Skip to content

llmcompressor.modifiers.quantization.quantization.base

Classes:

  • QuantizationModifier –

    Enables post training quantization (PTQ) and quantization aware training (QAT) for a

QuantizationModifier

Bases: Modifier, QuantizationMixin

Enables post training quantization (PTQ) and quantization aware training (QAT) for a given module or its submodules. After calibration (PTQ) or the start epoch (QAT), the specified module(s) forward pass will emulate quantized execution and the modifier will be enabled until training is completed.

In DDP mode, activation observer statistics are all-reduced across ranks at sequential layer boundaries so all ranks share identical quantization parameters.

Parameters:

  • config_groups –

    dictionary specifying quantization schemes to apply to target modules. Modules not matching a scheme target will NOT be quantized.

  • targets –

    list of layer names to quantize if a scheme is provided. Defaults to Linear layers

  • ignore –

    optional list of module class names or submodule names to not quantize even if they match a target in config_groups. Defaults to empty list.

  • scheme –

    a single quantization scheme to apply to the model. This is a dictionary that supports all keys from QuantizationScheme except targets, which will be set to the targets parameter set at the modifier level. Can also be set to a dictionary of the format preset_scheme_name: targets for example: W8A8: ['Linear'] for weight and activation 8-bit.

  • kv_cache_scheme –

    optional QuantizationArgs, that specify the quantization of the kv cache. If None, kv cache is not quantized. When applying kv cache quantization to transformer AutoModelForCausalLM, the kv_cache_scheme gets converted into a QuantizationScheme that: - targets the q_proj and k_proj modules of the model. The outputs of those modules are the keys and values that might be cached - quantizes the outputs of the aforementioned layers, so that keys and values are compressed before storing them in the cache There is an explicit assumption that the model contains modules with k_proj and v_proj in their names. If this is not the case and kv_cache_scheme != None, the quantization of kv cache will fail

Methods:

estimate_sequential_memory

estimate_sequential_memory(
    module: Module, num_tokens: int
) -> tuple[int, int]

Observers keep only small per-module statistics, but observing a weight when its subgraph ends may need a full precision copy of it

Parameters:

  • module (Module) –

    module belonging to the subgraph being calibrated

  • num_tokens (int) –

    number of calibration tokens, unused

Returns:

  • tuple[int, int] –

    tuple of (held, scratch) bytes

Source code in src/llmcompressor/modifiers/quantization/quantization/base.py
def estimate_sequential_memory(
    self, module: torch.nn.Module, num_tokens: int
) -> tuple[int, int]:
    """
    Observers keep only small per-module statistics, but observing a weight when
    its subgraph ends may need a full precision copy of it

    :param module: module belonging to the subgraph being calibrated
    :param num_tokens: number of calibration tokens, unused
    :return: tuple of (held, scratch) bytes
    """
    weight = getattr(module, "weight", None)
    if weight is None or not is_module_quantized(module):
        return 0, 0

    return 0, weight.numel() * torch.float32.itemsize

on_calibration_end

on_calibration_end(state: State, event: Event, **kwargs)

Finish calibrating by removing observers and calibration hooks.

Skipped when layerwise_decompression is enabled; per-layer cleanup is handled in on_sequential_epoch_end.

Source code in src/llmcompressor/modifiers/quantization/quantization/base.py
def on_calibration_end(self, state: State, event: Event, **kwargs):
    """
    Finish calibrating by removing observers and calibration hooks.

    Skipped when layerwise_decompression is enabled; per-layer cleanup
    is handled in on_sequential_epoch_end.
    """
    if not getattr(state, "layerwise_decompression", False):
        QuantizationMixin.end_calibration(self, state.model)

on_calibration_start

on_calibration_start(state: State, event: Event, **kwargs)

Begin calibrating activations.

Skipped when layerwise_decompression is enabled; per-layer calibration setup is handled by start_layerwise_calibration in the pipeline.

Source code in src/llmcompressor/modifiers/quantization/quantization/base.py
def on_calibration_start(self, state: State, event: Event, **kwargs):
    """
    Begin calibrating activations.

    Skipped when layerwise_decompression is enabled; per-layer calibration
    setup is handled by start_layerwise_calibration in the pipeline.
    """
    if not getattr(state, "layerwise_decompression", False):
        QuantizationMixin.start_calibration(self, state.model)

on_initialize

on_initialize(state: State, **kwargs) -> bool

Prepare to calibrate activations and weights

According to the quantization config, a quantization scheme is attached to each targeted module. The module's forward call is also overwritten to perform quantization to inputs, weights, and outputs.

Then, according to the module's quantization scheme, observers and calibration hooks are added. These hooks are disabled until the modifier starts.

Skipped when layerwise_decompression is enabled because modules are still compressed; per-layer setup happens in start_layerwise_calibration instead.

Source code in src/llmcompressor/modifiers/quantization/quantization/base.py
def on_initialize(self, state: State, **kwargs) -> bool:
    """
    Prepare to calibrate activations and weights

    According to the quantization config, a quantization scheme is attached to each
    targeted module. The module's forward call is also overwritten to perform
    quantization to inputs, weights, and outputs.

    Then, according to the module's quantization scheme, observers and calibration
    hooks are added. These hooks are disabled until the modifier starts.

    Skipped when layerwise_decompression is enabled because modules are still
    compressed; per-layer setup happens in start_layerwise_calibration instead.
    """
    if not QuantizationMixin.has_config(self):
        raise ValueError(
            "QuantizationModifier requires that quantization fields be specified"
        )
    if not getattr(state, "layerwise_decompression", False):
        QuantizationMixin.initialize_quantization(self, state)

    return True