When optimizing models by quantization or pruning, the key metrics to watch are model accuracy and inference latency. Accuracy tells us if the model still makes good predictions after optimization. Latency shows how fast the model runs, which is often the goal of optimization. We also check model size to see how much memory is saved. Balancing these metrics helps us keep the model useful while making it smaller and faster.
Model optimization (quantization, pruning) in PyTorch - Model Metrics & Evaluation
Original model confusion matrix:
TP=90 FP=10
FN=5 TN=95
After pruning:
TP=85 FP=15
FN=10 TN=90
Total samples = 200
Precision before pruning = 90 / (90 + 10) = 0.9
Recall before pruning = 90 / (90 + 5) = 0.947
Precision after pruning = 85 / (85 + 15) = 0.85
Recall after pruning = 85 / (85 + 10) = 0.895
This shows a slight drop in precision and recall after pruning, which is common but should be minimal.
Quantization and pruning reduce model size and speed up inference but can lower accuracy. For example:
- Quantization: Converts weights from 32-bit floats to 8-bit integers. This shrinks model size and speeds up calculations but may cause small accuracy loss.
- Pruning: Removes less important connections. This reduces size and computation but can remove useful information, lowering accuracy.
We must decide how much accuracy loss is acceptable for the gain in speed and size. For mobile apps, smaller and faster models are often worth a small accuracy drop.
Good:
- Accuracy drop < 1-2% after optimization
- Model size reduced by 50% or more
- Inference latency reduced by 30% or more
Bad:
- Accuracy drops more than 5%
- Minimal size or speed improvement
- Model becomes unstable or unpredictable
- Ignoring accuracy drop: Focusing only on size/speed can break the model.
- Data leakage: Testing on data seen during training can hide accuracy loss.
- Overfitting to optimization: Tweaking too much on test data can give false confidence.
- Not measuring latency on target device: Speed gains on desktop may not appear on mobile.
Your model after pruning has 98% accuracy but recall on the positive class dropped to 12%. Is it good for production? Why or why not?
Answer: No, it is not good. Even though overall accuracy is high, the very low recall means the model misses most positive cases. For example, if detecting fraud, missing 88% of fraud cases is dangerous. High recall is critical in such tasks.
Practice
model pruning in PyTorch?Solution
Step 1: Understand pruning concept
Pruning means removing weights that do not contribute much to the model's output.Step 2: Identify pruning effect
Removing these weights makes the model smaller and faster without changing its structure.Final Answer:
Remove less important weights to make the model smaller -> Option DQuick Check:
Pruning = Remove less important weights [OK]
- Thinking pruning adds layers
- Confusing pruning with data augmentation
- Believing pruning changes model type
Solution
Step 1: Identify pruning functions in PyTorch
PyTorch pruning utilities are intorch.nn.utils.prunemodule.Step 2: Match pruning function
l1_unstructuredis a common pruning method that removes weights based on L1 norm.Final Answer:
torch.nn.utils.prune.l1_unstructured -> Option AQuick Check:
Pruning function = l1_unstructured [OK]
- Confusing pruning with quantization functions
- Choosing optimizer functions by mistake
- Selecting activation functions instead of pruning
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)
Solution
Step 1: Check layer weight shape
A Linear layer with input 4 and output 3 has weight shape (3, 4).Step 2: Understand pruning effect on weight tensor
Pruning sets some weights to zero but does not change tensor shape.Final Answer:
torch.Size([3, 4]) with some weights zeroed -> Option CQuick Check:
Pruning zeros weights, shape stays same [OK]
- Thinking pruning changes tensor shape
- Confusing input/output dimensions order
- Assuming weights are physically removed
import torch.nn.utils.prune as prune layer = torch.nn.Linear(5, 2) prune.l1_unstructured(layer, name='bias', amount=0.3)
Solution
Step 1: Examine the code imports
The code imports only prune but attempts to use torch.nn.Linear without importing torch.Step 2: Identify the runtime error
This causes NameError: name 'torch' is not defined when creating the layer.Final Answer:
Missing import for torch -> Option AQuick Check:
Missing torch import causes NameError [OK]
- Overlooking missing torch import
- Thinking pruning bias is unsupported
- Assuming amount must be integer
Solution
Step 1: Understand quantization purpose
Quantization reduces number precision (e.g., float32 to int8) to speed up inference.Step 2: Identify correct method
Dynamic quantization in PyTorch converts weights to lower precision without retraining.Step 3: Compare other options
Pruning removes weights but may not speed inference as much; batch size and dropout affect training, not inference speed.Final Answer:
Apply dynamic quantization to convert weights to lower precision -> Option BQuick Check:
Quantization = lower precision for speed [OK]
- Confusing pruning with quantization
- Thinking batch size affects model speed directly
- Adding dropout to speed inference
Ready to prove it?
Pass the test and this pattern moves unknown
