This guide demonstrates how to load a model (e.g., Llama 3 8B), apply round-to-nearest (RTN) MXFP4 weight quantization, compute scales directly from weights (no calibration data required), and save the compressed model.
Workflow:
- Load Model: Use
AutoModelForCausalLM. - Configure Quantization: Use
QuantizationConfig to define the scheme (e.g., MXFP4) and target layers (e.g., Linear), while specifying layers to ignore (e.g., lm_head). - Apply Config: Call
apply_quantization_config(model, config) to attach a QuantizationScheme to targeted modules. - Compute Scales: Iterate through modules, extract weights, and use
calculate_qparams to find scales based on min/max values (optionally using group_size). Update the module using update_offload_parameter. - Compress and Save: Use
ModelCompressor.from_pretrained_model(model) to initialize a compressor, call compressor.compress_model(model), save the model, and finally call compressor.update_config(output_dir) to update the config.json with the necessary quantization metadata.
model_name = "meta-llama/Meta-Llama-3-8B"
device = "cuda:0" if torch.cuda.is_available() else "cpu"
# Load the model
model = AutoModelForCausalLM.from_pretrained(
model_name, device_map=device, torch_dtype="auto"
)
# Set-up the quantization config.
config = QuantizationConfig(
config_groups={"MXFP4": ["Linear"]},
ignore=["lm_head"],
)
apply_quantization_config(model, config)
# Compute weight scales using round-to-nearest quantization
for name, module in model.named_modules():
scheme = getattr(module, "quantization_scheme", None)
if scheme is None or scheme.weights is None:
continue
weight = module.weight.data
args = scheme.weights
group_size = args.group_size
if group_size is not None and group_size > 0:
reshaped = weight.unflatten(-1, (math.ceil(weight.shape[-1] / group_size), group_size))
min_val = reshaped.amin(dim=-1)
max_val = reshaped.amax(dim=-1)
else:
min_val, max_val = torch.aminmax(weight)
scale, _ = calculate_qparams(min_val, max_val, args)
update_offload_parameter(module, "weight_scale", scale)
output_dir = "./Meta-Llama-3-8B-MXFP4"
compressor = ModelCompressor.from_pretrained_model(model)
compressor.compress_model(model)
model.save_pretrained(output_dir)
compressor.update_config(output_dir)