Bird
Raised Fist0
PyTorchml~10 mins

Model optimization (quantization, pruning) in PyTorch - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply dynamic quantization to a PyTorch model.

PyTorch
import torch
import torch.nn as nn

model = nn.Linear(10, 5)
quantized_model = torch.quantization.[1](model, {nn.Linear})
Drag options to blanks, or click blank then click option'
Aquantize_static
Bquantize_dynamic
Cquantize_per_tensor
Dquantize_per_channel
Attempts:
3 left
💡 Hint
Common Mistakes
Using static quantization function instead of dynamic.
Passing wrong module types to the quantization function.
2fill in blank
medium

Complete the code to prune 20% of the weights in the first linear layer using L1 unstructured pruning.

PyTorch
import torch.nn.utils.prune as prune

prune.l1_unstructured(model.[1], name='weight', amount=0.2)
Drag options to blanks, or click blank then click option'
Abias
Blinear1
Clayer1
Dweight
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to prune the 'bias' parameter instead of 'weight'.
Using the layer name instead of the parameter name.
3fill in blank
hard

Fix the error in the code to remove pruning reparameterization from the linear layer.

PyTorch
prune.[1](model.linear, 'weight')
Drag options to blanks, or click blank then click option'
Aremove
Bunprune
Cclear
Dreset
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent functions like 'unprune' or 'clear'.
Trying to delete the layer instead of removing pruning.
4fill in blank
hard

Fill both blanks to apply global unstructured pruning to two layers with 30% sparsity.

PyTorch
parameters_to_prune = [(model.fc1, 'weight'), (model.fc2, 'weight')]
prune.[1](parameters_to_prune, pruning_method=prune.[2], amount=0.3)
Drag options to blanks, or click blank then click option'
Aglobal_unstructured
Bl1_unstructured
Crandom_unstructured
Dstructured
Attempts:
3 left
💡 Hint
Common Mistakes
Using structured pruning method with global pruning function.
Mixing pruning methods and functions incorrectly.
5fill in blank
hard

Fill all three blanks to create a quantized model, prepare it for static quantization, and convert it.

PyTorch
model.qconfig = torch.quantization.get_default_[1]_qconfig('fbgemm')
torch.quantization.[2](model, inplace=True)
quantized_model = torch.quantization.[3](model)
Drag options to blanks, or click blank then click option'
Aqconfig
Bprepare
Cconvert
Dcalibrate
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing 'calibrate' with 'prepare' or 'convert'.
Skipping the prepare step before convert.

Practice

(1/5)
1. What is the main goal of model pruning in PyTorch?
easy
A. Add more training data to improve accuracy
B. Increase the number of layers in the model
C. Change the model architecture to a different type
D. Remove less important weights to make the model smaller

Solution

  1. Step 1: Understand pruning concept

    Pruning means removing weights that do not contribute much to the model's output.
  2. Step 2: Identify pruning effect

    Removing these weights makes the model smaller and faster without changing its structure.
  3. Final Answer:

    Remove less important weights to make the model smaller -> Option D
  4. Quick Check:

    Pruning = Remove less important weights [OK]
Hint: Pruning cuts unimportant weights to shrink model size [OK]
Common Mistakes:
  • Thinking pruning adds layers
  • Confusing pruning with data augmentation
  • Believing pruning changes model type
2. Which PyTorch function is used to apply pruning to a layer?
easy
A. torch.nn.utils.prune.l1_unstructured
B. torch.quantization.quantize_dynamic
C. torch.optim.Adam
D. torch.nn.functional.relu

Solution

  1. Step 1: Identify pruning functions in PyTorch

    PyTorch pruning utilities are in torch.nn.utils.prune module.
  2. Step 2: Match pruning function

    l1_unstructured is a common pruning method that removes weights based on L1 norm.
  3. Final Answer:

    torch.nn.utils.prune.l1_unstructured -> Option A
  4. Quick Check:

    Pruning function = l1_unstructured [OK]
Hint: Pruning uses torch.nn.utils.prune functions [OK]
Common Mistakes:
  • Confusing pruning with quantization functions
  • Choosing optimizer functions by mistake
  • Selecting activation functions instead of pruning
3. What will be the output shape of the model's weight tensor after applying this pruning code?
import torch
import torch.nn.utils.prune as prune

layer = torch.nn.Linear(4, 3)
prune.l1_unstructured(layer, name='weight', amount=0.5)
print(layer.weight.shape)
medium
A. torch.Size([4, 3]) with half weights removed
B. torch.Size([3, 4]) with half weights removed physically
C. torch.Size([3, 4]) with some weights zeroed
D. torch.Size([4, 3]) unchanged

Solution

  1. Step 1: Check layer weight shape

    A Linear layer with input 4 and output 3 has weight shape (3, 4).
  2. Step 2: Understand pruning effect on weight tensor

    Pruning sets some weights to zero but does not change tensor shape.
  3. Final Answer:

    torch.Size([3, 4]) with some weights zeroed -> Option C
  4. Quick Check:

    Pruning zeros weights, shape stays same [OK]
Hint: Pruning zeros weights but keeps tensor shape [OK]
Common Mistakes:
  • Thinking pruning changes tensor shape
  • Confusing input/output dimensions order
  • Assuming weights are physically removed
4. Identify the error in this PyTorch pruning code:
import torch.nn.utils.prune as prune
layer = torch.nn.Linear(5, 2)
prune.l1_unstructured(layer, name='bias', amount=0.3)
medium
A. Missing import for torch
B. Layer input and output sizes are invalid
C. Amount must be an integer, not float
D. Cannot prune bias with l1_unstructured

Solution

  1. Step 1: Examine the code imports

    The code imports only prune but attempts to use torch.nn.Linear without importing torch.
  2. Step 2: Identify the runtime error

    This causes NameError: name 'torch' is not defined when creating the layer.
  3. Final Answer:

    Missing import for torch -> Option A
  4. Quick Check:

    Missing torch import causes NameError [OK]
Hint: Import torch before using torch.nn [OK]
Common Mistakes:
  • Overlooking missing torch import
  • Thinking pruning bias is unsupported
  • Assuming amount must be integer
5. You want to speed up inference on a PyTorch model by reducing number precision. Which approach should you use?
hard
A. Increase batch size during training
B. Apply dynamic quantization to convert weights to lower precision
C. Prune 90% of the model weights randomly
D. Add dropout layers to the model

Solution

  1. Step 1: Understand quantization purpose

    Quantization reduces number precision (e.g., float32 to int8) to speed up inference.
  2. Step 2: Identify correct method

    Dynamic quantization in PyTorch converts weights to lower precision without retraining.
  3. Step 3: Compare other options

    Pruning removes weights but may not speed inference as much; batch size and dropout affect training, not inference speed.
  4. Final Answer:

    Apply dynamic quantization to convert weights to lower precision -> Option B
  5. Quick Check:

    Quantization = lower precision for speed [OK]
Hint: Quantization reduces precision to speed inference [OK]
Common Mistakes:
  • Confusing pruning with quantization
  • Thinking batch size affects model speed directly
  • Adding dropout to speed inference
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard