Bird
Raised Fist0
Computer Visionml~12 mins

Model optimization (pruning, quantization) in Computer Vision - Model Pipeline Trace

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
Model Pipeline - Model optimization (pruning, quantization)

This pipeline shows how a computer vision model is made smaller and faster using pruning and quantization. These steps help the model run well on devices like phones without losing much accuracy.

Data Flow - 7 Stages
1Original Data Input
1000 images x 64 x 64 pixels x 3 color channelsRaw images loaded for training1000 images x 64 x 64 x 3
Image of a cat with RGB pixel values
2Preprocessing
1000 images x 64 x 64 x 3Normalize pixel values to 0-1 range1000 images x 64 x 64 x 3
Pixel value 128 becomes 0.5
3Feature Extraction
1000 images x 64 x 64 x 3Convolutional layers extract features1000 images x 16 x 16 x 32 feature maps
Edges and shapes detected in images
4Model Training
1000 images x 16 x 16 x 32Train CNN classifierTrained model weights
Weights learned to recognize cats and dogs
5Pruning
Trained model weightsRemove 30% of smallest weights (set to zero)Smaller model with sparse weights
Weights near zero removed to reduce size
6Quantization
Pruned model weights (float32)Convert weights from float32 to int8Smaller model weights in int8 format
Weight 0.123 float32 becomes 12 int8
7Optimized Model
Quantized model weightsModel ready for fast inference on deviceCompressed model with reduced size
Model size reduced from 20MB to 7MB
Training Trace - Epoch by Epoch

Epochs
1 |***************
3 |********************
5 |*************************
7 |******************************
10|********************************
Loss
1.2|***************
0.8|************
0.5|*******
0.4|*****
0.35|****
EpochLoss ↓Accuracy ↑Observation
11.20.55Model starts learning basic features
30.80.70Accuracy improves as model learns patterns
50.50.82Model converging with good accuracy
70.40.87Loss decreases steadily, accuracy rises
100.350.90Training stabilizes with high accuracy
Prediction Trace - 5 Layers
Layer 1: Input Image
Layer 2: Convolutional Layer
Layer 3: Pruned Weights Applied
Layer 4: Quantized Weights Applied
Layer 5: Output Layer (Softmax)
Model Quiz - 3 Questions
Test your understanding
What is the main purpose of pruning in this model pipeline?
AIncrease the number of model layers
BRemove less important weights to reduce model size
CConvert weights to integers
DNormalize input images
Key Insight
Pruning and quantization help make computer vision models smaller and faster with little loss in accuracy. This allows models to run efficiently on devices with limited resources.

Practice

(1/5)
1. What is the main goal of model pruning in computer vision?
easy
A. To remove less important parts of the model to reduce size
B. To increase the number of layers in the model
C. To add more training data for better accuracy
D. To convert the model to a different programming language

Solution

  1. Step 1: Understand pruning concept

    Pruning means removing parts of the model that contribute less to its output.
  2. Step 2: Identify pruning goal

    The goal is to reduce model size and speed up inference by cutting unnecessary parts.
  3. Final Answer:

    To remove less important parts of the model to reduce size -> Option A
  4. Quick Check:

    Pruning = Remove less important parts [OK]
Hint: Pruning cuts unneeded parts to shrink model size [OK]
Common Mistakes:
  • Thinking pruning adds layers instead of removing
  • Confusing pruning with data augmentation
  • Believing pruning changes programming language
2. Which of the following is the correct way to apply quantization in TensorFlow Lite?
easy
A. model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
B. converter.optimizations = [tf.lite.Optimize.DEFAULT]
C. model.compile(optimizer='adam', loss='mse')
D. model.fit(x_train, y_train, epochs=10)

Solution

  1. Step 1: Identify quantization syntax

    In TensorFlow Lite, quantization is enabled by setting converter.optimizations to Optimize.DEFAULT.
  2. Step 2: Check other options

    model = tf.lite.TFLiteConverter.from_keras_model(model).convert() converts model but does not enable quantization. Options B and C are training commands, not quantization.
  3. Final Answer:

    converter.optimizations = [tf.lite.Optimize.DEFAULT] -> Option B
  4. Quick Check:

    Quantization flag = converter.optimizations [OK]
