llmcompressor.observers
Framework for monitoring and analyzing model behavior during compression.
Provides observers for tracking tensor statistics, activation ranges, and model behavior during compression workflows. Includes min-max observers, MSE observers, and helper utilities for quantization and other compression techniques.
Modules:
-
base– -
fused_mappings– -
fusion– -
grid_search–Shared eager and Triton grid-search implementation for quantization observers.
-
helpers–Helper functions for observer token counting and analysis.
-
imatrix– -
min_max– -
mse–
Classes:
-
FusedMapping–Layers that vLLM loads into a single packed weight. Packed layers must be
-
FusionHandler–Manages fusion bookkeeping for a single Observer.
-
IMatrixMSEObserver–MSE observer weighted by per-input-channel importance (E[x²]).
-
MemorylessMinMaxObserver–Compute quantization parameters by taking the min/max of the observed value.
-
MinMaxObserver–Compute quantization parameters by taking the moving average of min/max values.
-
MovingAverageMSEObserver–Compute quantization parameters by finding the optimal min/max values which minimize
-
Observer–Base class for observers which compute quantization parameters given
-
QParamsDict–Dictionary containing quantization parameters.
-
StaticMinMaxObserver–Compute quantization parameters by taking the min/max of all observed values.
Functions:
-
flatten_for_calibration–Reshapes the value according to the quantization strategy for the purposes of
-
fuse_weight_observers–Link weight observers across fused layer groups for shared global_scale.
-
get_fused_layers–Find the fused groups among the layers of one parent module, as defined by
-
resolve_fused_names–Resolve the fused groups among the layers present under one parent module.
FusedMapping
dataclass
Layers that vLLM loads into a single packed weight. Packed layers must be quantized the same way and, for TENSOR_GROUP schemes (e.g. NVFP4), must share one global_scale.
Names are paths relative to the layers' common parent module. They are matched against transformers module attributes (oneshot) and against checkpoint weight names (model_free_ptq). Where the two namings differ, the fusion is listed once per naming.
Parameters:
-
fused_name(str) –name of the packed module in vLLM, for reference
-
names(tuple[str, ...]) –layers that are always packed. The mapping applies to a parent only when all of these are present
-
optional_names(tuple[str, ...], default:()) –layers that are packed only in some model configurations. When the mapping applies, those present join the group
FusionHandler
Manages fusion bookkeeping for a single Observer.
Every Observer gets a FusionHandler at init time. When observers are fused (e.g. Q/K/V sharing a global_scale), FusionHandler.fuse() links their handlers together and stores weak refs to the modules whose weights may need lazy observation.
Methods:
-
fuse–Link all observers in the iterable with each other for shared global_scale.
-
get_fused_statistics–Returns statistics for every observer in the fusion group
-
maybe_delete_statistics–Cooperative statistics deletion. Each handler calls this when it
Source code in src/llmcompressor/observers/fusion.py
fuse
classmethod
Link all observers in the iterable with each other for shared global_scale. Sets module weak-references and makes handlers aware of each other.
Parameters:
-
observers_and_modules(Iterable[tuple['Observer', Module]]) –iterable of (observer, module) tuples
Source code in src/llmcompressor/observers/fusion.py
get_fused_statistics
Returns statistics for every observer in the fusion group (including this handler's own observer).
If a fused observer lacks statistics, runs observation on its module's weight via the weak ref stored during fuse().
Returns:
-
list[dict[str, Tensor]]–list of {"min_vals": Tensor, "max_vals": Tensor} dicts
Source code in src/llmcompressor/observers/fusion.py
maybe_delete_statistics
Cooperative statistics deletion. Each handler calls this when it is done with fused statistics. When ALL handlers in the group have called it, deletes statistics from every observer in the group and resets the bookkeeping.
For unfused observers, deletes statistics immediately.
Source code in src/llmcompressor/observers/fusion.py
IMatrixMSEObserver
Bases: Observer
MSE observer weighted by per-input-channel importance (E[x²]).
Supports CHANNEL, GROUP, and TENSOR_GROUP for weight-only Linear modules. Falls back to uniform MSE when importance data is unavailable.
Importance is accumulated on the observer as raw _imatrix_sum /
_imatrix_count and synced across DDP ranks via _act_sync_dict
before observation.
Methods:
-
attach–Attach a forward-pre hook to accumulate E[x²] per input channel.
-
detach–Remove the activation collection hook.
Source code in src/llmcompressor/observers/imatrix.py
attach
Attach a forward-pre hook to accumulate E[x²] per input channel.
Source code in src/llmcompressor/observers/imatrix.py
detach
MemorylessMinMaxObserver
Bases: Observer
Compute quantization parameters by taking the min/max of the observed value.
Source code in src/llmcompressor/observers/base.py
MinMaxObserver
Bases: Observer
Compute quantization parameters by taking the moving average of min/max values.
Source code in src/llmcompressor/observers/min_max.py
MovingAverageMSEObserver
Bases: Observer
Compute quantization parameters by finding the optimal min/max values which minimize the mean of quantization error squared, with moving average smoothing.
Source code in src/llmcompressor/observers/mse.py
Observer
Bases: InternalModule, RegistryMixin
Base class for observers which compute quantization parameters given observations of weights, activations, or attention states.
Parameters:
-
base_name(str) –str used to name the observer attribute
-
args(QuantizationArgs) –quantization args used to calibrate and quantize the observed value
-
**observer_kwargs–keyword arguments for observer initialization
Methods:
-
attach–Called when the observer is attached to a module.
-
delete_statistics–Delete this observer's statistics.
-
detach–Called before the observer is deleted from a module.
-
forward–Update observer statistics from observed value.
-
get_global_scale–Compute global_scale from this observer and all fused observers.
-
get_qparams–Compute quantization parameters from accumulated statistics.
-
get_statistics–Return this observer's current statistics.
-
sync_activation_stats–All-reduce accumulated activation statistics across DDP ranks.
-
update_statistics_from_observed–Update internal observer statistics (min_vals, max_vals) from observed tensor.
Source code in src/llmcompressor/observers/base.py
attach
Called when the observer is attached to a module. Subclasses can override to register hooks or initialize state.
Parameters:
-
module(Module) –the module this observer is being attached to
Source code in src/llmcompressor/observers/base.py
delete_statistics
Delete this observer's statistics.
Parameters:
-
check_fused(bool, default:True) –if True (default), use cooperative fusion deletion so stats are only removed when all fused observers are ready. If False, delete immediately regardless of fusion state.
Source code in src/llmcompressor/observers/base.py
detach
Called before the observer is deleted from a module. Subclasses can override to remove hooks and clean up module attributes.
Parameters:
-
module(Module) –the module this observer is being removed from
Source code in src/llmcompressor/observers/base.py
forward
Update observer statistics from observed value. If fused, also triggers observation for all fused observers.
Parameters:
-
observed(Tensor) –value being observed
Returns:
-
Observer–self for method chaining
Source code in src/llmcompressor/observers/base.py
get_global_scale
Compute global_scale from this observer and all fused observers.
Uses the FusionHandler to collect statistics from the fusion group. Returns None if strategy is not TENSOR_GROUP.
Returns:
-
Optional[Tensor]–global_scale tensor or None
Source code in src/llmcompressor/observers/base.py
get_qparams
Compute quantization parameters from accumulated statistics.
For TENSOR_GROUP, global_scale is computed from the absmax of this observer and all fused observers.
Returns:
-
QParamsDict–dict with keys "scale", "zero_point", and "global_scale"
Source code in src/llmcompressor/observers/base.py
get_statistics
Return this observer's current statistics.
Returns:
-
dict[str, Tensor]–dict mapping each stats attr name to its tensor
Source code in src/llmcompressor/observers/base.py
sync_activation_stats
All-reduce accumulated activation statistics across DDP ranks.
note: weight statistics don't need to be synced since weights
are synced across ranks, only data (activations) differs by rank.
Returns:
-
List[Work]–list of async communication handles
Source code in src/llmcompressor/observers/base.py
update_statistics_from_observed
abstractmethod
Update internal observer statistics (min_vals, max_vals) from observed tensor.
Parameters:
-
observed(Tensor) –flattened observed value of shape (num_observations, *qparam_shape, group_size)
Source code in src/llmcompressor/observers/base.py
QParamsDict
Bases: TypedDict
Dictionary containing quantization parameters.
StaticMinMaxObserver
Bases: MemorylessMinMaxObserver
Compute quantization parameters by taking the min/max of all observed values.
Source code in src/llmcompressor/observers/base.py
flatten_for_calibration
Reshapes the value according to the quantization strategy for the purposes of scale/zp calibration. The value after flattening has the following shape:
(num_observations, *qparam_shape, group_size)
For block quantization, value will be zero-padded if it is not evenly divisible by block_size, so as not to distort the calculated qparams and to be compatible with vllm block-wise kernels that do not require even divisibility.
The first dim is the number of observations (usually the batch size times number of tokens), the middle dims are the dimension of the scales, and the last dim is the number of elements being quantized per group.
Parameters:
-
value(Tensor) –value being flattened
-
base_name(str) –weight, input, output, q/k/v. Used to characterize the value as being a weight, activation, or attention state
-
args(QuantizationArgs) –quantization args for determining how the value is flattened
Returns:
-
Tensor–value which has been reshaped for calibration
Source code in src/llmcompressor/observers/helpers.py
fuse_weight_observers
Link weight observers across fused layer groups for shared global_scale.
For TENSOR_GROUP quantization (e.g. NVFP4), vLLM requires that fused layers (Q/K/V attention, gate/up MLP) share the same global_scale. This function links their observers so that get_qparams() computes global_scale from the combined statistics of all observers in the group. Fused groups are defined in llmcompressor.observers.fused_mappings.
Parameters:
-
model(Module) –model whose weight observers should be linked
Source code in src/llmcompressor/observers/helpers.py
get_fused_layers
Find the fused groups among the layers of one parent module, as defined by FUSED_MODULE_MAPPINGS.
Parameters:
-
module(Module) –parent module of the layers, e.g. an attention module
Returns:
-
list[dict[str, Module]]–one dict per fused group, mapping each layer name to its layer
Source code in src/llmcompressor/observers/fused_mappings.py
resolve_fused_names
Resolve the fused groups among the layers present under one parent module.
A mapping applies when all of its names are present, and those of its
optional_names that are present join the group. This follows vLLM, which
packs a layer into whichever fused module exists on that parent. For
example, Kimi g_proj is packed into in_proj_qkvgfab on delta attention
layers and into fused_qkv_a_g_proj on MLA layers.
Larger groups take precedence, and a group that shares a layer with an already chosen group is dropped. For example, a Kimi delta attention layer resolves to one q/k/v/b/f_a group rather than a q/k/v group.
Parameters:
-
present_names(Collection[str]) –layer names present under one parent, relative to it
Returns:
-
list[tuple[str, ...]]–disjoint groups of layer names. The first name of each group is always one of its mapping's required
names