AI Hints
Home›Fine-Tuning LLMs Tutorial›Quantization and QLoRA
Fine-Tuning LLMs · Lesson 58 of 120

Quantization

Fewer bits per number.

⏱ 2 min read▶ Video at 1:30:40🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

LoRA shrank the memory for training. But the frozen model itself is still big. An eight billion parameter model needs sixteen gigabytes, just to load. Quantization shrinks the model itself.

  • LoRA shrank training memory
  • The model is still big
  • Quantization shrinks it

The idea

Quantization means storing each weight with fewer bits. Instead of a sixteen bit decimal, we store a small whole number, like eight bits, or even four. Plus one scale number, shared by a group of weights, to turn them back into decimals. We lose a tiny bit of precision, but save a lot of memory.

keyvalue
Quantizestore weights with fewer bits
Storesmall whole numbers
Plusa shared scale
Tradetiny precision for big savings

Quantize by hand

Let's quantize six weights to eight bits, by hand. The scale maps the biggest weight to one hundred and twenty seven, the largest eight bit value. We divide by the scale, round, and store whole numbers. To use them, we multiply by the scale again. Run it. The weights became small whole numbers. Restored, they're almost exactly the originals. The biggest error is three thousandths.

app.pypython
import torch

w = torch.tensor([0.82, -0.31, 0.05, -1.27, 0.66, 0.003])
scale = w.abs().max() / 127                 # the biggest weight maps to 127
q = torch.round(w / scale).to(torch.int8)   # store small whole numbers
back = q.float() * scale                    # turn them back into decimals
print("original:", [round(x, 3) for x in w.tolist()])
print("int8:    ", q.tolist())
print("restored:", [round(x, 3) for x in back.tolist()])
print(f"biggest error: {(w - back).abs().max():.4f}")
Output
original: [0.82, -0.31, 0.05, -1.27, 0.66, 0.003]
int8:     [82, -31, 5, -127, 66, 0]
restored: [0.82, -0.31, 0.05, -1.27, 0.66, 0.0]
biggest error: 0.0030

Summary

Let's recap. Quantization stores weights as small whole numbers, plus a scale. Eight bits halves the memory of sixteen bits. And the error is tiny. Next, going all the way down to four bits.

Key takeaways
  • Fewer bits per weight
  • Whole numbers + scale
  • Tiny error
Next up: 4-bit NF4 — a quarter of the memory