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

Data Types

Float32, bfloat16 and more.

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

A computer can store a number with lots of detail, or with less detail. Less detail means less memory, but less precision. The format is called the data type, or d type.

  • Lots of detail, or less
  • Less detail = less memory
  • The format: dtype

Common data types

Float thirty two uses four bytes. It's very precise, and it's the default for training on a CPU. Float sixteen uses two bytes, but it can't hold very large numbers. B float sixteen also uses two bytes, and it can hold huge numbers, with less precision. It's the favourite for modern training. And int eight, and four bit formats, use even less. We'll meet those later, with QLoRA.

dtypeBytesNotes
float324precise, the CPU default
float162small range, can overflow
bfloat162big range, the modern favourite
int8 / 4-bit1 / 0.5for QLoRA, later

Precision you can see

Let's store pi, in three data types. Item gives us the stored value back. Element size gives the bytes per number. Then we print the largest number each sixteen bit type can hold. Run it. Float thirty two keeps seven correct digits. The sixteen bit types keep only three. And look at the maximum. Float sixteen stops at sixty five thousand. B float sixteen goes up to a number with thirty eight zeros.

app.pypython
import torch

x = torch.tensor(3.14159265358979)
for dtype in [torch.float32, torch.float16, torch.bfloat16]:
    y = x.to(dtype)
    print(f"{str(dtype):15} {y.item():.10f}  {y.element_size()} bytes")
print("float16 max:  ", torch.finfo(torch.float16).max)
print("bfloat16 max: ", torch.finfo(torch.bfloat16).max)
Output
torch.float32   3.1415927410  4 bytes
torch.float16   3.1406250000  2 bytes
torch.bfloat16  3.1406250000  2 bytes
float16 max:   65504.0
bfloat16 max:  3.3895313892515355e+38

Why bfloat16 wins

During training, some numbers get very big. In float sixteen, they can overflow, which means they become infinity, and training breaks. B float sixteen has the same big range as float thirty two. So it's half the memory, and it rarely breaks. Most modern GPUs support it.

keyvalue
float16 riskoverflow → infinity
bfloat16same range as float32
Memoryhalf of float32
GPUsmost modern ones support it

Summary

Let's recap. The data type sets how many bytes each number uses. Float thirty two is precise, but large. B float sixteen is half the size, with a big range. That's why it's the favourite for training. Next, why training needs much more memory than just the weights.

Key takeaways
  • float32: 4 bytes
  • bfloat16: 2 bytes, big range
  • int8 and 4-bit later
Next up: Training Memory — why training needs more