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

4-bit NF4

A quarter of the memory.

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

Eight bits worked beautifully. So how low can we go? Let's try four bits, and two bits, and watch what happens to the error.

  • Eight bits worked
  • How low can we go?
  • Watch the error

Fewer and fewer bits

We use the same six weights. For each bit size, we work out how many levels we can store. Then we round to those levels, and measure the average error. Run it. Eight bits is almost perfect. Four bits is rougher, but still close. Two bits destroys the weights. Every value becomes one of only three numbers.

app.pypython
import torch

w = torch.tensor([0.82, -0.31, 0.05, -1.27, 0.66, 0.003])
for bits in [8, 4, 2]:
    levels = 2 ** (bits - 1) - 1              # 127 for 8 bits, 7 for 4 bits, 1 for 2 bits
    scale = w.abs().max() / levels
    back = torch.round(w / scale) * scale
    print(f"{bits} bits: {[round(x, 2) for x in back.tolist()]}  "
          f"error {(w - back).abs().mean():.3f}")
Output
8 bits: [0.82, -0.31, 0.05, -1.27, 0.66, 0.0]  error 0.001
4 bits: [0.91, -0.36, 0.0, -1.27, 0.73, 0.0]  error 0.043
2 bits: [1.27, -0.0, 0.0, -1.27, 1.27, 0.0]  error 0.237

NF4: smarter four bits

Four bits is the sweet spot, if we're clever. Model weights aren't spread evenly. Most are close to zero, and few are large. NF4, which means normal float four, puts more of its sixteen levels near zero, where most weights are. So it loses much less than simple four bit rounding.

keyvalue
4 bits16 levels
Weightsmostly near zero
NF4more levels near zero
Resultmuch less error

Memory for an 8B model

Here's what that means for an eight billion parameter model. In b float sixteen, the weights need sixteen gigabytes. In eight bits, eight. In NF4, about four and a half, including the scales. That fits on a normal gaming GPU.

FormatWeight memory
bfloat16~16 GB
int8~8 GB
NF4 (4-bit)~4.5 GB
Fits ona 12–24 GB gaming GPU

Summary

Let's recap. Fewer bits mean more error. Four bits is the sweet spot. NF4 puts its levels where most weights are. And an eight billion model shrinks to about four and a half gigabytes. Next, combining this with LoRA. QLoRA.

Key takeaways
  • 2 bits: too rough
  • NF4: the sweet spot
  • 8B → ~4.5 GB
Next up: QLoRA — 4-bit model + LoRA