Code QuizAdvanced

Dynamic Quantization Before Inference

Spot why calling eval() on the wrong object leaves the quantized model in the wrong mode.

Codepython
import torch
from torch.quantization import quantize_dynamic

model = load_trained_model()  # a trained nn.Module

# Quantize Linear layers to int8 for faster CPU inference
quantized = quantize_dynamic(
    model, {torch.nn.Linear}, dtype=torch.qint8
)

model.eval()  # switch to inference mode

with torch.no_grad():
    output = quantized(sample_input)

What is the bug in this code?

Watch the code walkthrough

Watch on YouTube →