Walk model parameters + persistent buffers, apply recipe. Returns a single state dict containing quantized tensor subclasses (``Int4Tensor``, ``IntxUnpackedToInt8Tensor``) and unquantized plain tensors. Non-persistent buffers (KV cache, RoPE tables) are excluded.
(
model: nn.Module,
recipe: QuantRecipe,
dtype: torch.dtype = torch.bfloat16,
verbose: bool = False,
)
| 280 | |
| 281 | |
| 282 | def quantize_model( |
| 283 | model: nn.Module, |
| 284 | recipe: QuantRecipe, |
| 285 | dtype: torch.dtype = torch.bfloat16, |
| 286 | verbose: bool = False, |
| 287 | ) -> dict[str, torch.Tensor]: |
| 288 | """Walk model parameters + persistent buffers, apply recipe. |
| 289 | |
| 290 | Returns a single state dict containing quantized tensor subclasses |
| 291 | (``Int4Tensor``, ``IntxUnpackedToInt8Tensor``) and unquantized plain |
| 292 | tensors. Non-persistent buffers (KV cache, RoPE tables) are excluded. |
| 293 | """ |
| 294 | state: dict[str, torch.Tensor] = {} |
| 295 | persistent_keys = set(model.state_dict().keys()) |
| 296 | |
| 297 | n_params = sum(1 for _ in model.named_parameters()) |
| 298 | for i, (fqn, param) in enumerate(model.named_parameters()): |
| 299 | config = recipe.get_config(fqn) |
| 300 | if config is None: |
| 301 | state[fqn] = param.data.to(dtype) |
| 302 | else: |
| 303 | state[fqn] = quantize_weight(param.data, config) |
| 304 | if verbose: |
| 305 | print(f" Quantized {i + 1}/{n_params}: {fqn}", end="\r") |
| 306 | if verbose: |
| 307 | print() |
| 308 | |
| 309 | for fqn, buf in model.named_buffers(): |
| 310 | if fqn in persistent_keys and fqn not in state: |
| 311 | state[fqn] = buf.data |
| 312 | |
| 313 | return state |