Module contents
Lesson 23 of 28Core 105 min

Quantization I: foundations

Quantization reduces weight storage and can accelerate memory-bound decoding. Build symmetric and affine quantizers, analyze rounding and clipping, calibrate ranges, compare granularities and simulate integer matrix multiplication. A local lab measures packed weights on an RTX 3060.

After this lesson you can

  • Calculate scale and zero point for symmetric or affine quantizers and quantize and dequantize tensors.
  • Separate quantization error into rounding and clipping components and find an optimal range.
  • Compare calibration methods and granularities by error and actual bits per weight.
  • Simulate INT8 matrix multiplication with an INT32 accumulator and requantization and explain when it is faster.
  • Measure memory, decoding speed and perplexity for a small LLM with 8-bit and 4-bit weights.

Before you start

A grid to reduce memory

A BF16 parameter occupies two bytes. Ideally, seven billion parameters would occupy 14 decimal GB in weights alone; at four bits they would take 3.5 GB before scales, metadata, KV cache and other memory. Reducing bytes can speed up memory-bound decoding, but storing fewer bits is not enough: the kernel must read and use them efficiently. Memory accounting and the latency-throughput tradeoff determine the actual gain.

A roofline calculation helps decide what to measure. A dense multiplication reusing PP weights for a batch of BB vectors performs approximately 2PB2PB arithmetic operations. If each weight occupies bb bits and is read once, weight traffic is Pb/8Pb/8 bytes and corresponding intensity is approximately 16B/b16B/b operations per byte. This omits activations, scales, repeated reads and dequantization. As BB grows, weight reuse improves and memory may stop being the bottleneck. Compare effective intensity with the machine’s compute-to-bandwidth ratio and measure the kernel to check which cost dominates.

The figures in this lesson use the first four rows and 128 columns of model.layers.0.self_attn.q_proj.weight from SmolLM2-135M, revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2. These 512 weights are not a representative sample of all layers. Scale and error are recalculated on them in the browser. The histogram groups weights outside the displayed interval at the ends.

InteractiveA grid and its errors
Original weights (blue) and reconstructed weights (orange); 16 bins from -2 to 2, extremes grouped. Representable range [−1.000, 1.000]. The affine scheme uses requested range [-L, L/2].
−202
Quantizer
4
1.0
Step and zero point0.1429, 0
Mean squared error0.00194
Clipping / rounding0.00033 / 0.00161
SQNR dB17.18
Change bits, scheme and range. Compare original and reconstructed bars and clipping and rounding errors.

Scale and zero point

Uniform affine quantization maps a real number xx to an integer qq in [qmin⁡,qmax⁡][q_{\min},q_{\max}] using

q=clip⁡(round⁡(x/s)+z,qmin⁡,qmax⁡),x^=s(q−z).q=\operatorname{clip}\left(\operatorname{round}(x/s)+z,q_{\min},q_{\max}\right),\qquad \hat{x}=s(q-z).

Here s>0s>0 is the scale and zz is a representable integer, the zero point. Thus q=zq=z represents x=0x=0 exactly. For a desired range [a,b][a,b] including zero, a common recipe is s=(b−a)/(qmax⁡−qmin⁡)s=(b-a)/(q_{\max}-q_{\min}) and z=clip⁡(round⁡(qmin⁡−a/s),qmin⁡,qmax⁡)z=\operatorname{clip}(\operatorname{round}(q_{\min}-a/s),q_{\min},q_{\max}). Rounding zz slightly shifts the representable real endpoints. The degenerate case a=ba=b needs an explicit convention to avoid division by zero.

A symmetric variant uses z=0z=0 and a symmetric integer range [−Q,Q][-Q,Q], with Q=2b−1−1Q=2^{b-1}-1 and s=max⁡∣x∣/Qs=\max|x|/Q. This leaves the most negative integer of a signed bb-bit representation unused. The rounding tie-break rule also matters: NumPy uses ties-to-even, while other runtimes may choose another convention. Jacob et al. detail an affine integer inference implementation.

