Block-wise 4-bit codebook quantization with double-quantized scales

QLoRA-style 4-bit storage does not use an evenly spaced grid. Each block of weights is divided by its absmax, and every normalized value is snapped to the nearest entry of a fixed 16-level codebook whose levels are packed near 0, where most weights sit. To save more memory, the per-block absmax values are themselves quantized to 8 bits (double quantization).

Write nf4_quantize(w, block, codebook, scale_group) for a 1D float array w whose length is a multiple of block. The tests use this 16-level normal-float style codebook:
[-1.0, -0.6962, -0.5251, -0.3949, -0.2844, -0.1848, -0.0911, 0.0, 0.0796, 0.1609, 0.2461, 0.3379, 0.4407, 0.5626, 0.723, 1.0]

Steps:
1. Split w into blocks of size block. absmax[b] = max |w| in block b (use 1.0 if it is 0).
2. codes = index of the nearest codebook entry to w / absmax[block of w]. Ties go to the lower index.
3. Double quantization: split absmax into groups of scale_group consecutive blocks (the last group may be shorter). For each group, gscale = max(absmax in group) / 127 and qscale = np.round(absmax / gscale) as int.
4. Dequantize with the 8-bit scales: absmax_hat = qscale * gscale, w_hat = codebook[codes] * absmax_hat[block].
Return a dict with "codes" (int array, len(w)), "qscale" (int array, one per block), "gscale" (float array, one per group), "w_hat" (float array) and "mse" = mean((w - w_hat) ** 2).

Signaturedef nf4_quantize(w, block, codebook, scale_group)

Understand the idea

This 4-bit format does not use evenly spaced levels. Each block of weights is divided by its largest absolute value, and each normalised number is snapped to the nearest of 16 fixed levels, packed tightly near 0 where most weights live. To save more memory, the per-block absmax values are themselves stored in 8 bits. Worked example: block [0.2, -0.8, 0.4, 0.1], absmax 0.8, normalised [0.25, -1, 0.5, 0.125]. Nearest levels: 0.25 to 0.2461 (index 10), -1 to -1.0 (index 0), 0.5 to 0.4407 (index 12, since 0.0593 beats 0.0626), 0.125 to 0.1609 (index 9). Codes [10, 0, 12, 9]. Double quant for a group with absmax [0.8, 0.3]: gscale = 0.8 / 127 = 0.0063, qscale = [127, round(47.6) = 48], so the second block's absmax is rebuilt as 48 * 0.0063 = 0.3024. Rule: codes by nearest level (lower index on ties); per group gscale = max absmax / 127, qscale = round(absmax / gscale); w_hat = level[code] * qscale * gscale. Dequantize with the 8-bit scales, not the exact absmax. This is the storage format behind QLoRA fine-tuning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 6 blocks, groups of 4nf4_quantize(_w, 8, _cb, 4)
  • Sample 2: zero blocknf4_quantize(_w2, 4, _cb, 2)