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:
quantize(weights): return{ scale, q }.scaleis the largest absolute value divided by 127 (or1when every weight is zero).qis anInt8ArraywithMath.round(w / scale)for each weight, clamped to the range -127 to 127.dequantize({ scale, q }): return a plain array withq[i] * scale.maxError(a, b): the largest absolute difference between two arrays of the same size (0when they are empty).sizeBytes(count, bits): the bytes taken bycountweights stored withbitsbits 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.
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 →