Scaling and Context Windows

Updated · 10 min read
hardPython 3.13aillmscaling-lawscomputecontext-windowkv-cache

Scaling laws describe how a language model's loss improves, smoothly and predictably, as you increase three things: the number of parameters, the amount of training data in tokens, and the compute spent on training. They explain why AI labs build ever-larger models and training clusters. Context windows are the other kind of scale: how many tokens a model can read at once, which costs memory and time every time the model runs.

The Three Things That Scale

QuantityDescription
Parameters (N)The model's weights; more parameters can store more patterns
Training tokens (D)How much text the model learns from
Training compute (C)It is used to measure the total arithmetic of training: about 6 × N × D floating-point operations (FLOPs)
LossFalls as a smooth curve as N, D and C grow, with smaller gains each time
Context windowIt is used to limit how many tokens the model reads at once, prompt and reply together

The rule C ≈ 6ND comes from counting: each token costs about 2 operations per parameter going forward and about 4 more for backpropagation.

Example: The Scale of Real Models

The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown. This program downloads only the small settings files of the three SmolLM2 sizes, counts their parameters from the settings, and estimates their training compute from the token counts on their model cards.

More parameters, more tokens, more compute; longer context costs memory and time
Python
from transformers import AutoConfig
 
# Training tokens from each model card on Hugging Face
family = {"SmolLM2-135M": 2e12, "SmolLM2-360M": 4e12, "SmolLM2-1.7B": 11e12}
 
def count_parameters(c):
    """Count weights from the config alone: embeddings plus every block."""
    head_dim = c.hidden_size // c.num_attention_heads
    attention = c.hidden_size * head_dim * (2 * c.num_attention_heads + 2 * c.num_key_value_heads)
    feed_forward = 3 * c.hidden_size * c.intermediate_size
    block = attention + feed_forward + 2 * c.hidden_size
    return c.vocab_size * c.hidden_size + c.num_hidden_layers * block + c.hidden_size
 
print(f"{'model':14}{'layers':>7}{'width':>7}{'parameters':>15}{'tokens':>8}{'tokens/param':>14}{'compute (FLOPs)':>17}")
for name, tokens in family.items():
    c = AutoConfig.from_pretrained(f"HuggingFaceTB/{name}")   # downloads only the small config file
    n = count_parameters(c)
    flops = 6 * n * tokens                                    # rule of thumb: 6 x parameters x tokens
    print(f"{name:14}{c.num_hidden_layers:7}{c.hidden_size:7}{n:15,}{tokens / 1e12:7.0f}T{tokens / n:14,.0f}{flops:17.1e}")
 
print("\nCompute-optimal rule of thumb (Chinchilla, 2022): about 20 tokens per parameter")
for name, n in [("135M", 135e6), ("1.7B", 1.7e9), ("70B", 70e9)]:
    print(f"  {name:5} model -> about {20 * n / 1e9:,.0f} billion tokens")
Output
model          layers  width     parameters  tokens  tokens/param  compute (FLOPs)
SmolLM2-135M       30    576    134,515,008      2T        14,868          1.6e+21
SmolLM2-360M       32    960    361,821,120      4T        11,055          8.7e+21
SmolLM2-1.7B       24   2048  1,711,376,384     11T         6,428          1.1e+23
 
Compute-optimal rule of thumb (Chinchilla, 2022): about 20 tokens per parameter
  135M  model -> about 3 billion tokens
  1.7B  model -> about 34 billion tokens
  70B   model -> about 1,400 billion tokens

