Skip to content
class

QuantizedLinearMLX

extendsModule
QuantizedLinearMLX(in_features: int, out_features: int, bias: bool = True, bits: int = 8, group_size: int = 64, relu: bool = False)

Weight-only int4/int8 linear backed by a real Metal low-precision GEMM.

The compute-and-memory quantized linear, and the layer lucid.quantization.convert routes the Linear family to when the MLX backend is active. Where lucid.nn.quantized.Linear dequantizes its int8 weight back to float and runs an ordinary float matmul (a memory-only win), QuantizedLinearMLX stores the weight in MLX's group-wise packed format and runs the genuine low-precision kernel — the packed weight is dequantized inside the GEMM, in one pass, so a full float weight is never materialized. Build it from a float lucid.nn.Linear via from_float, choosing bits (4 or 8).

Group-wise packed representation. The float weight (out_features, in_features) is split, along the input dim, into contiguous groups of group_size elements; every (output-channel, group) block gets its own affine scale ss and bias β\beta (an offset, distinct from the layer's additive bias term), and the codes are bit-packed into a uint32 tensor (tagged I32). Finer groups track a channel's local dynamic range more tightly than one per-row scale, at the cost of more metadata. This is the packing MLX's quantized_matmul consumes directly.

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

qo,i=clamp⁡ ⁣(round⁡ ⁣((wo,i−βo,g)/so,g), 0, 2b−1),w^o,i=so,g qo,i+βo,gq_{o,i} = \operatorname{clamp}\!\Bigl( \operatorname{round}\!\bigl((w_{o,i} - \beta_{o,g}) / s_{o,g}\bigr),\ 0,\ 2^{b}-1\Bigr), \qquad \hat{w}_{o,i} = s_{o,g}\, q_{o,i} + \beta_{o,g} y=x w^⊤+b,g=⌊i/group_size⌋y = x\, \hat{w}^{\top} + \mathbf{b}, \qquad g = \bigl\lfloor i / \texttt{group\_size} \bigr\rfloor

where oo indexes out_features, ii the input dim, bb the bit-width (grid 0 .. 2^b - 1), and gg maps input index ii to its group. A ReLU is optionally fused after + b. In the kernel, w^\hat{w} is never fully realized — the packed codes and the per-group (s,β)(s, \beta) are streamed into the matmul directly.

Parameters

in_featuresint
Size of each input sample.
out_featuresint
Size of each output sample.
biasbool= True
Whether a learned float bias term is added after the GEMM. Defaults to True.
bitsint= 8
Weight bit-width — 4 (aggressive memory) or 8. Defaults to 8.
group_sizeint= 64
Number of input-dim elements sharing one scale / bias block in the packed layout. Must divide in_features. Smaller groups are tighter but carry more metadata. Defaults to 64.
relubool= False
If True, a ReLU is fused after the GEMM (+ bias). Defaults to False.

Attributes

packed_weightTensor
The bit-packed codes, shape (out_features, in_features·bits/32), int32 (I32-tagged uint32) — bits/32 codes packed per word.
scalesTensor
Per-(output-channel, group) affine scale, shape (out_features, in_features/group_size).
biasesTensor
Per-(output-channel, group) affine offset, shape (out_features, in_features/group_size).
biasTensor or None
The float bias of shape (out_features,), or None.

Notes

  • The kernel is Metal-only but the layer is device-transparent: a CPU-carried activation is moved onto the GPU for the GEMM and the result is moved back to the input's device, so this layer accelerates inside an otherwise-CPU model (or residual skip branch) without forcing the whole model onto Metal.
  • Build via from_float (which quantizes on Metal), not by constructing directly: a fresh instance has an all-zero packed_weight and zeroed scales / biases, so it returns zeros until from_float / load_state_dict populates the buffers.
  • The state_dict carries the packed int32 weight + per-group scales / biases + the float bias — never a float weight. The weight payload shrinks ~3.55x at bits=8 and ~6.40x at bits=4 (the packed codes plus the small per-group metadata).
  • This is the layer that wins on compute, not just memory: it skips the dequantize-to-float hop entirely. The speed-up is bandwidth-bound — it is largest in the memory-bound decode / generation regime (measured 3.15x at M = 1) and fades toward parity (0.9-1x) in compute-bound (large-M) training GEMMs, where the matmul, not weight bandwidth, dominates.
  • The real int4/int8 kernels are an optional C++ submodule; gate on lucid.quantization._qgemm.is_available before relying on this fast path. lucid.quantization.convert routes the Linear family here only when the MLX backend is active.
  • Activation gradients for QLoRA. While the packed integer weight and per-group scales/biases are frozen buffers, quantized_matmul defines a backward pass with respect to the floating input activation x, so upstream parameters and parallel LoRA branches receive gradients.

Examples

>>> import lucid, lucid.nn as nn
>>> from lucid.nn.quantized import QuantizedLinearMLX
>>> lin = nn.Linear(512, 256)
>>> qlin = QuantizedLinearMLX.from_float(lin, bits=8)  # quantize on Metal
>>> x = lucid.randn(4, 512)
>>> y = qlin(x)          # GEMM runs on Metal, y returns on x's device
>>> y.shape
(4, 256)
The layer is device-transparent — a CPU input is round-tripped through Metal
for the GEMM and the result comes back on the input's device, while a Metal
input stays on the GPU throughout:
>>> qlin(x).is_metal                       # CPU in -> CPU out
False
>>> qlin(x.to("metal")).is_metal           # Metal in -> Metal out
True
Constructing directly (instead of via from_float) yields a zeroed,
no-op layer — the packed weight is all zero until the buffers are filled:
>>> broken = QuantizedLinearMLX(512, 256, bits=8)
>>> bool((broken.packed_weight == 0).all().item())
True

See Also

Used by 1

Constructors

1
dunder

__init__

→None
__init__(in_features: int, out_features: int, bias: bool = True, bits: int = 8, group_size: int = 64, relu: bool = False)

Class methods

1
cls

from_float

→QuantizedLinearMLX
from_float(mod: nn.Module, bits: int = 8, group_size: int = 64, relu: bool = False)

Quantize a float Linear's weight into MLX packed form (on Metal).

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)

Run the MLX low-precision GEMM x @ packed_wᵀ (+ bias, +ReLU).

The kernel is Metal-only, so a CPU-carried activation is moved onto the GPU for the GEMM and the result is moved back to the input's device. That keeps this layer device-transparent — it accelerates inside an otherwise-CPU model without forcing the whole model (or residual skip branches) onto Metal.