Skip to content
class

HistogramObserver

extendsObserverBase
HistogramObserver(bins: int = 2048, qscheme: QScheme = per_tensor_affine, qdtype: QDtype = quint8, eps: float = 1e-08)

Per-tensor observer that records a value histogram and picks a clip range.

The accuracy-maximising activation observer. Instead of committing to the raw [min, max] — which on a heavy-tailed activation would stretch the grid over a handful of rare extremes and quantize the dense bulk coarsely — it accumulates a bins-bucket histogram of every value seen (via the engine histc primitive), then at calculate_qparams time searches for the clip range [new_min, new_max] that minimises the expected L2 quantization error. Clipping the tails costs a little error on the rare outliers but wins far finer resolution on the common values, which is usually a large net accuracy gain.

When to pick it. Use it for activations with skewed / heavy-tailed distributions — it is the activation observer in lucid.quantization.get_default_qconfig (static PTQ). It is more expensive than min/max (it maintains a histogram and runs a search) and applies to per-tensor affine schemes, so it is not used for per-channel weights (see PerChannelMinMaxObserver). When calibration is cheap and distributions are light-tailed, plain MinMaxObserver / MovingAverageMinMaxObserver suffice.

The running range widens with the data; when it grows the existing histogram is rebinned onto the wider support before the new batch is added. With bin centers cic_i and counts nin_i, the search evaluates candidate clip endpoints [a,b][a, b] (drawn from a few tail quantiles) and picks the pair minimising the per-value clip error plus the uniform-quantization noise variance:

err⁡(a,b)=∑ini[(ci−clip⁡(ci,a,b))2+Δ212],Δ=b−aqmax⁡−qmin⁡,\operatorname{err}(a, b) = \sum_i n_i \Bigl[\bigl(c_i - \operatorname{clip}(c_i, a, b)\bigr)^2 + \tfrac{\Delta^2}{12}\Bigr], \qquad \Delta = \frac{b - a}{q_{\max} - q_{\min}},

where the first term is the squared clipping error (mass pushed onto the boundary) and Δ2/12\Delta^2/12 is the variance of rounding to a uniform grid of step Δ\Delta. The winning [a,b][a, b] is then fed to lucid.quantization.calculate_qparams for the final affine (scale, zero_point).

Parameters

binsint= 2048
Number of histogram buckets over the running [min, max]. More bins give a finer clip search at higher memory / compute cost.
qschemeQScheme= per_tensor_affine
Target quantization scheme (the clip search assumes a per-tensor grid).
qdtypeQDtype= quint8
Target quantized dtype; quint8 gives the unsigned [0, 255] grid.
epsfloat= 1e-8
Lower floor on the derived scale.

Attributes

min_valTensor
Scalar (shape ()) running minimum of the histogram support, seeded +inf.
max_valTensor
Scalar (shape ()) running maximum of the histogram support, seeded -inf.
histogramTensor
The accumulated value histogram, shape (bins,), seeded to zeros.

Notes

  • Rebinning on growth. When a batch widens [min, max], the stored histogram is redistributed onto the new, wider bin grid before the fresh counts are added, so accumulated mass is preserved rather than discarded.
  • Search is a coarse scan. The clip endpoints are candidate tail quantiles (0, 1e-5, 1e-4, 1e-3, 5e-3, 1e-2), not a full exhaustive sweep — a deliberate speed / accuracy trade-off. The best-scoring pair wins.
  • Data-dependent control flow. forward reads x.min()/.max() via .item() and the search runs in Python over histogram.tolist(); this is a sanctioned CPU round-trip (data-dependent output), still H4-pure (engine histc, no external histogram library).
  • No autograd history. min_val / max_val / histogram are all updated under lucid.no_grad and written in place, per the ObserverBase contract.
  • Symmetric vs affine. The reduction honours qscheme; the default per-tensor affine leaves zero_point free to fit the (clipped) asymmetric range.
  • Default activation observer of lucid.quantization.get_default_qconfig.

Examples

>>> import lucid
>>> import lucid.quantization as Q
>>> obs = Q.HistogramObserver(bins=512)
>>> for _ in range(4):
...     _ = obs(lucid.randn(8, 1024))
>>> obs.histogram.shape
(512,)
>>> scale, zero_point = obs.calculate_qparams()
>>> bool(scale.item() > 0)
True
On a heavy-tailed input the search clips the rare extreme, so the chosen range is
*narrower* than the raw min/max the histogram spans.  It does so only when the bulk
is large enough that the finer grid outweighs the outlier's clipping error — at
1e5 values, keeping the outlier is the lower-error choice; at 1e6 it is not:
>>> import lucid
>>> _ = lucid.manual_seed(0)
>>> x = lucid.randn(1, 1_000_000)
>>> x[0, 0] = 50.0                           # a single far outlier
>>> obs = Q.HistogramObserver(bins=2048)
>>> _ = obs(x)
>>> s, _ = obs.calculate_qparams()
>>> bool(s.item() * 255 < 50.0)              # grid span clipped below the outlier
True

See Also

Used by 2

Constructors

1
dunder

__init__

→None
__init__(bins: int = 2048, qscheme: QScheme = per_tensor_affine, qdtype: QDtype = quint8, eps: float = 1e-08)

Instance methods

2
fn

calculate_qparams

→tuple[Tensor, Tensor]
calculate_qparams()

Return (scale, zero_point) from the accumulated statistics.

fn

forward

→Tensor
forward(x: Tensor)

Update the running range and accumulate the histogram.