Quantization¶
quantization
¶
Symmetric per-tensor quantization for training and compression.
uniform_quantize
¶
Fake-quantize model parameters in place and return their integer codes.
Each parameter w becomes clamp(round(s * w), -quant_max, quant_max) / s,
with s = quant_max / max(abs(w)), or s = 1 for an all-zero tensor. Complex
parameters are unsupported.
Parameters:
-
model(Module) –Module to quantize in place; pass a copy to keep the original weights.
-
quant_max(int) –Largest integer level, less than
2**63; codes use the smallest signed integer dtype that holds it.
Returns:
-
tuple[Module, dict[str, dict[str, Tensor]]]–The same model and a dictionary mapping parameter names to
{"quant": codes, "scale": s}, both detached CPU tensors.
Examples:
>>> model, codes = uniform_quantize(nn.Linear(2, 3), quant_max=127)
>>> codes["weight"]["quant"].dtype
torch.int8
>>> restored = uniform_dequantize(nn.Linear(2, 3), codes)
>>> restored.weight.equal(model.weight)
True
Source code in inro/quantization.py
uniform_dequantize
¶
Load parameters from uniform_quantize codes in place.
Parameters:
-
model(Module) –Module to overwrite in place.
-
model_dict(dict[str, dict[str, Tensor]]) –Codes and scales of every parameter of
model, by name.
Returns:
-
Module–The same model, each parameter being
quant.float() / scale.float().