"""Store symmetric INT8 weights and dequantize one layer at a time for inference.""" import torch from torch import nn from torch.nn.utils.parametrize import register_parametrization INT8_FORMAT = "symmetric-int8-per-row" def quantize_weights(weights: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: """Quantize matrix and convolution weights along their first (output) axis.""" result = {} for name, weight in weights.items(): if weight.ndim < 2: result[name] = weight.contiguous() continue # Use one FP32 scale per output row; zero rows keep a harmless unit scale. scale = weight.abs().amax(dim=tuple(range(1, weight.ndim)), keepdim=True) / 127 scale.masked_fill_(scale == 0, 1) prefix = name.removesuffix("weight") + "parametrizations.weight." result[prefix + "original"] = (weight / scale).round_().clamp_(-127, 127).to(torch.int8) result[prefix + "0.scale"] = scale return result class _DequantizeWeight(nn.Module): """Present a temporary FP32 weight to the existing PyTorch layer.""" def __init__(self, shape: tuple[int, ...], device: torch.device): super().__init__() self.register_buffer("scale", torch.empty((shape[0],) + (1,) * (len(shape) - 1), device=device)) def forward(self, weight: torch.Tensor) -> torch.Tensor: """Broadcast the row scales without keeping a float copy on the module.""" return weight.float().mul_(self.scale) def prepare_int8_model(model: nn.Module) -> None: """Install INT8 weight slots on a meta-device model before assigning saved tensors.""" for layer in model.modules(): if isinstance(layer, (nn.Linear, nn.Conv1d, nn.Embedding)): weight = layer.weight layer.weight = nn.Parameter(torch.empty_like(weight, dtype=torch.int8), requires_grad=False) register_parametrization(layer, "weight", _DequantizeWeight(weight.shape, weight.device), unsafe=True)