For example, with four bits and symmetric range [−1,1][-1,1], Q=7Q=7 and the step is 1/71/7. The value 0.50.5 falls halfway between 3/73/7 and 4/74/7; the tie rule decides which to choose. In an affine implementation requesting [−1,0.5][-1,0.5], the scale is 1.5/15=0.11.5/15=0.1 and integer zero is 10. Its integers from 0 to 15 represent −1-1 to 0.50.5. If requested endpoints do not exactly match the grid after rounding zz, a fraction of a step can be lost at an endpoint.

Rounding, clipping and calibration

Quantization error has two sources. Inside the range, rounding to the nearest level introduces error of magnitude up to s/2s/2; outside, clipping also occurs. If rounding error is modeled as uniform in [−s/2,s/2][-s/2,s/2], it has zero mean and variance s2/12s^2/12, calculated by integrating e2/se^2/s. That assumption is not an identity for arbitrary data or clipped values.

To make the assumption explicit, write e=x^−xe=\hat x-x. If ee were independent of the signal and uniform on that interval, E[e]=0\E[e]=0 and

Var⁡(e)=1s∫−s/2s/2e2  ⁣de=s212.\Var(e)=\frac1s\int_{-s/2}^{s/2}e^2\,\dd e=\frac{s^2}{12}.

On a fixed grid without added noise, error is determined by xx: it is not independent by definition. It can correlate with a structured signal and concentrate at certain grid phases. The approximation is often more useful when many levels are occupied and the range fits well. If you algebraically separate x−x^=(x−clip⁡(x))+(clip⁡(x)−x^)x-\hat x=(x-\operatorname{clip}(x))+(\operatorname{clip}(x)-\hat x), squaring introduces a cross term; you cannot add two variances without justification. In the figure’s quantizer, clipping endpoints are representable levels. Outside the range, rounding the clipped value gives zero error; inside, clipping error is zero. The cross product vanishes and the two squared errors add, apart from numerical rounding.

With fixed range, doubling levels approximately halves ss and quarters error power. Under those assumptions the signal-to-noise ratio rises 10log⁡10(4)≈6.0210\log_{10}(4)\approx6.02 dB per additional bit. Clipped tails and few levels break the approximation. The figure calculates sample error directly and does not assume the 6 dB rule.

InteractiveSignal-to-noise and bits
  • Simulated normal
  • Simulated Laplace
  • Real weights
Calibration
Weights: gain from 7 to 8 bits5.81 dB
Compare maximum calibration with MSE search for simulated data and real weights. Observe the jumps between bit widths.

Range calibration estimates the grid using data: minimum and maximum avoid clipping the observed sample, but an outlier can make interior steps too coarse. Percentiles sacrifice extremes; minimizing squared error seeks a compromise for the sample; an entropy criterion compares reconstructed distributions. The calibration set should resemble deployment inputs, especially for activations. A range optimal for squared error does not guarantee optimal task accuracy.

MSE search must define the range space, quantizer, zero-point treatment and calibration sample. The KL criterion also requires specifying how histograms are built and division by zero mass is avoided. When static scales are applied to activations, the distribution can change across tasks or positions; with dynamic scales, range calculation is repeated during inference and also has a cost. A value absent during calibration can fall outside the range at deployment.

Granularity and metadata cost

Granularity determines which values share a scale. Per-tensor scaling has little overhead, but a channel with small values can lose resolution if another contains outliers. Per-output-channel scaling assigns one scale to each row of the weight matrix. Grouping divides each row into smaller blocks and increases the number of scales. With groups of gg weights, FP16 scale and FP16 zero point, the ideal cost is b+32/gb+32/g bits per weight, excluding padding and headers.

