Bird
Raised Fist0
NLPml~20 mins

Model optimization (distillation, quantization) in NLP - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Model Optimization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Understanding Model Distillation Purpose

What is the main goal of model distillation in NLP?

ATo train a smaller model to mimic a larger model's behavior
BTo increase the number of parameters in the model for better accuracy
CTo add noise to the training data to improve robustness
DTo convert a model into a rule-based system
Attempts:
2 left
💡 Hint

Think about how a big model can help a smaller one learn.

Predict Output
intermediate
2:00remaining
Output of Quantization Code Snippet

What is the output shape of the quantized model's embedding layer weights after applying 8-bit quantization?

NLP
import torch
import torch.nn as nn

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = nn.Embedding(1000, 64)

model = SimpleModel()
quantized_model = torch.quantization.quantize_dynamic(
    model, {nn.Embedding}, dtype=torch.qint8
)
weight_shape = quantized_model.embedding.weight.shape
print(weight_shape)
AAttributeError
B(64, 1000)
C(1000, 32)
D(1000, 64)
Attempts:
2 left
💡 Hint

Quantization changes data type but not tensor shape.

Model Choice
advanced
2:00remaining
Choosing a Model for Distillation

You want to distill a large BERT model into a smaller one for mobile deployment. Which student model architecture is best suited?

AA recurrent neural network with LSTM cells
BA convolutional neural network designed for images
CA smaller BERT model with fewer layers and parameters
DA large transformer model with more layers than the teacher
Attempts:
2 left
💡 Hint

Student model should be similar but smaller than the teacher.

Hyperparameter
advanced
1:30remaining
Key Hyperparameter in Quantization

Which hyperparameter is critical to set correctly when applying post-training quantization to an NLP model?

AThe learning rate of the optimizer
BThe number of bits used to represent weights and activations
CThe dropout rate in the model layers
DThe batch size during training
Attempts:
2 left
💡 Hint

Quantization precision depends on this setting.

Metrics
expert
2:30remaining
Evaluating Distilled Model Performance

After distilling a large NLP model, which metric best shows if the smaller model retained the teacher's knowledge effectively?

AAccuracy on a held-out validation set compared to the teacher model
BTraining loss of the student model on the training data
CNumber of parameters in the student model
DInference time on a GPU
Attempts:
2 left
💡 Hint

Think about measuring how well the student predicts compared to the teacher.

Practice

(1/5)
1. What is the main goal of model distillation in NLP?
easy
A. To increase the number of layers in a neural network
B. To add more training data for better accuracy
C. To convert text data into numerical vectors
D. To train a smaller model to mimic a larger model's behavior

Solution

  1. Step 1: Understand model distillation concept

    Model distillation is about making a smaller model learn from a bigger, well-trained model.
  2. Step 2: Identify the goal of distillation

    The goal is to keep performance while reducing model size and complexity.
  3. Final Answer:

    To train a smaller model to mimic a larger model's behavior -> Option D
  4. Quick Check:

    Distillation = smaller model copies bigger model [OK]
Hint: Distillation means small model learns from big model [OK]
Common Mistakes:
  • Confusing distillation with adding layers
  • Thinking distillation increases data size
  • Mixing distillation with data preprocessing
2. Which of the following is the correct way to apply quantization to a model's weights in Python using PyTorch?
easy
A. model.quantize(weights=True)
B. torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
C. torch.quantize(model, dtype=torch.float32)
D. torch.quantization(model, dtype=torch.int32)

Solution

  1. Step 1: Recall PyTorch quantization syntax

    PyTorch uses torch.quantization.quantize_dynamic for dynamic quantization on layers like Linear.
  2. Step 2: Check correct function and parameters

    torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8) correctly calls quantize_dynamic with model, target layers, and dtype torch.qint8.
  3. Final Answer:

    torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8) -> Option B
  4. Quick Check:

    PyTorch quantize_dynamic with Linear and qint8 = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8) [OK]
Hint: Use torch.quantization.quantize_dynamic for quantization [OK]
Common Mistakes:
  • Using non-existent torch.quantize function
  • Passing wrong dtype like float32 instead of qint8
  • Calling quantization as a model method
3. Given the following code snippet for distillation, what will be the output loss value if the student model perfectly mimics the teacher model's outputs?
teacher_outputs = torch.tensor([0.1, 0.9])
student_outputs = torch.tensor([0.1, 0.9])
loss_fn = torch.nn.MSELoss()
loss = loss_fn(student_outputs, teacher_outputs)
print(loss.item())
medium
A. 0.0
B. 0.5
C. 1.0
D. Cannot compute due to shape mismatch

Solution

  1. Step 1: Understand MSELoss calculation

    MSELoss calculates mean squared error between student and teacher outputs.
  2. Step 2: Calculate loss for identical outputs

    Since student_outputs equals teacher_outputs, difference is zero, so loss is 0.0.
  3. Final Answer:

    0.0 -> Option A
  4. Quick Check:

    Identical outputs give zero MSE loss [OK]
Hint: Same outputs mean zero loss in MSE [OK]
Common Mistakes:
  • Assuming loss is 1.0 by default
  • Confusing loss with accuracy
  • Thinking shape mismatch error occurs
4. You tried to quantize a model but got an error: AttributeError: 'MyModel' object has no attribute 'quantize'. What is the likely cause?
medium
A. The model class does not have a built-in quantize method
B. You forgot to import torch
C. Quantization only works on CPU, not GPU
D. The model is already quantized

Solution

  1. Step 1: Analyze the error message

    The error says the model object lacks a 'quantize' method, meaning it is not defined.
  2. Step 2: Understand quantization usage

    Quantization is applied via PyTorch functions, not as a model method, so calling model.quantize() causes error.
  3. Final Answer:

    The model class does not have a built-in quantize method -> Option A
  4. Quick Check:

    Quantize is a function, not a model method [OK]
Hint: Quantize via torch functions, not model methods [OK]
Common Mistakes:
  • Trying to call quantize as model.quantize()
  • Ignoring import errors
  • Assuming quantization only works on CPU
5. You want to deploy a chatbot on a mobile device with limited memory and CPU. Which combination of model optimization techniques is best to reduce size and speed up inference without losing much accuracy?
hard
A. Use quantization first, then retrain the large model from scratch
B. Only increase the training data size to improve accuracy
C. Use distillation to train a smaller model, then apply quantization to reduce precision
D. Add more layers to the model and use float64 precision

Solution

  1. Step 1: Identify constraints and goals

    Mobile devices need small, fast models with good accuracy.
  2. Step 2: Choose suitable optimization techniques

    Distillation creates a smaller model; quantization reduces number precision to save space and speed up inference.
  3. Step 3: Combine techniques for best effect

    Using distillation first then quantization is a common, effective approach.
  4. Final Answer:

    Use distillation to train a smaller model, then apply quantization to reduce precision -> Option C
  5. Quick Check:

    Distillation + quantization = small, fast, accurate model [OK]
Hint: Distill first, then quantize for mobile deployment [OK]
Common Mistakes:
  • Ignoring quantization for mobile
  • Adding layers increases size and slows down
  • Retraining large model after quantization wastes effort