← Math
Math

Quantization and numeric precision

Will the 12B model fit on the 24 GB GPU?

Budget model memory and measure the error introduced by a smaller number format.

Outcome

Work out what each format costs in memory, range and precision, quantize a tensor to int8, and choose per-tensor or per-row scales when one weight is an outlier.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Quantization
Storing values in fewer bits, here int8 codes from −127 to 127 multiplied by one scale.
bf16 Also bfloat16
A 16-bit float with fp32’s range and only 8 significant bits; fp16 has more precision and a largest finite value of 65,504.
Absmax scale
The largest magnitude divided by 127, so that value maps to ±127.
Clipping
Forcing a value outside the representable range to the nearest end of it.
RMSE
Root mean squared error: √(mean of the squared differences) over all values.
Accumulation precision
The format sums are kept in; libraries add 16-bit and int8 products in fp32 or int32.

Why this matters

Whether a model runs on the hardware you have is often decided by the number format of its weights. Each format trades memory against range and precision, and the conversion to int8 can quietly damage a layer when a single weight is much larger than the rest.

This lesson assumes floating-point basics, rounding and square roots.

Representing weights with fewer bits

Range is the span of representable values; precision is the spacing between them. Floating-point formats divide their bits between an exponent and a fraction, so equal storage sizes can provide different ranges and precision.

Quantization maps weights onto a finite set of codes. A scale converts each code back into an approximate weight, and the reconstruction error measures what that mapping loses. Memory arithmetic and reconstruction error together guide the format choice; acceptable answer quality still needs evaluation on the model’s tasks.

01Four ways to store a weight

Four ways to store a weight

Your team self-hosts a 12-billion-parameter open-weights model for the support assistant, on one 24 GB GPU. In bf16 the weights are exactly 24 GB, so the plan is int8. The conversion runs, but one layer’s answers get noticeably worse, and nobody can say why from the summary error.

Formats for model weights
FormatBitsLargest valueStep just above 1
fp3232 (8 exponent, 23 fraction)about 3.4 × 10³⁸2⁻²³ ≈ 0.00000012
fp1616 (5 exponent, 10 fraction)65,5042⁻¹⁰ ≈ 0.00098
bf1616 (8 exponent, 7 fraction)about 3.4 × 10³⁸2⁻⁷ ≈ 0.0078
int88127 × scaleone scale

fp16 and bf16 both take two bytes and split them differently. fp16 keeps more fraction bits but its largest finite value is 65,504, below some large activations. bf16 keeps fp32’s range and gives up precision: it represents integers exactly only up to 256, so a bf16 running total of ones stops growing at 256 under nearest-even rounding. That is why libraries keep sums in fp32 even when weights are 16-bit.

JavaScript numbers are 64-bit floats. Math.fround rounds to fp32, and recent engines add Float16Array for fp16; model weights usually reach Node.js as raw bytes from a .safetensors file.

02What fits on the GPU

What fits on the GPU

Weight memory is the parameter count times the bytes per weight: 12 billion parameters take 48 GB in fp32, 24 GB in fp16 or bf16 and 12 GB in int8, using decimal GB = 10⁹ bytes. This first budget counts weight payload; scales, metadata and runtime allocations also need room. The server also needs room for the KV cache, which grows with every token of every open conversation; the team budgets 6 GB for it. bf16 fills the 24 GB card on its own, so int8 is the format that leaves room.

An 8B model in bf16 on the same GPU, with the same 6 GB of headroom?

03int8 with a scale

int8 with a scale

Signed int8 can store −128 through 127; this model deliberately uses the symmetric codes −127 through 127 and one floating-point scale per tensor. The absmax scale is the largest magnitude divided by 127, so that weight becomes ±127 and every other weight rounds to the nearest code, with exact half ties away from zero: ±0.5 become ±1. This is our conversion policy; other quantizers can choose another tie rule. Taking the largest signed value instead would clip a large negative weight. Predict both lines. Q and P use 1..10,000 total finite weights, with P a nonempty rectangular matrix. For every nonzero tensor and nonzero row used in either plan, the computed peak/127 scale must be finite, positive and representable; every quotient and reconstructed error is finite, rounded codes fit the declared symmetric range, and squared errors and their accumulated sums remain finite. An all-zero tensor or row remains valid with zero codes and zero scale. These are valid-input preconditions; this lab does not ask the learner to implement general underflow or overflow admission.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The same four weights quantized to int8 alone, then next to one outlier.
// This model uses nearest codes with half ties away from zero.
const roundCode = (x: number) => Math.sign(x) * Math.round(Math.abs(x));
const codes = (ws: number[]) => {
  const scale = Math.max(...ws.map(Math.abs)) / 127; // absmax: the largest magnitude maps to 127

  return ws.map((w) => roundCode(w / scale)).join(" ");
};

const small = [0.031, -0.012, 0.045, -0.027];

console.log(codes(small));
console.log(codes([...small, 2.4]));

Alone, the four small weights use codes up to 127. Next to 2.4 the scale grows to about 0.019, and they are left with the codes 2, −1, 2 and −1: four distinct weights stored as two values.

04One outlier sets the scale

One outlier sets the scale

Trained models often have a few values far larger than the rest; in large language models these outliers are well documented. Giving each row of a weight matrix its own scale keeps an outlier from coarsening the other rows. For the complete 3 × 4 diagnostic matrix, rows are (0.031, −0.012, 0.045, −0.027), (0.018, −0.039, 0.024, 0.009) and (2.4, 0.011, −0.033, 0.016). Each reconstructed weight is code × scale. Square each original-minus-reconstructed error, average all 12 squares, then take the square root: RMSE = √(Σ error² / 12). Use that same all-weight measure for both scaling plans; averaging row RMSEs would measure something else.

RMSE over all 12 weights, tolerance 0.004
ScalingRMSEWithin tolerance?
One scale for the tensor0.00588no
One scale per row0.00280yes: store per row
With a tolerance of 0.0001 neither scaling passes. What should the plan be?

05What the error does not say

What the error does not say

06Plan the quantized deployment

Plan the quantized deployment

The deployment needs enough runtime headroom as well as small weight files. Repair its memory check, then the absmax conversion, and use the layer’s reconstruction error to choose a storage plan.

In the frontend A format picker in Next.js and Svelte Optional

The model settings page can disable formats that would leave no room for the KV cache, using the same arithmetic as the server.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The model settings page: show which formats fit before an admin picks one.
type Fit = { name: string; gb: number; ok: boolean };

export function FormatPicker({
  fits,
  value,
  onChange
}: {
  fits: Fit[];
  value: string;
  onChange: (name: string) => void;
}) {
  return (
    <fieldset>
      <legend>Weight format</legend>
      {fits.map((f) => (
        <label key={f.name}>
          <input
            type="radio"
            name="format"
            checked={value === f.name}
            disabled={!f.ok}
            onChange={() => onChange(f.name)}
          />
          {f.name}: {f.gb.toFixed(1)} GB
          {f.ok ? "" : " (does not fit with the KV cache)"}
        </label>
      ))}
    </fieldset>
  );
}

Check this idea later
Activations in one layer reach 80,000. Which 16-bit format can hold them?
A tensor’s weights are 0.3, −0.6 and 0.2. What is the absmax scale?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The support assistant, the GPU budget and the weight values are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.