If final groups are incomplete, count one scale for each actual group: for NN values and GG groups that is b+16G/Nb+16G/N bits per weight if only an FP16 scale is stored and the zero point is implicit. A packed format may require extra alignment space. The figure assumes a 16-bit scale in the count, but reconstruction uses JavaScript precision to show the effect of the weight grid: quantizing the scale too would introduce another error.

InteractiveLocal scales

Absolute error: greater intensity indicates larger error. Four rows by 128 columns; groups do not cross rows.

Scales are FP16 in the count; the model uses symmetric 4 bits without stored zero point. Final groups may be shorter.

Granularity
32
Map
Bits per weight4.500
Minimum / maximum scales0.0653 / 0.1808
Mean squared error0.00135
Compare per-tensor, per-channel and per-group scales; switch between weight map and absolute error. The count adds one FP16 scale per group.

Matmul and requantization

In integer matmul with requantization, represent input and weights as xi≈sx(qx,i−zx)x_i\approx s_x(q_{x,i}-z_x) and wji≈sw,j(qw,ji−zw,j)w_{ji}\approx s_{w,j}(q_{w,ji}-z_{w,j}). Then

y^j=sxsw,j∑i(qx,i−zx)(qw,ji−zw,j).\hat y_j=s_xs_{w,j}\sum_i(q_{x,i}-z_x)(q_{w,ji}-z_{w,j}).

The sum is typically accumulated in INT32, and a quantized output uses another scale and zero point with rounding and saturation. The product of scales per output channel can be applied after the sum because it does not depend on ii. A different scale per input channel does depend on ii and cannot be extracted as one factor. The accumulator can overflow: bound the dimension and magnitudes or use another strategy.

Expanding the centered sum yields four terms: ∑iqx,iqw,ji\sum_iq_{x,i}q_{w,ji}, −zw,j∑iqx,i-z_{w,j}\sum_iq_{x,i}, −zx∑iqw,ji-z_x\sum_iq_{w,ji} and dzxzw,jd z_xz_{w,j}. The third can be precomputed while weights are fixed; the second depends on the input. If the weight is symmetric, zw,j=0z_{w,j}=0 removes two terms. To requantize an output with scale sys_y and zero point zyz_y, multiply the accumulator by sxsw,j/sys_xs_{w,j}/s_y, round, add zyz_y and saturate to the output range. In an entirely integer path, that real multiplication is approximated with a fixed-point multiplier and a shift, with its own rounding error.

Taxonomy and codebooks

Post-training and quantization-aware quantization distinguishes PTQ, which quantizes after training, from QAT, which simulates the grid during training. W4A16 denotes four-bit weights and 16-bit activations; W8A8 quantizes both. The labels alone do not specify granularity, metadata or kernel.

In QAT the forward pass usually applies simulated quantization and reconstruction while the optimizer keeps higher-precision parameters. Since rounding has zero derivative almost everywhere and discontinuities, a surrogate gradient estimator is often used. It is a training approximation, not the exact derivative of rounding. PTQ avoids that tuning but needs calibration compatible with deployment; QAT adds training cost and may adapt better to the chosen format’s error. The study by Nagel et al. presents both approaches and their tradeoffs.

Codebook quantization assigns each value to a table center, which can be nonuniform. Lloyd’s algorithm alternates assignment and center updates to minimize squared error on the sample. Indices consume bits and the codebook also takes memory. Rate-distortion theory studies lossy compression limits under a specified source and distortion; it does not guarantee that a particular table reaches them.

With a codebook of KK centers, a fixed-length index costs ⌈log⁡2K⌉\lceil\log_2 K\rceil bits plus the shared cost of the table. Quantiles can reserve more levels for dense regions, while k-means adapts centers to squared error. The codebook can reduce error for the same number of indices, but requires lookups or decoding that a kernel must support. Best numerical error does not automatically mean lowest time or best task accuracy.

An affine quantizer from scratch

[ ]Quantization and reconstructionBrowser
import numpy as np

