MCPcopy Create free account
hub / github.com/pytorch/executorch / quantize_model

Function quantize_model

examples/models/gemma4_31b/quant/quantize.py:282–313  ·  view source on GitHub ↗

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,
)

Source from the content-addressed store, hash-verified

280
281
282def 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

Callers 15

mainFunction · 0.90
load_and_quantizeFunction · 0.90
test_applies_recipeMethod · 0.90
test_empty_modelMethod · 0.90
save_checkpointFunction · 0.90
test_pack_for_mlxMethod · 0.90

Calls 5

quantize_weightFunction · 0.85
keysMethod · 0.80
named_parametersMethod · 0.80
get_configMethod · 0.45
toMethod · 0.45