LLM engineering · Medium · 15 min

Quantisation by hand: float32 to int8 and back

A Q8 file stores each weight in fewer bits. Quantise eight weights to int8, restore them and measure the error, outlier included.

WEIGHTS holds eight weights of a model. Each takes 32 bits; you are going to store them in 8. Write four functions:

  1. quantize(weights): return { scale, q }. scale is the largest absolute value divided by 127 (or 1 when every weight is zero). q is an Int8Array with Math.round(w / scale) for each weight, clamped to the range -127 to 127.
  2. dequantize({ scale, q }): return a plain array with q[i] * scale.
  3. maxError(a, b): the largest absolute difference between two arrays of the same size (0 when they are empty).
  4. sizeBytes(count, bits): the bytes taken by count weights stored with bits bits each.

The round-trip error never exceeds half a step, scale / 2. WITH_OUTLIER is the same weights with a single value ten times larger: the step grows with it and every other weight loses precision. The challenges measure it with your functions.

Do not modify the input arrays.

Challenges 0/5

  • quantize works out the step and returns an Int8Array
  • Round trip: the error exists and stays within half a step
  • One outlier enlarges the step and the error of all the others
  • Edge cases: all zeros, an empty array and the input left alone
  • sizeBytes: going from 32 to 8 bits takes a quarter

function quantize(weights) {
  // scale = largest absolute value / 127 (1 when it is 0)
  // q = Int8Array of Math.round(w / scale), clamped to [-127, 127]
  return { scale: 1, q: Int8Array.from(weights, (w) => Math.round(w)) };
}

function dequantize({ scale, q }) {
  // a plain array with q[i] * scale
  return Array.from(q);
}

function maxError(a, b) {
  // the largest |a[i] - b[i]|
  return 0;
}

function sizeBytes(count, bits) {
  return count;
}

const packed = quantize(WEIGHTS);
console.log(packed.scale, Array.from(packed.q), maxError(WEIGHTS, dequantize(packed)));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

The letters Q8, Q5 and Q4 in the name of a GGUF file say how many bits store each weight, and that decides whether a model fits on your card. This is the simplest version of the idea: one step for the whole tensor. Real formats split the weights into small blocks, each with its own step, precisely because of what you see in the outlier challenge. Understanding that trade-off between size and error lets you choose a file on its merits instead of copying a recommendation. The memory sums for your machine are in the VRAM explorer.

Go deeper: the related guide →

This in production, with your data? Let's talk for 15 minutes →