def affine(x, low, high, bits=8):
    if not low < high or low > 0 or high < 0:
        raise ValueError('el rango debe ser no degenerado e incluir cero')
    qmax = 2**bits - 1
    scale = (high-low)/qmax
    zero = int(np.clip(np.rint(-low/scale), 0, qmax))
    q = np.clip(np.rint(np.asarray(x)/scale)+zero, 0, qmax).astype(np.int32)
    return q, scale, zero, scale*(q-zero)

q, s, z, xhat = affine([-0.4, 0.5, 1.2], -0.4, 1.2)
print('escala', s, 'punto cero', z, 'enteros', q, 'reconstrucción', xhat)

The rounded zero point slightly shifts the endpoints: in this example −0.4-0.4 reconstructs as approximately −0.40157-0.40157. For 0.50.5, the integer is 144 and its reconstruction is approximately 0.501960.50196. Endpoint rounding is not an implementation error: it follows from requiring zero to be exactly representable with an integer zero point.

Lab: choosing the range

Compare two seeded samples: one normal and one with Laplace tails. They are not real weights or results from a trained model. To isolate the tradeoff we use a symmetric quantizer with representable endpoints. The function calculates squared clipping error separately from rounding error on the clipped signal. Since outside the range the clipped endpoint is already a grid level, one of the two errors is zero for each sample and their sum matches total error up to numerical precision.

[ ]Calibrate by squared error and percentileBrowser
import numpy as np

def symmetric(x, bits, bound):
    if bound <= 0 or bits < 2:
        raise ValueError('rango positivo y al menos dos bits')
    Q = 2**(bits-1)-1
    scale = bound/Q
    codes = np.clip(np.rint(np.asarray(x)/scale), -Q, Q).astype(np.int32)
    return codes, scale, codes*scale

def error_parts(x, reconstruction, bound):
    clipped = np.clip(x, -bound, bound)
    clip_error = np.mean((x-clipped)**2)
    round_error = np.mean((clipped-reconstruction)**2)
    assert np.isclose(clip_error+round_error, np.mean((x-reconstruction)**2))
    return clip_error, round_error

gen = np.random.default_rng(31)
normal = gen.normal(size=4096)
laplace = gen.laplace(scale=1/np.sqrt(2), size=4096)
for label, x in [('normal', normal), ('laplace', laplace)]:
    candidates = np.linspace(np.max(np.abs(x))*.1, np.max(np.abs(x)), 100)
    errors = np.array([np.mean((x-symmetric(x, 4, bound)[2])**2) for bound in candidates])
    best = candidates[np.argmin(errors)]
    for name, bound in [('máximo', np.max(np.abs(x))), ('percentil 99', np.quantile(np.abs(x), .99)), ('MSE', best)]:
        _, _, rec = symmetric(x, 4, bound)
        clipping, rounding = error_parts(x, rec, bound)
        print(label, name, 'rango', round(bound, 3), 'MSE', round(clipping+rounding, 5),
              'recorte', round(clipping, 5), 'redondeo', round(rounding, 5))

The range minimizing MSE in this sample was chosen among 100 candidates, not by continuous optimization. The percentile criterion ignores how costly errors in discarded samples are, so it need not match minimum MSE. When calibrating activations, separate calibration and evaluation data and preserve the usage domain.

A KL-divergence criterion requires defining histograms and treatment of empty cells. The following uses fixed bins, a small smoothing mass and the same edges for originals and reconstructions. This is one pedagogical implementation, not an equivalent of every entropy calibration used in libraries.

[ ]A KL divergence searchBrowser
def histogram_kl(original, reconstructed, edges, epsilon=1e-8):
    p = np.histogram(original, bins=edges)[0].astype(float) + epsilon
    q = np.histogram(reconstructed, bins=edges)[0].astype(float) + epsilon
    p /= p.sum()
    q /= q.sum()
    return np.sum(p*np.log(p/q))

