quantization
shrinkai.compression.quantization
Quantization: reducing the numerical precision of a model's weights/activations.
Quantizer (configured via QuantConfig) supports Post-Training Quantization
(PTQ, dynamic, or static when QuantConfig.calibrate_data is provided) and
Quantization-Aware Training (QAT, meant to be trained further, e.g. through a
shrinkai.distillation.Distiller, before calling Quantizer.finalize_qat).
Note
Built on torch.ao.quantization, which PyTorch has marked deprecated in
favor of torchao. It still works correctly today; migrating this module
once torchao's API has stabilized is a known follow-up.
Modules:
| Name | Description |
|---|---|
quantization |
The |
Classes:
| Name | Description |
|---|---|
QuantConfig |
Configuration parameters for model quantization. |
Quantizer |
Orchestrates the quantization of PyTorch models. |
Classes
QuantConfig
dataclass
Configuration parameters for model quantization.
This dataclass standardizes how quantization is applied across different backends and strategies. It defines the target bit-width and the mathematical approach used to compress the network.
Attributes:
| Name | Type | Description |
|---|---|---|
target_dtype |
str
|
The target data type for the model's weights. Currently supported options include: - "int8": 8-bit integer (Standard for CPU/Edge deployment). - "fp16": 16-bit float (Standard for GPU memory reduction). Defaults to "int8". |
strategy |
str
|
The quantization strategy to apply.
- "ptq" (Post-Training Quantization): Applies immediate mathematical
conversion to the weights. No gradient computation or training is required.
- "qat" (Quantization-Aware Training): Prepares the model with FakeQuantize
nodes. Requires subsequent training (e.g., via |
backend |
str
|
The underlying engine executing the quantization. - "torch": Native PyTorch quantization (fbgemm/qnnpack). Ideal for CNNs and small LMs. - "bitsandbytes": (Reserved for future LLM integration) Block-wise quantization. Defaults to "torch". |
calibrate_data |
Any | None
|
A dataloader (or any iterable of batches, each
either a plain input tensor or a |
Source code in src/shrinkai/compression/quantization/quantization.py
Quantizer
Orchestrates the quantization of PyTorch models.
The Quantizer reads a QuantConfig and safely modifies the computational graph
of a given PyTorch nn.Module. It handles the complexities of PyTorch's native
quantization APIs.
Equation
PTQ and QAT both rely on the affine (uniform) quantization scheme of Jacob et al. (2018):
where \(s > 0\) (scale) and \(z\) (zero-point) are derived from the observed
range of \(x\), via calibration on calibrate_data for static PTQ
activations, on the fly per-batch for dynamic PTQ, or from weight
statistics directly, and \([q_{min}, q_{max}]\) bounds the target integer
range (e.g. \([-128, 127]\) for int8). PyTorch's default backends use
\(z = 0\) (symmetric) for weights and the full affine form for activations.
For QAT, this same round-trip is simulated in the forward pass ("Fake
Quantization") while gradients flow through it via the straight-through
estimator (\(\partial q / \partial x \approx 1\) inside \([x_{min}, x_{max}]\),
\(0\) outside), letting the model adapt its weights to the quantization
noise before finalize_qat() converts it to real integer weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
QuantConfig
|
The configuration object defining the quantization rules. |
required |
Methods:
| Name | Description |
|---|---|
apply |
Applies the selected quantization strategy to the model. |
benchmark |
Runs complete profiling suite on original and quantized models. |
finalize_qat |
To be called AFTER the distillation training loop (distiller.fit). |
Source code in src/shrinkai/compression/quantization/quantization.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
Methods:
apply
Applies the selected quantization strategy to the model.
Depending on config.strategy, this method will either immediately convert
the weights (PTQ) or insert FakeQuantize nodes for future training (QAT).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The standard, full-precision PyTorch model. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The modified model. If PTQ, it is ready for deployment. |
Module
|
If QAT, it must be trained and then passed to |
Source code in src/shrinkai/compression/quantization/quantization.py
benchmark
benchmark(
original_model: Module,
quantized_model: Module,
sample_input: Tensor,
original_name: str = "Original (FP32)",
quantized_name: str = "Quantized",
val_dataloader: DataLoader | None = None,
device: str | device = "cpu",
) -> BenchmarkReport
Runs complete profiling suite on original and quantized models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_model
|
Module
|
The base FP32 PyTorch model. |
required |
quantized_model
|
Module
|
The model returned by |
required |
sample_input
|
Tensor
|
Batch tensor matching target inference dimension. |
required |
original_name
|
str
|
Display label for the original model. |
'Original (FP32)'
|
quantized_name
|
str
|
Display label for the quantized model. |
'Quantized'
|
val_dataloader
|
DataLoader | None
|
Optional dataloader to compute final accuracy metrics. |
None
|
device
|
str | device
|
Device to run the benchmark on (default "cpu", as INT8 is often CPU-optimized). |
'cpu'
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Structured benchmark report ready for |
Source code in src/shrinkai/compression/quantization/quantization.py
finalize_qat
staticmethod
To be called AFTER the distillation training loop (distiller.fit). Converts the simulated FakeQuantize nodes into actual quantized weights (e.g., int8).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qat_model
|
Module
|
The model trained with FakeQuantize nodes. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The fully quantized model. |