Skip to content
class

Linear

extendsModule
Linear(in_features: int, out_features: int, bias: bool = True)

Implementing kernel

C++ engine symbols that back this Python API.

Quantized linear (fully-connected) layer — int8 weight, float compute.

The inference-time replacement that lucid.quantization.convert installs in place of a calibrated float lucid.nn.Linear. It is the quantized workhorse of every fully-connected stack — classifier heads, Transformer MLP blocks, projection layers — and the layer whose weight memory dominates most language models.

Representation (sidecar design B). The learned float weight is quantized once, at from_float time, into an int8 code tensor plus a per-output-channel scale / zero_point; the float weight is then dropped. Only the int8 codes, the qparams, and the (still-float) bias live in the module, so the checkpoint is roughly 4x smaller than the float layer's. Each forward dequantizes the weight back to float, runs the ordinary F.linear, and finally fake-quantizes the output onto the activation grid that calibration observed. Keeping the matmul itself in float means the result matches a genuine int8 kernel to within a rounding step and the layer runs unchanged on any device, with no int8 GEMM kernel required.

Per-channel weights. The weight (out_features, in_features) is quantized independently for every output channel (axis 0): each row carries its own scale and zero-point. Because different output neurons often span very different dynamic ranges, per-channel quantization tracks them far more tightly than a single per-tensor scale, and is the standard accuracy-preserving choice for linear and convolution kernels. The bias is small and precision-sensitive, so it is left in float.

Encoding happens once (at from_float); decode + matmul run on every forward:

wijq=clamp⁡ ⁣(round⁡(wij/si)+zi, −128, 127),w^ij=(wijq−zi) siw^{q}_{ij} = \operatorname{clamp}\!\bigl( \operatorname{round}(w_{ij}/s_i) + z_i,\ -128,\ 127\bigr), \qquad \hat{w}_{ij} = (w^{q}_{ij} - z_i)\, s_i y=fake_quant⁡ ⁣(w^ x⊤+b),fake_quant⁡(t)=(clamp⁡(round⁡(t/S)+Z, qmin⁡, qmax⁡)−Z) Sy = \operatorname{fake\_quant}\!\bigl(\hat{w}\, x^{\top} + b\bigr), \qquad \operatorname{fake\_quant}(t) = \bigl( \operatorname{clamp}(\operatorname{round}(t/S) + Z,\ q_{\min},\ q_{\max}) - Z\bigr)\, S

where si,zis_i, z_i are the per-output-channel weight scale / zero-point and S,ZS, Z the scalar calibrated output (scale, zero_point) with grid bounds qmin⁡,qmax⁡q_{\min}, q_{\max} (0, 255 for the default quint8). The decode → float-matmul → re-quantize round-trip is what makes the output bit- equivalent to a true int8 kernel without needing one.

Parameters

in_featuresint
Size of each input sample — the in dimension of the weight.
out_featuresint
Size of each output sample — the out dimension, quantized per-channel.
biasbool= True
If True the layer keeps a learned float bias added after the matmul; if False no bias term is stored.

Attributes

weight_int8Tensor
The int8 weight codes, shape (out_features, in_features).
weight_scaleTensor
Per-output-channel weight scale, shape (out_features,).
weight_zero_pointTensor
Per-output-channel weight zero-point, shape (out_features,).
scaleTensor
Scalar output-activation scale, set from the calibrated observer.
zero_pointTensor
Scalar output-activation zero-point, set from the calibrated observer.
biasTensor or None
The float bias of shape (out_features,), or None.

Notes

  • Instances are normally produced by lucid.quantization.convert (or from_float), not constructed directly: a freshly constructed layer has identity qparams (scale = 1, zero_point = 0) and zeroed weights, and only becomes meaningful once from_float / load_state_dict fills the buffers.
  • Only int8 codes + qparams + float bias enter the state_dict; the float weight never does. In practice the weight payload shrinks ~3.55x (int8) and a whole model checkpoint ~3.97x (measured on resnet_18).
  • This layer wins on memory, not compute — the GEMM runs in float, so on the CPU stream it is roughly float-speed. For the genuine low-precision compute speed-up on Metal, convert with the MLX backend active so the Linear family is routed to lucid.nn.quantized.QuantizedLinearMLX, which runs a real weight-only int4/int8 GEMM (skipping the dequantize hop) — measured 3.15x faster at the memory-bound decode shape M = 1 on a fully-Metal model. That win is bandwidth-bound: it lands in the inference / generation regime and fades toward parity (0.9-1x) in compute-bound training GEMMs.
  • _activation is the identity here; the fused lucid.nn.quantized.LinearReLU overrides it to apply ReLU before the output fake-quant so calibration and inference see the same post-ReLU range.

Examples

>>> import lucid, lucid.nn as nn
>>> import lucid.quantization as Q
>>> model = nn.Sequential(nn.Linear(128, 64))
>>> model.qconfig = Q.get_default_qconfig()
>>> prepared = Q.prepare(model)          # insert activation/weight observers
>>> _ = prepared(lucid.randn(32, 128))   # calibrate on representative data
>>> qmodel = Q.convert(prepared)         # float Linear -> quantized layer
>>> type(qmodel[0]).__name__             # MLX kernels built in: the int8 GEMM
'QuantizedLinearMLX'
>>> qlin = nn.quantized.Linear.from_float(prepared[0])   # this layer, explicitly
>>> type(qlin).__name__
'Linear'
>>> y = qlin(lucid.randn(1, 128))        # int8-weight inference
>>> y.shape
(1, 64)
Constructing the layer directly is **not** a substitute for that workflow — a
bare instance carries zeroed weights and identity qparams, so it returns garbage
until from_float / load_state_dict populates the buffers:
>>> broken = nn.quantized.Linear(128, 64)     # zeroed weight, scale=1, zp=0
>>> bool((broken.weight_int8 == 0).all().item())
True
For the *compute* speed-up on Metal, route through the real low-precision GEMM:
>>> src = nn.Linear(512, 512)
>>> qlin = nn.quantized.QuantizedLinearMLX.from_float(src, bits=8)
>>> qlin(lucid.randn(1, 512).to("metal")).shape
(1, 512)

See Also

Used by 2

Constructors

1
dunder

__init__

→None
__init__(in_features: int, out_features: int, bias: bool = True)

Class methods

1
cls

from_float

→Linear
from_float(mod: nn.Module)

Quantize a calibrated float lucid.nn.Linear.

Instance methods

2
fn

extra_repr

→str
extra_repr()

Override to add extra repr info (e.g. Linear shows in_features, etc.).

fn

forward

→Tensor
forward(x: Tensor)

Dequantize the weight, run linear, fake-quantize the output.