x = laplace
extent = np.max(np.abs(x)) + 1e-6
edges = np.linspace(-extent, extent, 33)
candidates = np.linspace(extent*.2, extent, 50)
scores = [histogram_kl(x, symmetric(x, 4, bound)[2], edges) for bound in candidates]
best_kl = candidates[np.argmin(scores)]
print('rango KL aproximado:', round(best_kl, 3), 'KL:', round(min(scores), 4))

Changing the number of bins or smoothing changes the criterion and may change the chosen range. Histogram KL is not directly model loss or necessarily the best metric for a task.

For granularity, cost depends on shape and whether groups align with rows. This example builds four channels with different magnitudes, quantizes each group independently and counts one 16-bit scale per group. It includes incomplete final groups: a real format can also add padding so kernels read aligned blocks.

[ ]Compare channel and group granularitiesBrowser
rng = np.random.default_rng(22)
matrix = rng.normal(size=(4, 64))*np.array([.1, .4, 1., 2.])[:, None]
def reconstruct_groups(matrix, bits, group):
    result = np.empty_like(matrix)
    scales = []
    for i, row in enumerate(matrix):
        for start in range(0, row.size, group):
            part = row[start:start+group]
            bound = np.max(np.abs(part))
            if bound == 0:
                result[i, start:start+group] = 0
                scales.append(1.)
            else:
                _, scale, rec = symmetric(part, bits, bound)
                result[i, start:start+group] = rec
                scales.append(scale)
    return result, np.array(scales)

_, scale_tensor, rec_tensor = symmetric(matrix, 4, np.max(np.abs(matrix)))
print('tensor MSE:', round(np.mean((matrix-rec_tensor)**2), 6), 'bits/peso:', 4+16/matrix.size)
for group in (64, 16):
    rec, scales = reconstruct_groups(matrix, 4, group)
    print('grupo', group, 'MSE:', round(np.mean((matrix-rec)**2), 6),
          'bits/peso:', 4+16*len(scales)/matrix.size)

With one scale per row, the group has 64 values in this matrix. In this run the four magnitudes fit better separately than with a global scale; the result belongs to this sample. Reducing group size does not guarantee an improvement in a downstream metric, although it gives more freedom to fit the grid to the local range.

Integer matmul and accumulation

With one activation scale per tensor and one per weight row, the centered integer product is calculated before applying scales. Expanding (qx−zx)(qw−zw)(q_x-z_x)(q_w-z_w) allows sum terms to be precomputed to reduce work, while respecting dimensions and sign. The next cell uses INT64 to check that the sum fits in INT32 before conversion. The reconstructed product is compared with multiplication of the already quantized tensors, not the original values.

[ ]Integer product and requantizationBrowser
X = np.array([[0.1, -0.4, 0.8], [-0.2, 0.3, 0.5]])
W = np.array([[0.2, -0.1, 0.6], [-0.7, 0.2, 0.1]])
qx, sx, zx, xr = affine(X, -1, 1)
weight_codes, scales, weight_rec = [], [], []
for row in W:
    q, s, rec = symmetric(row, 8, np.max(np.abs(row)))
    weight_codes.append(q)
    scales.append(s)
    weight_rec.append(rec)
qw = np.asarray(weight_codes, dtype=np.int32)
wide = (qx.astype(np.int64)-zx) @ qw.astype(np.int64).T
assert np.max(np.abs(wide)) <= np.iinfo(np.int32).max
acc = wide.astype(np.int32)
y = acc.astype(float)*sx*np.asarray(scales)[None,:]
reference = xr @ np.asarray(weight_rec).T
assert np.allclose(y, reference)
qy, sy, zy, yr = affine(y, -2, 2)
print('acumulador INT32:', acc.tolist())
print('producto descuantizado:', np.round(y, 5))
print('salida recuantizada:', qy.tolist(), 'reconstrucción:', np.round(yr, 5))

