Skip to content
class

ConvBn1d

extends_ConvBnNd
ConvBn1d(conv: nn.Module, bn: nn.Module, qconfig: QConfig | None = None)

QAT fused Conv1d + BatchNorm1d — BN folded into the weight every forward.

The training-time stand-in for a Conv1d immediately followed by a BatchNorm1d. At inference the BN scale-and-shift can be absorbed into the conv weight and bias so the pair runs as a single convolution; a naive QAT layer that folded BN once up front, however, would freeze BN's running statistics and stop it training. This class instead re-folds BN into the conv weight on every forward, fake-quantizes the folded weight, convolves, and fake-quantizes the output — all differentiably — so BN keeps learning while the network already experiences the folded-and-quantized numerics it will see at inference.

Straight-through estimator (STE). The weight fake-quant rounds the folded kernel in the forward pass but passes gradients straight through in the backward pass, so both the conv weight and the BN affine parameters receive clean gradients despite the non-differentiable round. The running statistics are not learned — the wrapped bn updates them from each training batch, exactly as in the unfused model.

Where it sits. lucid.quantization.prepare_qat builds this from a fused conv+BN pattern. After training, lucid.quantization.convert folds BN one final time, quantizes the folded weight to int8, and bakes it — together with the calibrated activation qparams — into an inference lucid.nn.quantized.Conv1d. No separate BN layer survives conversion; it lives entirely inside the conv weight and bias.

The per-output-channel BN fold (cc indexes output channels) is

wc′=γc wcσc2+ϵ,bc′=βc+γc bc−μcσc2+ϵw'_{c} = \gamma_c\,\frac{w_c}{\sqrt{\sigma_c^2 + \epsilon}}, \qquad b'_{c} = \beta_c + \gamma_c\,\frac{b_c - \mu_c}{\sqrt{\sigma_c^2 + \epsilon}}

with BN affine (γ,β)(\gamma, \beta), running statistics (μ,σ2)(\mu, \sigma^2), numerical floor ϵ\epsilon, and conv weight / bias (wc,bc)(w_c, b_c). When the conv has no bias (the usual fused case, bc=0b_c = 0) the shift reduces to bc′=βc−γc μc/σc2+ϵb'_c = \beta_c - \gamma_c\,\mu_c/\sqrt{\sigma_c^2+\epsilon}. In eval mode (or once the BN statistics are frozen) the layer is exactly that folded conv, with the folded weight fake-quantized under the STE:

y=fake_quant⁡a ⁣(fake_quant⁡w(w′)⋆x+b′),∂ fake_quant⁡(t)∂t=1y = \operatorname{fake\_quant}_{a}\!\bigl( \operatorname{fake\_quant}_{w}(w') \star x + b'\bigr), \qquad \frac{\partial\, \operatorname{fake\_quant}(t)}{\partial t} = 1

where ⋆\star is the 1-D cross-correlation and fake_quant⁡(t)=(clamp⁡(round⁡(t/s)+z,qmin⁡,qmax⁡)−z) s\operatorname{fake\_quant}(t) = (\operatorname{clamp}(\operatorname{round}(t/s) + z,q_{\min}, q_{\max}) - z)\, s.

Parameters

The float 1-D convolution whose weight receives the folded BN affine.
The batch-norm layer folded into conv. It must track running statistics; its affine parameters train under the STE and its running statistics update from each training batch (ValueError if track_running_stats=False).
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 from qconfig.weight(); rounds the folded kernel each forward and tracks its range so convert can pick the int8 qparams.
activation_post_processFakeQuantize
The output observer + fake-quant from qconfig.activation(); calibrates the activation grid whose (scale, zero_point) convert later bakes in.

Notes

  • Batch statistics in training. bn normalises with them and updates its running ones; freeze_bn_stats / update_bn_stats stop and resume that.
  • STE differentiability. The folded weight is rounded forward but the gradient is passed through as the identity, so the conv weight and the BN parameters train.
  • Both directions are wired for you. lucid.quantization.prepare_qat builds this fused layer in; lucid.quantization.convert folds it out into the matching lucid.nn.quantized.Conv1d (BN absorbed, no BN layer left).

Examples

>>> import lucid, lucid.nn as nn
>>> import lucid.quantization as Q
>>> import lucid.nn.intrinsic.qat as nniqat
>>> cbn = nniqat.ConvBn1d(
...     nn.Conv1d(3, 8, 3, padding=1, bias=False),
...     nn.BatchNorm1d(8),
...     qconfig=Q.get_default_qat_qconfig(),
... )
>>> w, b = cbn._fold()                 # BN folded into (weight, bias)
>>> w.shape, b.shape
((8, 3, 3), (8,))
>>> loss = (cbn(lucid.randn(2, 3, 8)) ** 2).mean()
>>> loss.backward()                    # STE trains conv weight AND BN params
A qconfig is mandatory — constructing the layer without one raises:
>>> nniqat.ConvBn1d(nn.Conv1d(3, 8, 3), nn.BatchNorm1d(8))
Traceback (most recent call last):
    ...
ValueError: ConvBn1d requires a qconfig

See Also

Used by 1

Constructors

1
dunder

__init__

→None
__init__(conv: nn.Module, bn: nn.Module, qconfig: QConfig | None = None)

Instance methods

4
fn

forward

→Tensorfrom _ConvBnNd
forward(x: Tensor)

Scale and fake-quant the weight → conv → unscale → BN → (ReLU) → fake-quant.

fn

freeze_bn_stats

→Selffrom _ConvBnNd
freeze_bn_stats()

Stop the running-stat updates; bn normalises with its running stats.

fn

train

→Selffrom _ConvBnNd
train(mode: bool = True)

Set the mode recursively, except that a frozen bn stays frozen.

fn

update_bn_stats

→Selffrom _ConvBnNd
update_bn_stats()

Let bn normalise with batch statistics and update its running ones.