Skip to content
class

Linear

extendsLinear
Linear(in_features: int, out_features: int, bias: bool = True, qconfig: QConfig | None = None)

Implementing kernel

C++ engine symbols that back this Python API.

Quantization-aware Linear — trainable float weight, fake-quant every forward.

The training-time stand-in that lucid.quantization.prepare_qat installs in place of a float lucid.nn.Linear. It keeps a trainable float weight but routes both the weight and the layer output through a lucid.quantization.FakeQuantize on every forward, so the network feels the int8 rounding error while it is still learning and can adapt its weights to compensate. This is what closes the train / inference accuracy gap: plain post-training quantization perturbs a network that never saw rounding, whereas a QAT-trained network has already minimised its loss with the rounding baked in, so its accuracy barely moves when the weights are finally frozen to int8.

Straight-through estimator (STE). Rounding is a step function; its derivative is zero almost everywhere, so a literal round would block all gradient flow. The fake-quant therefore rounds in the forward pass but, in the backward pass, pretends it was the identity — the incoming gradient passes straight through to the underlying float weight (clipped to the quantization range). The float weight thus stays fully trainable while every forward value it produces is the dequantized number an int8 kernel would have computed.

Where it sits. lucid.quantization.prepare_qat deep-copies the float model and swaps each lucid.nn.Linear for this class, attaching the weight and activation FakeQuantize modules described by the layer's qconfig. After training, lucid.quantization.convert reads the trained weight together with the activation observer's final (scale, zero_point) and bakes them into an inference lucid.nn.quantized.Linear whose weight is stored as true int8 codes.

On each forward the weight is fake-quantized, the ordinary F.linear runs, and the result is fake-quantized onto the observed activation grid:

fake_quant⁡(t)=(clamp⁡(round⁡(t/s)+z, qmin⁡, qmax⁡)−z) s,∂ fake_quant⁡(t)∂t=1\operatorname{fake\_quant}(t) = \bigl( \operatorname{clamp}(\operatorname{round}(t / s) + z,\ q_{\min},\ q_{\max}) - z\bigr)\, s, \qquad \frac{\partial\, \operatorname{fake\_quant}(t)}{\partial t} = 1 y=fake_quant⁡a ⁣(fake_quant⁡w(W) x⊤+b)y = \operatorname{fake\_quant}_{a}\!\bigl( \operatorname{fake\_quant}_{w}(W)\, x^{\top} + b\bigr)

where s,zs, z are the scale / zero-point the enclosing FakeQuantize derives from its observer and qmin⁡,qmax⁡q_{\min}, q_{\max} are the grid bounds (0, 255 for the default quint8 activation, -128, 127 for the qint8 weight). The straight-through unit derivative is what keeps the layer differentiable despite the non-differentiable round.

Parameters

in_featuresint
Size of each input sample — forwarded verbatim to the float lucid.nn.Linear parent.
out_featuresint
Size of each output sample — forwarded verbatim to the float parent.
biasbool= True
Whether to add a learnable (float) bias term; forwarded to the float parent. The bias is left in float and never fake-quantized.
qconfigQConfig= None
Quantization recipe supplying the weight and activation lucid.quantization.FakeQuantize modules applied during training. Required — constructing the layer without one raises ValueError.

Attributes

weight_fake_quantFakeQuantize
The weight observer + fake-quant built from qconfig.weight(); rounds the float weight each forward and tracks its range so convert can pick the int8 qparams.
activation_post_processFakeQuantize
The output observer + fake-quant built from qconfig.activation(); calibrates the activation grid whose (scale, zero_point) convert later bakes in.

Notes

  • STE differentiability. round is applied in the forward pass but the gradient is passed through as if it were the identity, so the float weight trains normally — no gradient is lost to the non-differentiable rounding step.
  • Both directions are wired for you. lucid.quantization.prepare_qat swaps the float layer in; lucid.quantization.convert folds this layer out into the matching lucid.nn.quantized.Linear. Manual construction is rarely needed and requires an explicit qconfig.
  • Training is slower, not faster. Only the numerics of int8 are simulated; the matmul itself still runs in float and each forward carries two extra fake-quant ops, so a QAT model runs slower than the float baseline. The speed / memory win arrives only after convert replaces this layer with the int8 inference module.

Examples

>>> import lucid, lucid.nn as nn
>>> import lucid.quantization as Q
>>> model = nn.Sequential(nn.Linear(16, 4))
>>> qat = Q.prepare_qat(model)              # nn.Linear -> qat.Linear
>>> type(qat[0]).__name__
'Linear'
>>> loss = (qat(lucid.randn(8, 16)) ** 2).mean()
>>> loss.backward()                         # STE routes grads to the float weight
>>> _ = qat.eval()
>>> qmodel = Q.convert(qat)                 # qat.Linear -> quantized.Linear (int8)
>>> type(qmodel[0]).__name__
'Linear'
A qconfig is mandatory — constructing the layer directly without one raises:
>>> import lucid.nn.qat as nnqat
>>> nnqat.Linear(8, 8)
Traceback (most recent call last):
    ...
ValueError: qat.Linear requires a qconfig

See Also

Used by 1

Constructors

1
dunder

__init__

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

Class methods

1
cls

from_float

→Linear
from_float(mod: nn.Module)

Build a QAT Linear from a float one (shares the trained weight).

Instance methods

1
fn

forward

→Tensor
forward(x: Tensor)

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