A fast implementation does not convert each operation individually in Python: it uses instructions and kernels that fuse reading, multiplication and scaling. The centered integer may need more bits than the original integer; a conservative bound is dmax⁡∣qx−zx∣max⁡∣qw−zw∣d\max|q_x-z_x|\max|q_w-z_w|. If it exceeds the accumulator’s maximum there is no guarantee against overflow.

Lab: a small MLP and data separation

Train a two-layer classifier on a known synthetic distribution and compare accuracy before and after quantizing its weights. The seed, split and rule are shown in full. Evaluation measures accuracy on unseen examples from the same generator, not LLM perplexity or quality. This result is not extrapolated to another model.

[ ]Train an MLP and quantize its weightsBrowser
rng = np.random.default_rng(43)
features = rng.normal(size=(800, 2))
labels = ((features[:,0]**2 + features[:,1]**2) > 1.2).astype(float)[:,None]
train_x, test_x = features[:600], features[600:]
train_y, test_y = labels[:600], labels[600:]
W1 = rng.normal(0, .5, size=(2, 16)); b1 = np.zeros((1,16))
W2 = rng.normal(0, .5, size=(16, 1)); b2 = np.zeros((1,1))
def forward(x, w1, b1, w2, b2):
    hidden = np.tanh(x@w1+b1)
    logits = np.clip(hidden@w2+b2, -30, 30)
    return hidden, 1/(1+np.exp(-logits))
for _ in range(400):
    h, p = forward(train_x, W1, b1, W2, b2)
    dz = (p-train_y)/len(train_x)
    gW2 = h.T@dz; gb2 = dz.sum(axis=0, keepdims=True)
    dh = ([email protected])*(1-h*h)
    gW1 = train_x.T@dh; gb1 = dh.sum(axis=0, keepdims=True)
    W1 -= .2*gW1; b1 -= .2*gb1; W2 -= .2*gW2; b2 -= .2*gb2
def accuracy(w1, w2):
    return np.mean((forward(test_x,w1,b1,w2,b2)[1] >= .5) == test_y)
print('sin cuantizar:', round(accuracy(W1,W2), 3))
for bits in (2, 3, 4, 8):
    w1 = symmetric(W1, bits, np.max(np.abs(W1)))[2]
    w2 = symmetric(W2, bits, np.max(np.abs(W2)))[2]
    print(bits, 'bits:', round(accuracy(w1,w2), 3))

This test keeps biases and activations in floating-point precision. Differences between precisions can vary with seed and distribution. To select a configuration, reserve a validation set separate from test and do not choose the best variant by repeatedly looking at the test set.

Local lab: packed weights from a real model

This lab uses SmolLM2-135M and the test split of WikiText-2 raw. It requires PyTorch, Transformers and Datasets, and downloads the model and dataset if uncached. Both revisions are pinned. For a short check, 1016 tokens are scored in eight independent windows of 128 tokens; the first token of each window is not scored. This is not benchmark perplexity over the entire test set and does not use sliding context. Set MAX_TOKENS to None to traverse complete windows of the entire split, and specify the protocol before comparing with other work.

Internal linear layers are replaced by a teaching implementation with groups of 128, FP16 scale and INT8 weights or two four-bit codes per byte. The head and embeddings retain their original precision. Each call unpacks weights to floating point: it is not a fused INT4 kernel and can be slower than the original model. Persistent memory counts tensors and buffers without double-counting shared storage; peak CUDA includes temporaries during measurement. Time includes cached generation, with prior warmup and CUDA synchronization. Since hardware may be shared, repeat several times and report the distribution of times; do not treat one pass as a GPU property.

[ ]Quantize, evaluate and measureLocal GPU
import time, math, gc
import torch
from torch import nn
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset

torch.set_num_threads(4)
MODEL = 'HuggingFaceTB/SmolLM2-135M'
REV = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
MAX_TOKENS = 1024  # None: todas las ventanas completas del test
device = 'cuda' if torch.cuda.is_available() else 'cpu'
dtype = torch.bfloat16 if device == 'cuda' and torch.cuda.is_bf16_supported() else torch.float32
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REV)
test = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1', split='test', revision='b08601e04326c79dfdd32d625aee71d232d685c3')
text = chr(10).join(row['text'] for row in test if row['text'].strip())
tokens = tokenizer(text, return_tensors='pt', truncation=MAX_TOKENS is not None, max_length=MAX_TOKENS).input_ids[0]
prompt = tokenizer('Explain how quantization changes neural network inference:', return_tensors='pt').input_ids.to(device)

class PackedLinear(nn.Module):
    def __init__(self, layer, bits=4, group=128):
        super().__init__()
        assert bits in (4, 8) and group % 2 == 0
        self.bits, self.group = bits, group
        self.rows, self.cols = layer.weight.shape
        groups = math.ceil(self.cols/group)
        w = F.pad(layer.weight.detach().float(), (0, groups*group-self.cols)).reshape(self.rows, groups, group)
        Q = 2**(bits-1)-1
        scale = w.abs().amax(dim=-1).clamp_min(1e-8)/Q
        q = (w/scale[...,None]).round().clamp(-Q,Q).to(torch.int8)
        self.register_buffer('scale', scale.to(torch.float16))
        if bits == 4:
            u = (q.to(torch.int16)+7).to(torch.uint8)
            packed = u[...,0::2] | (u[...,1::2] << 4)
        else:
            packed = q
        self.register_buffer('packed', packed)
        self.register_buffer('bias', layer.bias.detach().clone() if layer.bias is not None else None)

    def forward(self, x):
        if self.bits == 4:
            u = self.packed
            q = torch.stack(((u & 15).to(torch.int16)-7, (u >> 4).to(torch.int16)-7), dim=-1).flatten(-2)
        else:
            q = self.packed
        w = (q.to(x.dtype)*self.scale.to(x.dtype)[...,None]).reshape(self.rows,-1)[:,:self.cols]
        return F.linear(x, w, self.bias)

def replace_linears(module, bits):
    for name, child in list(module.named_children()):
        if isinstance(child, nn.Linear):
            setattr(module, name, PackedLinear(child, bits))
        else:
            replace_linears(child, bits)

def test_packing():
    torch.manual_seed(31)
    layer = nn.Linear(131, 3)
    for bits in (4, 8):
        packed = PackedLinear(layer, bits)
        w = F.pad(layer.weight.detach().float(), (0, 125)).reshape(3, 2, 128)
        Q = 2**(bits-1)-1
        scales = w.abs().amax(dim=-1).clamp_min(1e-8)/Q
        expected = (w/scales[...,None]).round().clamp(-Q,Q).to(torch.int16)
        if bits == 4:
            u = packed.packed
            actual = torch.stack(((u & 15).to(torch.int16)-7, (u >> 4).to(torch.int16)-7), dim=-1).flatten(-2)
        else:
            actual = packed.packed.to(torch.int16)
        assert torch.equal(expected, actual)
    print('empaquetado verificado, incluido grupo final incompleto')

def persistent_bytes(model):
    seen, total = set(), 0
    for tensor in list(model.parameters()) + list(model.buffers()):
        storage = tensor.untyped_storage()
        ptr = storage.data_ptr()
        if ptr not in seen:
            seen.add(ptr)
            total += storage.nbytes()
    return total

@torch.inference_mode()
def perplexity(model):
    loss, count = 0., 0
    for start in range(0, len(tokens)-128+1, 128):
        ids = tokens[start:start+128].unsqueeze(0).to(device)
        logits = model(ids, use_cache=False).logits[:, :-1].float()
        loss += F.cross_entropy(logits.reshape(-1, logits.shape[-1]), ids[:,1:].reshape(-1), reduction='sum').item()
        count += 127
    return math.exp(loss/count), count