Hint: Quantization needs converter.optimizations set to Optimize.DEFAULT [OK]
Common Mistakes:
  • Confusing model conversion with quantization
  • Using training commands instead of conversion flags
  • Missing the optimization setting for quantization
3. Given this PyTorch pruning code snippet, what will be the output size of the model's first linear layer weights after pruning 20% of connections?
import torch
import torch.nn.utils.prune as prune

model = torch.nn.Sequential(
    torch.nn.Linear(100, 50),
    torch.nn.ReLU()
)
prune.l1_unstructured(model[0], name='weight', amount=0.2)
pruned_weights = model[0].weight
print((pruned_weights != 0).sum().item())
medium
A. 8000
B. 5000
C. 10000
D. 4000

Solution

  1. Step 1: Calculate total weights

    The first linear layer has 100 inputs and 50 outputs, so total weights = 100 * 50 = 5000.
  2. Step 2: Calculate remaining weights after pruning

    Pruning 20% removes 20% of weights, so remaining weights = 80% of 5000 = 4000.
  3. Step 3: Understand pruning method

    PyTorch's l1_unstructured pruning does not remove weights but masks them, so the weight tensor size remains 5000, but the number of non-zero weights is 4000.
  4. Step 4: Check print output

    The print statement counts non-zero weights, so output is 4000.
  5. Final Answer:

    4000 -> Option D
  6. Quick Check:

    5000 * 0.8 = 4000 [OK]
Hint: Remaining weights = total * (1 - pruning amount) [OK]
Common Mistakes:
  • Calculating total weights incorrectly
  • Using pruning amount as remaining instead of removed
  • Confusing layer input/output dimensions
4. You tried to quantize a model but got an error: AttributeError: 'TFLiteConverter' object has no attribute 'optimizations'. What is the likely cause?
medium
A. Quantization requires training the model again
B. Model is too large to quantize
C. Using an outdated TensorFlow version without quantization support
D. The model has no weights to quantize

Solution

  1. Step 1: Understand the error

    The error says the converter object lacks 'optimizations' attribute, meaning the TensorFlow version is old.
  2. Step 2: Identify cause

    Older TensorFlow versions do not support the 'optimizations' attribute needed for quantization.
  3. Final Answer:

    Using an outdated TensorFlow version without quantization support -> Option C
  4. Quick Check:

    Missing attribute = outdated TensorFlow [OK]
Hint: Check TensorFlow version supports quantization features [OK]
Common Mistakes:
  • Assuming model size causes attribute error
  • Thinking quantization needs retraining always
  • Believing model without weights causes this error
5. You want to deploy a computer vision model on a mobile device with limited memory and CPU. Which combination of optimization techniques is best to reduce model size and speed up inference without much accuracy loss?
hard
A. Apply pruning to remove unimportant weights, then quantize weights to 8-bit integers
B. Only increase model layers to improve accuracy
C. Use full precision weights and no pruning for best accuracy
D. Train longer without any model size changes

Solution

  1. Step 1: Understand device constraints

    Mobile devices have limited memory and CPU, so model size and speed matter.
  2. Step 2: Choose optimization techniques

    Pruning removes unnecessary weights reducing size; quantization reduces number precision speeding inference.
  3. Step 3: Combine pruning and quantization

    Using both together reduces size and speeds up model with minimal accuracy loss.
  4. Final Answer:

    Apply pruning to remove unimportant weights, then quantize weights to 8-bit integers -> Option A
  5. Quick Check:

    Pruning + quantization = smaller, faster model [OK]
Hint: Combine pruning and quantization for efficient mobile models [OK]
Common Mistakes:
  • Only increasing layers without optimization
  • Ignoring quantization benefits
  • Assuming full precision is always best for deployment