Explanation:

  • count_parameters works from the settings alone: the embedding table, plus each block's attention, feed-forward network and norms. For the 135M and 360M models it gives exactly the numbers PyTorch counts after loading.
  • Bigger models are mostly wider: the 1.7B model has fewer layers than the 135M (24 against 30), but each is 2,048 numbers wide instead of 576.
  • Training compute grows fast: about 1.6 × 10²¹ FLOPs for the 135M model and 1.1 × 10²³ for the 1.7B, about 70 times more. The model cards list 64 H100 GPUs for the smallest and 256 for the largest.
  • The Chinchilla rule (from DeepMind's 2022 research) says that for a fixed compute budget, the best loss comes from about 20 tokens per parameter. Their 70-billion-parameter Chinchilla model, trained on 1.4 trillion tokens, beat much larger models trained on less data.
  • SmolLM2 trains far past that: about 14,868 tokens per parameter for the 135M model. Training longer than "compute-optimal" costs more once, but gives a small model that is cheaper to run for everyone afterward. Most recent small models do this.

Example: What Long Context Costs

While generating, a model keeps the keys and values of every earlier token so it doesn't recompute them: the KV cache. This program computes its size and times how long the 135M model takes to read prompts of different lengths on this computer.

Python
import time
 
import torch
from transformers import AutoConfig, AutoModelForCausalLM
 
# 1. Memory for the KV cache: the keys and values kept for every token in the context
for name in ["SmolLM2-135M", "SmolLM2-1.7B"]:
    c = AutoConfig.from_pretrained(f"HuggingFaceTB/{name}")
    head_dim = c.hidden_size // c.num_attention_heads
    per_token = 2 * c.num_hidden_layers * c.num_key_value_heads * head_dim * 2   # keys + values, 2 bytes each
    print(f"{name}: {per_token:,} bytes per token -> {per_token * 8192 / 1e6:,.0f} MB for 8,192 tokens")
 
# 2. Time to read a long prompt, on this computer's CPU
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model.eval()
torch.manual_seed(0)
print()
for n in [512, 1024, 2048, 4096]:
    ids = torch.randint(0, 49152, (1, n))
    with torch.no_grad():
        model(ids)                                   # warm up once
        start = time.perf_counter()
        model(ids)
        seconds = time.perf_counter() - start
    print(f"{n:5} tokens: {seconds:6.2f} s  ({seconds / n * 1000:.2f} ms per token)")
Output
SmolLM2-135M: 23,040 bytes per token -> 189 MB for 8,192 tokens
SmolLM2-1.7B: 196,608 bytes per token -> 1,611 MB for 8,192 tokens
 
  512 tokens:   1.29 s  (2.52 ms per token)
 1024 tokens:   3.17 s  (3.10 ms per token)
 2048 tokens:   7.97 s  (3.89 ms per token)
 4096 tokens:  23.33 s  (5.70 ms per token)

Explanation:

  • KV cache: for every token, each layer stores a key and a value for each key-value head. SmolLM2-135M needs 23,040 bytes per token, so a full 8,192-token context takes 189 MB. The 1.7B model needs 1,611 MB, partly because it is bigger and partly because it gives every one of its 32 heads its own keys and values, while the 135M shares 3 among 9 (grouped-query attention, from "Self-Attention").
  • Time per token rises with length: 2.52 ms per token for 512 tokens, but 5.70 ms for 4,096. Doubling from 2,048 to 4,096 tokens took almost three times as long (7.97 to 23.33 seconds), because attention compares every token with every earlier one.
  • These timings are one run on an Apple M5 laptop CPU, with the model in its stored 16-bit format; they vary between runs and a lot between machines. A GPU is far faster, but the growth with length is the same.

How Long Contexts Are Made Practical

TechniqueWhat it does
Grouped-query attentionShares keys and values across heads, shrinking the KV cache
FlashAttentionComputes attention in small tiles on the GPU, using far less memory; the result is the same
Position scaling (RoPE extensions)Stretches rotary positions so a model trained on short texts can read longer ones
Sliding-window attentionLets some layers attend only to nearby tokens
KV cache compressionStores keys and values in fewer bits, or drops ones that matter little
Prompt cachingHosted APIs reuse the work for a repeated prompt start, saving time and money

Frontier models today offer context windows from about 128,000 to over a million tokens, built from techniques like these. See "Context and Context Windows".

Common Mistakes

Thinking scale fixes everything. Larger models still hallucinate and make reasoning mistakes, and data quality matters as much as quantity.

Comparing models by parameter count alone. A smaller model trained on more and better data can beat a larger one.

Filling the context window by default. Longer prompts are slower and cost more, and the model may miss details in the middle.

Forgetting the KV cache in memory planning. Serving many users with long contexts can need more memory for caches than for the model itself.

Interview Corner

What do scaling laws say?

A model's loss falls predictably, as a power law, as parameters, training data and compute increase. The Chinchilla results showed that for a fixed compute budget, parameters and tokens should grow together, at about 20 tokens per parameter.

Why are long context windows expensive?

Attention compares every token with every earlier token, so the work grows with the square of the length, and the KV cache grows with every token in the context. Techniques like FlashAttention and grouped-query attention reduce, but don't remove, these costs.

Practice

Exercise: plan a model. Using C ≈ 6ND, estimate the compute to train a 7-billion-parameter model on 2 trillion tokens. How many times more is that than SmolLM2-1.7B? How many tokens would the Chinchilla rule suggest for it?

Check your understanding:

  1. Why do small models like SmolLM2 train on far more than 20 tokens per parameter?
  2. What is stored in the KV cache, and why does it grow with the context?
  3. Why did doubling the prompt from 2,048 to 4,096 tokens take almost three times as long?

Quick check: scaling and context windows

4 questions
1What is the rule of thumb for training compute?
2How many tokens per parameter did SmolLM2-135M train on?
3How big is SmolLM2-135M's KV cache for 8,192 tokens?
4What does "lost in the middle" describe?

Key Takeaways

Quick reference

NeedCode or formula
Read a model's settings onlyAutoConfig.from_pretrained(name)
Training compute6 * parameters * tokens
Compute-optimal tokensabout 20 * parameters
KV cache per token2 * layers * kv_heads * head_dim * bytes
Time a steptime.perf_counter() before and after

Was this tutorial helpful?

Lesson 150 of 186