AI Hints
Home›Fine-Tuning LLMs Tutorial›Memory and Data Types
Fine-Tuning LLMs · Lesson 19 of 120

Parameters and Memory

How big is a model?.

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

The biggest problem in fine-tuning isn't the code. It's memory. Before we train anything, let's learn to estimate how much memory a model needs. It's simple maths.

  • The big problem: memory
  • Estimate it first
  • It's simple maths

The basic rule

Every parameter is a number. And every number takes some bytes of memory. So the memory for the weights is the number of parameters, times the bytes per number. Remember, a billion bytes is one gigabyte. So a model with one billion parameters, at two bytes each, needs about two gigabytes.

keyvalue
Memoryparameters × bytes each
1 billion bytes≈ 1 GB
1B params × 2 bytes≈ 2 GB
8B params × 2 bytes≈ 16 GB

Measure it

Let's check the rule on a real model. We load it twice. Once in float thirty two, which uses four bytes per number. And once in b float sixteen, which uses two. Get memory footprint tells us the real size. Run it. Five hundred and thirty eight megabytes, then exactly half. The rule works.

app.pypython
import torch
from transformers import AutoModelForCausalLM

name = "HuggingFaceTB/SmolLM2-135M"
for dtype in [torch.float32, torch.bfloat16]:
    model = AutoModelForCausalLM.from_pretrained(name, dtype=dtype)
    print(f"{str(dtype):15} {model.get_memory_footprint() / 1e6:.0f} MB")
Output
torch.float32   538 MB
torch.bfloat16  269 MB

Summary

Let's recap. Weight memory is parameters times bytes per number. One billion bytes is about a gigabyte. And halving the bytes halves the memory. Next, the different number formats, called data types.

Key takeaways
  • params × bytes
  • 1e9 bytes ≈ 1 GB
  • Fewer bytes, less memory
Next up: Data Types — float32, bfloat16 and more