@torch.inference_mode()
def speed(model):
    model.generate(prompt, max_new_tokens=3, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    if device == 'cuda': torch.cuda.synchronize()
    start = time.perf_counter()
    output = model.generate(prompt, max_new_tokens=32, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    if device == 'cuda': torch.cuda.synchronize()
    return (output.shape[1]-prompt.shape[1])/(time.perf_counter()-start)

test_packing()
for bits in (None, 8, 4):
    model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REV, dtype=dtype).eval()
    if bits is not None:
        replace_linears(model.model.layers, bits)
    model.to(device)
    if device == 'cuda': torch.cuda.reset_peak_memory_stats()
    ppl, scored = perplexity(model)
    rate = speed(model)
    peak = torch.cuda.max_memory_allocated() if device == 'cuda' else 0
    print('bits', bits, 'device', device, 'dtype', dtype, 'persistent_bytes', persistent_bytes(model),
          'peak_allocated', peak, 'scored_tokens', scored, 'ppl', round(ppl,4), 'tokens_per_s', round(rate,3))
    del model
    gc.collect()
    if device == 'cuda': torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The experiment keeps floating-point activations and quantizes weights by group. It does not measure W8A8. The next optional test checks native INT8 matmul if the PyTorch version and hardware expose it. It is an example of centered integers without scales, not the kernel from the previous class. The underscore name indicates an internal interface that can change: if it fails, this is reported and execution continues. Compare input codes, scales and results before measuring an optimized library. A fast integer operation and compact representation are distinct properties.

[ ]Check a native INT8 matmulLocal GPU
if device == 'cuda' and hasattr(torch, '_int_mm'):
    a = torch.randint(-128, 128, (64, 128), dtype=torch.int8, device=device)
    b = torch.randint(-128, 128, (128, 64), dtype=torch.int8, device=device)
    try:
        c = torch._int_mm(a, b)
        expected = a.cpu().to(torch.int32) @ b.cpu().to(torch.int32)
        assert torch.equal(c.cpu(), expected)
        print('INT8 nativa: igual al producto INT32 de referencia; forma', tuple(c.shape))
    except RuntimeError as exc:
        print('INT8 nativa no disponible para esta configuración:', str(exc)[:200])
else:
    print('INT8 nativa no disponible en este dispositivo o versión')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a short run on RTX 3060 with BF16, using this model and protocol, recorded persistent memory was 269030272 bytes unquantized, 173506432 with 8 bits and 115998592 with 4 bits. Perplexity over the 1016 scored tokens was 36.0877, 36.2329 and 58.9927 respectively. This is a small sample and simple quantizer, not a complete method comparison or precise estimate of general quality. The teaching decompression was slower than BF16 in that run; time depends on the GPU’s shared state and is not presented as a stable benchmark. Uncompressed embeddings and head explain part of the difference between the total memory reduction factor and the internal weight reduction factor.

Exercises

Numeric
With range [-0.4, 1.2], uint8 and ties-to-even rounding, what is the reconstruction of 0.5 using this lesson's recipe?
Numeric
With 4 bits per weight and groups of 128, each with FP16 scale and FP16 zero point, how many bits per weight are used without padding?
Proof
Prove: Derive the variance of uniform error and the ideal gain per bit.
0
Assume error E uniform on [-Δ/2, Δ/2], without clipping.

Step 1 of 3. What is the mean?

Quiz
Why can an output-channel scale be applied after the sum in a linear layer?
Code
Implement quantize_per_group(w, bits, group) and dequantize(q, scales, group). Use contiguous groups, symmetric range [-Q,Q], Q = 2^(bits-1)-1, maximum absolute scale per group and 1 for zero groups.
import numpy as np
def quantize_per_group(w, bits, group):
  pass
def dequantize(q, scales, group):
  pass
Shift+Enter to run
Key idea
Quantization trades precision for memory and computation: the grid, clipping, granularity and kernel must be chosen and measured together.