AI - Learn With Examples https://learnwithexamples.org/category/ai/ Lets Learn things the Easy Way Sat, 31 Oct 2026 09:03:37 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.4 https://i0.wp.com/learnwithexamples.org/wp-content/uploads/2026/07/cropped-learnwithexamples-icon.png?fit=32%2C32&ssl=1 AI - Learn With Examples https://learnwithexamples.org/category/ai/ 32 32 228207193 What Does “70 Billion Parameters” Actually Mean? https://learnwithexamples.org/what-does-70-billion-parameters-actually-mean/ https://learnwithexamples.org/what-does-70-billion-parameters-actually-mean/#respond Sat, 31 Oct 2026 09:03:36 +0000 https://learnwithexamples.org/?p=1008 Every few weeks a new AI model is announced with a number attached: 7B, 13B, 70B, 405B. The letter B stands for billion, and the thing being counted is called…

The post What Does “70 Billion Parameters” Actually Mean? appeared first on Learn With Examples.

]]>

Every few weeks a new AI model is announced with a number attached: 7B, 13B, 70B, 405B. The letter B stands for billion, and the thing being counted is called a parameter. Companies quote it the way car makers quote horsepower, and most explanations stop at “more is better”. That leaves the real questions untouched. What is a parameter, physically? Where do seventy billion of them live? Why does that number decide whether a model fits on your laptop or needs a room of GPUs? This guide answers all of it using tiny models you can follow by hand, then scales up to the real thing with numbers I calculated and ran in code.

The one-sentence answer

A parameter is a single adjustable number inside a model, and training is the process of finding good values for all of them. When someone says a model has 70 billion parameters, they mean its behaviour is controlled by 70 billion such numbers. Nothing mystical is hidden in there. A model, once trained, is essentially a very large file of numbers plus a fixed recipe for combining them with your input.

The easiest way to feel this is to start at the opposite end, with a model so small that you can hold every parameter in your head.

The short version. Parameters are the learned numbers, often called weights, that a model multiplies and adds to turn input into output. More parameters give a model more capacity to capture patterns, but they also cost proportionally more memory and computation. The count tells you the size of a model, not directly how smart it is.

A model with exactly two parameters

Suppose you want to predict house prices from size. You collect five sales, and you decide to describe the relationship with a straight line: price equals w times size plus b. That is the entire model. The two numbers w and b are its parameters. The first controls how steeply the price rises with size, and the second is a base price when size is zero. Before training, you have no idea what they should be, so both start at zero.

Training means nudging each number in whichever direction reduces the prediction error, over and over. Here is the complete program, which I ran:

# The smallest "model" there is: price = w * size + b   (2 parameters)
sizes  = [4, 6, 8, 10, 12]            # house size in hundreds of square feet
prices = [31, 43, 55, 69, 79]         # price in lakh rupees

w, b = 0.0, 0.0                       # both parameters start as ignorance
lr = 0.01
for step in range(20000):
    gw = gb = 0.0
    for x, y in zip(sizes, prices):
        err = (w * x + b) - y
        gw += 2 * err * x / len(sizes)
        gb += 2 * err / len(sizes)
    w -= lr * gw                      # nudge each knob against its error
    b -= lr * gb

print(f"learned w = {w:.2f}, b = {b:.2f}   (2 parameters)")
print(f"prediction for a 9-hundred sq ft house: {w * 9 + b:.1f} lakh")

Output:

learned w = 6.10, b = 6.60   (2 parameters)
prediction for a 9-hundred sq ft house: 61.5 lakh

The program discovered that each extra hundred square feet adds about 6.1 lakh rupees, with a base of about 6.6 lakh. Its prediction for a 900-square-foot house was 61.5 lakh. Two numbers, learned from five examples, now carry a small piece of knowledge about the housing market. That is all a parameter ever is: a knob whose setting was found by trial and error against data.

Think of the mixing console in a recording studio. A model with two parameters is a console with two sliders. A model with 70 billion parameters is a console with 70 billion sliders, each set by an automated process that listened to the result millions of times and moved the sliders a tiny amount each time.

From one line to a neural network

A straight line can only describe straight-line relationships. To capture richer patterns, such as recognising a face or continuing a sentence, models stack many simple units called neurons into layers. Each neuron takes numbers in, multiplies each by its own weight, adds them up with a bias (a constant nudge), and passes the result through a small bending function. A weight and a bias are both parameters.

The picture below is the smallest network that can learn the classic XOR puzzle, which outputs 1 when its two inputs differ and 0 when they match. A single straight line cannot solve it, but one hidden layer can.

8 weights4 weights2 inputs4 hidden neurons1 outputplus 4 biases (hidden) and 1 bias (output): 8 + 4 + 4 + 1 = 17 parameters
Two inputs, four hidden neurons, one output. Every line is one weight; every neuron also has one bias.

Counting is mechanical. Every connection between two neurons is one weight. The first gap has 2 × 4 = 8 connections, and the second has 4 × 1 = 4. Every neuron that receives input also has one bias: 4 in the hidden layer plus 1 at the output. The total is 8 + 4 + 4 + 1 = 17 parameters. I trained exactly this network:

import numpy as np

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], float)
y = np.array([[0], [1], [1], [0]], float)          # XOR: true when the inputs differ
sig = lambda z: 1 / (1 + np.exp(-z))

def train(seed, steps=5000, lr=0.5):
    rng = np.random.default_rng(seed)               # the starting values are random
    W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros(4)  # 2 inputs -> 4 hidden
    W2, b2 = rng.normal(0, 1, (4, 1)), np.zeros(1)  # 4 hidden -> 1 output
    n = W1.size + b1.size + W2.size + b2.size
    fwd = lambda: (lambda h: (h, sig(h @ W2 + b2)))(np.tanh(X @ W1 + b1))
    loss0 = float(np.mean((fwd()[1] - y) ** 2))
    for _ in range(steps):
        h, p = fwd()
        d2 = (p - y) * p * (1 - p)
        d1 = (d2 @ W2.T) * (1 - h ** 2)
        W2 -= lr * h.T @ d2; b2 -= lr * d2.sum(0)
        W1 -= lr * X.T @ d1; b1 -= lr * d1.sum(0)
    p = fwd()[1]
    return n, loss0, float(np.mean((p - y) ** 2)), p

n, l0, l1, p = train(seed=1)
print("parameters:", n, "(8 + 4 + 4 + 1)")
print("loss before training:", round(l0, 3))
print("loss after training :", round(l1, 4))
for row, out in zip(X, p):
    print(f"  inputs {row.astype(int)} -> {out[0]:.2f}")
ok = sum(train(s)[2] < 0.01 for s in range(20))
print()
print(f"different random starting values: {ok} of 20 runs learned XOR")

Output:

parameters: 17 (8 + 4 + 4 + 1)
loss before training: 0.24
loss after training : 0.0001
  inputs [0 0] -> 0.00
  inputs [0 1] -> 0.99
  inputs [1 0] -> 0.99
  inputs [1 1] -> 0.01

different random starting values: 19 of 20 runs learned XOR

The loss, a measure of how wrong the network was, fell from 0.24 to 0.0001, and the final predictions are almost perfectly 0, 1, 1, 0. Seventeen numbers now implement the XOR rule, and nobody wrote that rule down. Training found it.

The last line of the output deserves attention. Training began from random numbers, and in 19 of 20 attempts the network learned XOR, but in one it got stuck. The starting values matter, and training is a search, not a guarantee. Large models deal with this through careful initialisation and a lot of engineering, but the underlying nature of the process is the same.

How parameter counts are worked out

A fully connected layer with n_in inputs and n_out outputs has n_in × n_out weights and n_out biases. Chain a few layers and add the counts. Consider a simple digit recogniser that looks at a 28 by 28 grid of pixels, which is 784 numbers, passes them through a layer of 128 neurons, and then through a final layer of 10, one for each digit.

def linear(n_in, n_out):
    """A fully connected layer: one weight per connection, one bias per output."""
    return n_in * n_out + n_out

# 1. A small image classifier: 784 pixels -> 128 -> 10 digits
print("digit classifier:", f"{linear(784, 128):,} + {linear(128, 10):,} = {linear(784, 128) + linear(128, 10):,}")

# 2. GPT-2 small, counted from its published shape
d, layers, vocab, ctx = 768, 12, 50257, 1024
per_layer = (4 * d * d + 4 * d)          # attention: query, key, value, output (with biases)
per_layer += (8 * d * d + 5 * d)         # feed-forward: d -> 4d -> d (with biases)
per_layer += 4 * d                       # two layer norms
total = layers * per_layer + vocab * d + ctx * d + 2 * d
print(f"GPT-2 small    : {total:,}  (about {total / 1e6:.0f} million)")

# 3. A 70B-class design (Llama 2 70B shape: grouped-query attention, gated feed-forward)
d, layers, vocab = 8192, 80, 32000
kv_dim, ffn = 8 * 128, 28672             # 8 key/value heads of size 128
attn = 2 * d * d + 2 * d * kv_dim        # query + output, plus smaller key + value
mlp = 3 * d * ffn                        # gate, up and down projections
per_layer = attn + mlp + 2 * d           # plus two norms
total = layers * per_layer + 2 * vocab * d + d
print(f"70B-class model: {total:,}  (about {total / 1e9:.1f} billion)")
print(f"  attention is {layers * attn / total:.1%} of it, feed-forward {layers * mlp / total:.1%}, "
      f"embeddings {2 * vocab * d / total:.1%}")

Output:

digit classifier: 100,480 + 1,290 = 101,770
GPT-2 small    : 124,439,808  (about 124 million)
70B-class model: 68,976,648,192  (about 69.0 billion)
  attention is 17.5% of it, feed-forward 81.7%, embeddings 0.8%

That digit recogniser has 101,770 parameters: 100,480 in the first layer and 1,290 in the second. Notice that most of the parameters sit in the first layer, simply because 784 inputs times 128 outputs is a large product. This pattern repeats at every scale: parameters hide where two big dimensions meet.

Counting a real language model

The same program continues with two real architectures. Modern language models are built from transformers, whose layers each contain two main blocks: an attention block, which lets each word look at the other words, and a feed-forward block, which processes each word on its own. Both are made of big grids of numbers called weight matrices.

For GPT-2 small, a model released in 2019, the published shape is 12 layers, a width of 768, and a vocabulary of 50,257 tokens. Putting those through the counting rules gives 124,439,808 parameters, which matches the 124 million that the model is known by. So the counting really works; there is no hidden accounting.

Then I did the same for a 70-billion-class design, using the architecture numbers Meta published for Llama 2 70B: 80 layers, a width of 8,192, a feed-forward size of 28,672, grouped attention with 8 key-value heads, and a vocabulary of 32,000. The total came out at 68,976,648,192. That is about 69.0 billion, which is what gets rounded and sold as “70B”. Model names are marketing-friendly roundings, so a model called 70B might have 68 or 71 billion in reality.

Where 69 billion parameters live in a 70B-class designAttention17.5%Feed-forward blocks81.7%Embeddings 0.8%
Where a 70B-class model keeps its parameters: nearly all in the repeated layers, and most of those in the feed-forward blocks.

The breakdown is instructive. About 17.5 percent of the parameters are in the attention blocks, 81.7 percent in the feed-forward blocks, and under one percent in the table that converts words to numbers. If you picture a language model as a giant recall system, the feed-forward blocks are where most of its capacity sits.

What a parameter is not

People pick up some wrong pictures, so let me clear them out.

  • It is not a stored fact. No single parameter holds “Paris is the capital of France”. Knowledge is spread across enormous numbers of parameters working together, the way a photograph is spread across millions of pixels. Change one pixel and the picture survives; change one parameter and the model barely notices.
  • It is not a neuron. Neurons are the units; parameters are the weights and biases that connect and adjust them. The 17-parameter network had only 5 neurons.
  • It is not lines of code. The code that runs a 70B model is short, a few hundred lines. The size is in the numbers, not the instructions.
  • It is not a direct measure of intelligence. A newer, well-trained 8B model can beat an older, poorly trained 30B one, because quality depends on the data, the training recipe and the design, not just the count.
  • It is not the same as the brain’s connections. You will sometimes see comparisons with the number of synapses in a brain. The two are built and behave very differently, so such comparisons are loose at best.

Why the count decides what hardware you need

Here is the practical consequence, and the reason the number is on every announcement. Each parameter is a number that must be stored, and every one of them is used each time the model produces a word. So size translates directly into memory and computation.

Memory: bytes per parameter

The memory needed to simply hold the model is the parameter count times the bytes used for each parameter. Numbers can be stored with different precision: 32-bit floats take 4 bytes, 16-bit take 2, 8-bit take 1 and 4-bit take half a byte. I worked this out for 70 billion parameters:

import math

params = 70e9
print(f"Storing {params / 1e9:.0f} billion parameters")
for name, nbytes in (("32-bit float", 4), ("16-bit (fp16/bf16)", 2), ("8-bit integer", 1), ("4-bit integer", 0.5)):
    gb = params * nbytes / 1e9
    print(f"  {name:<20}{gb:>6.0f} GB   80 GB cards for the weights alone: {math.ceil(gb / 80)}")

print()
print("Training with Adam in mixed precision, a common recipe (bytes per parameter):")
parts = [("16-bit weights", 2), ("16-bit gradients", 2), ("32-bit master weights", 4),
         ("Adam momentum", 4), ("Adam variance", 4)]
for n, b in parts:
    print(f"  {n:<24}{b}")
total = sum(b for _, b in parts)
print(f"  {'total':<24}{total}   ->  {params * total / 1e12:.2f} TB before any activations")

Output:

Storing 70 billion parameters
  32-bit float           280 GB   80 GB cards for the weights alone: 4
  16-bit (fp16/bf16)     140 GB   80 GB cards for the weights alone: 2
  8-bit integer           70 GB   80 GB cards for the weights alone: 1
  4-bit integer           35 GB   80 GB cards for the weights alone: 1

Training with Adam in mixed precision, a common recipe (bytes per parameter):
  16-bit weights          2
  16-bit gradients        2
  32-bit master weights   4
  Adam momentum           4
  Adam variance           4
  total                   16   ->  1.12 TB before any activations
Memory for 70 billion parameters (gigabytes)one 80 GB GPU32-bit280 GB16-bit140 GB8-bit70 GB4-bit35 GB
Memory needed just to hold 70 billion parameters at different precisions, against a single 80 GB GPU.

At 16-bit precision, the common format, the weights alone weigh 140 gigabytes. No single 80 GB graphics card can hold that, so you need at least two. Shrink each parameter to 8 bits and it just about squeezes onto one card; shrink to 4 bits and it takes about 35 gigabytes. That shrinking is called quantisation, and it is the reason that large models can run on much more modest hardware. The trade-off is a small loss in accuracy, which is usually acceptable at 8 bits and noticeable more often at lower precision.

Notice the caveat in the output: those figures are for the weights alone. Running the model also needs working memory for the conversation, which grows with the length of the text, so real deployments need headroom.

Training is far hungrier. A common recipe stores, for every parameter, a 16-bit copy, a 16-bit gradient, a 32-bit master copy and two 32-bit running statistics for the optimiser. That is 16 bytes per parameter, which for 70 billion comes to about 1.12 terabytes, before counting the temporary values computed during the forward pass. This is why training happens across racks of GPUs, while running a finished model can sometimes be done on one.

Computation: operations per word

The second cost is arithmetic. A widely used rule of thumb says that generating one token needs about two operations per parameter, and training needs about six operations per parameter per token of training data. Here is what that gives:

params, tokens = 70e9, 2e12                 # 70 billion parameters, 2 trillion training tokens
train_flops = 6 * params * tokens           # rule of thumb: about 6 operations per parameter per token
per_token = 2 * params                      # generating one token: about 2 operations per parameter
print(f"training work : {train_flops:.2e} operations")
print(f"one new token : {per_token / 1e9:.0f} billion operations")

peak, utilisation = 312e12, 0.40            # an A100-class GPU peak in 16-bit, and a realistic share of it
hours = train_flops / (peak * utilisation) / 3600
print(f"on one GPU at {utilisation:.0%} of {peak / 1e12:.0f} TFLOP/s: {hours / 1e6:.2f} million GPU-hours")
print(f"spread over 2,000 GPUs: about {hours / 2000 / 24:.0f} days")
print()
print(f"tokens per parameter in this recipe: {tokens / params:.0f}")

Output:

training work : 8.40e+23 operations
one new token : 140 billion operations
on one GPU at 40% of 312 TFLOP/s: 1.87 million GPU-hours
spread over 2,000 GPUs: about 39 days

tokens per parameter in this recipe: 29

Generating a single token with a 70B model takes roughly 140 billion arithmetic operations. Training on 2 trillion tokens needs around 8.4 times ten to the 23rd operations. On one A100-class GPU, using realistic assumptions of 40 percent of its peak speed, that is about 1.9 million GPU-hours, or roughly 39 days if you spread it over 2,000 GPUs. For comparison, Meta reported a figure in the same ballpark, about 1.7 million GPU-hours, for training the 70B model, so the rule of thumb lands close to reality. It is also why training a model is a headline-grabbing investment, while using it is comparatively cheap.

One last number in the output is worth pausing on: tokens per parameter. A 2022 study from DeepMind suggested that, for a fixed compute budget, models were being made too big and fed too little text, and recommended roughly 20 training tokens per parameter as a good balance. Their 70B-parameter model trained on 1.4 trillion tokens beat much larger models that had seen less text. The lesson is that parameter count is only half of the story. The other half is how much data the parameters were tuned against.

Size words you will meet

TermWhat it meansWhy it matters
7B, 13B, 70BBillions of parametersRough size class of the model
fp16 / bf1616-bit numbers, 2 bytes eachStandard format for running models
8-bit, 4-bit, Q4Quantised: fewer bytes per parameterSmaller files, small accuracy loss
Total vs active parametersMixture-of-experts models use only part of themselves per wordMemory follows total, speed follows active
Context lengthHow much text the model reads at onceNot the same thing as parameter count
TokensWord pieces; training data is counted in themThe other half of model quality

The mixture-of-experts row catches many people out. In such a model, the layers contain several specialist blocks and a small router chooses a few of them for each word. The full set of experts must sit in memory, so the memory bill follows the total parameter count, but only the chosen experts do any arithmetic, so the speed follows the active count. A model can therefore be large to store but quick to run.

Model sizes in real life

Different jobs call for very different sizes. Click through five everyday situations and notice that bigger is not always the right answer.

Spam filter

Your email app decides whether each message is spam. How big does that model need to be?

SizeThousands to millions
TaskSpam or not
MemoryA few megabytes
FitsSmall model

What size fits. A spam filter makes one narrow yes-or-no decision, and a model with a modest number of parameters can do it well. Using a 70B model here would be like hiring a professor to sort the post. The tiny size also means it answers instantly and costs almost nothing to run.

Wake word

A phone listens all day for a phrase such as “hey assistant” and wakes up only when it hears it.

SizeTypically very small
TaskHear one phrase
RunsAlways on
Why smallBattery life

What size fits. This listener runs constantly, so it must sip power. Such detectors are typically tiny models that do one thing, and only after they fire does a bigger model wake up. It is a good reminder that parameter count is a budget: spend it where the job needs it.

Phone assistant

You want a chat assistant that works offline on a phone or laptop. What size is realistic?

Size1B to 8B
At 4-bit, 8BAbout 4 GB
RunsOn the device
Trade-offLess depth

What size fits. Memory is parameters times bytes. An 8-billion-parameter model at 4 bits per parameter needs about 4 GB (8 billion × 0.5 bytes), which a modern phone or laptop can hold. You trade some depth and accuracy for privacy, speed and offline use.

Cloud chatbot

A company runs a large assistant for millions of users. Why is it hosted in a data centre?

Size70B and up
At 16-bit, 70B140 GB
NeedsSeveral GPUs
RunsIn a data centre

What size fits. At 16-bit precision, 70 billion parameters need 140 GB just for the weights, more than a single 80 GB GPU holds, and generating each word costs about 140 billion operations. Sharing that hardware across many users is what makes the economics work.

Mixture of experts

Imagine a model advertised as 100 billion parameters in total, but only 20 billion of them are used for any one word. What does that mean for cost?

TotalSay 100B (illustrative)
ActiveSay 20B (illustrative)
Memory followsTotal
Speed followsActive

What size fits. All 100 billion must sit in memory, because any expert might be chosen, so the storage bill follows the total. But a router sends each word to only a few experts, so the arithmetic, and the speed, follows the 20 billion active. These numbers are an illustration of the idea, not a specific product.

How to choose a size

When people ask me which model size they need, I do not start from the parameter count. I start from the job and the hardware. A short sequence of questions settles most cases.

1. Is it a simple, narrow task(spam, yes/no, tagging)?yesSmall modelthousands to millionsno2. Must it run offline on aphone or laptop?yes1B to 8B, quantisedabout 1 to 5 GBno3. Does it need strong reasoningor broad knowledge?yes70B and upuse an API or several GPUsno4. Do you have your own dataand one clear goal?yesFine-tune a smaller modelcheaper than going bignoStill unsure? Start small, test on your task, then scale up
Start from the task and the hardware. Bigger models are a cost you should only pay for a reason.

Common mistakes and misconceptions

  • Assuming more parameters always means a better model. Data quality, training length and design matter as much. Compare actual results on your task.
  • Confusing parameters with training data. Parameters are the learned numbers; training data is the text the numbers were tuned on. Both are measured in billions, in different units.
  • Forgetting the precision. “70B” says nothing about file size until you know the bytes per parameter. The same model is 140 GB at 16-bit and 35 GB at 4-bit.
  • Ignoring working memory. Weights are the minimum. Long conversations need extra room on top.
  • Treating the headline number as exact. Names are rounded; the real count of my 70B-class calculation was 69.0 billion.
  • Mixing up total and active parameters. A mixture-of-experts model can quote a big total but compute with a fraction.
  • Expecting one parameter to hold one fact. Knowledge is distributed across many parameters at once.
  • Using a giant model for a tiny task. A spam filter does not need 70 billion parameters, and paying for them wastes money and energy.

A mental model that sticks

Picture an orchestra of seventy billion musicians, each holding a single instrument that can play only one note at a time, loud or soft. No individual musician plays a melody, and none of them knows the song. Yet when each one adjusts their volume to exactly the right amount, the combined sound becomes music. Training is the long rehearsal in which a conductor, listening to the result, tells every musician to turn up or down by a hair, repeated trillions of times. The “70 billion” is the head count of the orchestra, and the size of the concert hall you need follows directly from it.

Practice problems with answers

Try each one on paper before you tap to check.

1. How many parameters does a layer with 100 inputs and 50 outputs have?

5,050. That is 100 × 50 = 5,000 weights plus 50 biases.

2. How many parameters are in a network with layers of 784, 128 and 10 neurons?

101,770. The first layer has 100,480 and the second has 1,290.

3. How much memory do the weights of a 7-billion-parameter model need at 16-bit and at 4-bit?

14 GB at 16-bit (7 billion × 2 bytes) and 3.5 GB at 4-bit (7 billion × 0.5 bytes).

4. A 13B model is stored at 8 bits per parameter. About how large is the file?

About 13 GB, because 8 bits is one byte per parameter.

5. About how many arithmetic operations does a 70B model need to generate one token?

About 140 billion, using the rule of thumb of two operations per parameter.

6. Using the line model w = 6.10, b = 6.60, what price does it predict for a size of 9?

61.5 lakh, since 6.10 × 9 + 6.60 = 61.5.

7. Why can a smaller model beat a bigger one?

Quality also depends on the training data, how long it was trained and the design. A well-trained 8B model can beat an older, poorly trained 30B model.

Test yourself: five quick questions

Tap a question to reveal the answer. The correct option is marked.

What is a parameter in a neural network?
  1. A line of code
  2. A word in the training data
  3. A learned number such as a weight or bias
  4. A neuron

Parameters are the adjustable numbers that training sets. Neurons are the units they connect.

How many parameters does a network with layers 2, 4 and 1 have?
  1. 17
  2. 13
  3. 8
  4. 21

Weights: 2×4 + 4×1 = 12. Biases: 4 + 1 = 5. Total 17.

How much memory do 70 billion parameters need at 16 bits each?
  1. 35 GB
  2. 70 GB
  3. 280 GB
  4. 140 GB

16 bits is 2 bytes, and 70 billion × 2 bytes is 140 GB.

What does quantisation do?
  1. Adds more parameters
  2. Stores each parameter with fewer bits
  3. Trains the model longer
  4. Removes the vocabulary

Fewer bits per parameter shrinks the file, usually at a small cost in accuracy.

In a mixture-of-experts model, what does speed follow?
  1. The total parameters
  2. The context length
  3. The active parameters
  4. The vocabulary size

Only the chosen experts compute for each word, while memory must hold them all.

Frequently asked questions

What is a parameter in AI?

A parameter is a single learned number inside a model, usually a weight or a bias. Training adjusts all of them so the model’s output matches the training data as closely as possible.

Does a model with more parameters always perform better?

No. Training data, training length and design matter as much. Larger models have more capacity, but a smaller well-trained model can beat a bigger poorly trained one.

How much memory does a model need?

Roughly the parameter count times the bytes per parameter: 2 bytes at 16-bit, 1 at 8-bit and 0.5 at 4-bit. Add headroom for the working memory that grows with the length of the conversation.

Is 70B the exact number of parameters?

Usually it is a rounding. My calculation for a 70B-class design gave 68,976,648,192, about 69.0 billion.

What is the difference between parameters and tokens?

Parameters are the learned numbers in the model. Tokens are the pieces of text the model reads, and training data is counted in them. A model with 70 billion parameters might be trained on trillions of tokens.

Can I run a 70B model on my own computer?

Only with heavy shrinking. At 4 bits the weights are about 35 GB, which needs a computer with a lot of memory. Smaller models of 7B or 8B are far more practical on ordinary hardware.

Key takeaways

  • A parameter is one learned number, a weight or a bias. The line model had 2, the XOR network 17, the digit recogniser 101,770, GPT-2 small about 124 million and a 70B-class design about 69 billion.
  • Parameters sit where big dimensions meet. In my 70B-class count, 81.7 percent were in the feed-forward blocks and 17.5 percent in attention.
  • Memory is parameters times bytes per parameter: 140 GB at 16-bit, 70 GB at 8-bit and 35 GB at 4-bit for 70 billion parameters.
  • Generating one word takes about 2 operations per parameter, 140 billion for a 70B model. Training takes about 6 per parameter per training token, around 1.9 million GPU-hours by my estimate.
  • Parameter count measures size, not intelligence. Training data and design matter as much, and a larger model is not automatically the right choice.
  • Names are roundings, and for mixture-of-experts models the total and the active counts differ.
model parameters70 billion parameterslarge language modelsneural network weightsLLM model sizequantizationAI for beginners

The post What Does “70 Billion Parameters” Actually Mean? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-does-70-billion-parameters-actually-mean/feed/ 0 1008
What Are Tokens and Context Windows? https://learnwithexamples.org/what-are-tokens-and-context-windows/ https://learnwithexamples.org/what-are-tokens-and-context-windows/#respond Tue, 04 Aug 2026 09:21:42 +0000 https://learnwithexamples.org/?p=814 LearnWithExamples A language model never actually sees your sentence. It sees a stream of numbered fragments, and it can only hold so many of them at once. Understand those two…

The post What Are Tokens and Context Windows? appeared first on Learn With Examples.

]]>

LearnWithExamples

A language model never actually sees your sentence. It sees a stream of numbered fragments, and it can only hold so many of them at once. Understand those two facts and almost every strange AI behaviour you have ever run into suddenly has an explanation.

I have been building things on top of language models since the days when “context window” meant 512 fragments and you budgeted them like a family budgets grocery money. The hardware got better. The models got enormous. And yet, in workshop after workshop, the same two questions come up first — and they are almost always asked in the wrong order.

People ask “why did the AI forget what I told it?” before they ask “what exactly is the AI storing in the first place?” That is like asking why your suitcase won’t close before checking what you packed. So let’s do it properly. First we’ll open up a token — see it, split it, count it. Then we’ll build the window it lives inside, and watch what happens when the window fills up.

By the end you’ll be able to look at a prompt and estimate its cost in your head, explain why the model insists “strawberry” has two Rs, know why Hindi or Tamil text costs nearly triple what English does, and — most usefully — know exactly what to trim when a system tells you your input is too long.

The 30-second answer

Tokens and context windows, defined

A token is the smallest chunk of text a language model actually reads. Usually it’s a piece of a word — roughly ¾ of an English word on average. The model converts every token into a number before it does anything else. Text in, numbers out.

A context window is the maximum number of tokens the model can have in front of it at one time — your instructions, the uploaded file, the entire chat history, plus the reply it is currently writing. It’s a hard ceiling, not a soft suggestion. Nothing outside it exists as far as the model is concerned.

Tokens are the units. The context window is the container. Everything else in this article is a consequence of those two sentences.

Part 1 — A token is not a word

Here is the first mental model most beginners build, and it is wrong: “the AI reads word by word, like I do.” Reasonable guess. Also the source of about half the confusion I see.

Think about why splitting on words fails. English alone has well over a million distinct word forms once you include names, typos, plurals, brand names, hashtags, and the thing your colleague types when they mean “definitely.” A model would need a lookup table with a million-plus entries, and the moment somebody typed Kanniyakumari or ngrok or bruhhhh, the table would shrug and return “unknown.”

Now try the opposite extreme: split on characters. Only about a hundred symbols to memorise — clean, complete, nothing is ever unknown. But now the word “encyclopedia” costs twelve slots instead of one, and the model has to learn spelling from scratch before it learns meaning. Sequences get impossibly long, and long sequences are expensive (we’ll get to why).

So the field landed in the middle. Subword tokenization: keep whole tokens for the text fragments that show up constantly, and break rare things into smaller pieces that can be reassembled. Common stuff is cheap. Weird stuff still works, just costs more.

Split by words

Tiny sequences, impossible vocabulary. Any unseen word breaks it. Rejected.

Split by characters

Tiny vocabulary, endless sequences. Nothing breaks, but everything is slow. Rejected.

Split by subwords

Frequent chunks stay whole, rare chunks get split. This is what every major model uses today.

Watch it happen

Reading about tokenization is far less convincing than watching a sentence get shredded. Type into the box below — or hit one of the preset buttons — and see the fragments appear. Each coloured block is one token. Notice the little spaces sitting inside the blocks: in most tokenizers a leading space is part of the token, which is why the and the are two different entries entirely.

Live token splitter

estimate · type to update
0Tokens
0Words
0Characters
0Tokens / word

Grey <byte> blocks are the extra tokens spent on characters outside the basic Latin set. This tool approximates real byte-pair encoding closely enough to build intuition — exact counts vary a little between model families.

How the splitting rules get invented

Nobody sits down and hand-writes the list of fragments. It’s learned from data, most often with an algorithm called Byte Pair Encoding (BPE). The idea is almost embarrassingly simple, and you can run it on paper.

Suppose your entire training corpus is these three words, repeated a lot:

RoundWhat the algorithm seesMost frequent adjacent pairNew merged token
Startl o w · l o w e r · l o w e s tl + olo
2lo w · lo w e r · lo w e s tlo + wlow
3low · low e r · low e s te + rer
4low · low er · low e s te + ses
5low · low er · low es tes + test

Five rounds and the algorithm has independently discovered the root low and the suffixes er and est — real English morphology, learned purely by counting. Run this for millions of rounds on a slice of the internet and you get a vocabulary of roughly 50,000 to 200,000 fragments, ordered by how useful they are.

Two consequences fall straight out of this, and both matter in practice:

  • Frequency decides price. Text that looked like the training data gets packed efficiently. Text that didn’t gets shredded into crumbs. Your name is probably one token if you’re called David and five tokens if you’re called Devanshi.
  • The vocabulary is frozen at training time. A model trained mostly on English carries an English-shaped tokenizer forever. It can still read Hindi, Swahili, or Korean — it just pays a heavier toll per sentence.
Example you can feel

Type “Learning is fun” into the splitter above, then type the same sentence in Hindi. English: about 3–4 tokens. Hindi: often 15–25. Same meaning, four to six times the cost. If you build a product for an Indian audience and price it per token, this single detail can decide whether your unit economics work.

Part 2 — Token maths you can do in your head

You will rarely need an exact count. You will constantly need a fast estimate: will this fit? These are the ratios I have used for years, and they hold up well enough for planning.

Rule of thumbApproximate valueHow to use it
English words → tokens1 word ≈ 1.3 tokensMultiply your word count by 4/3.
Characters → tokens4 characters ≈ 1 tokenFastest check: divide character count by 4.
A typical page of prose≈ 600 tokens450 words per double-spaced page.
Source code1 line ≈ 8–12 tokensIndentation and punctuation are surprisingly costly.
Meeting transcript1 minute ≈ 200 tokensSpeech runs near 150 words per minute.
Non-Latin scripts2–4× the English costDevanagari, Tamil, Thai, Arabic, Korean.
Emoji1 emoji ≈ 2–4 tokensSkin-tone and family emoji are the worst offenders.

Let’s apply them to things you actually handle:

A WhatsApp message

~25 words → ≈ 33 tokens. You could send 6,000 of these before filling a 200K window.

A one-page résumé

~600 words → ≈ 800 tokens. Screening 100 résumés at once is genuinely feasible.

A 12-page contract

~6,000 words → ≈ 8,000 tokens. Comfortable in any modern window.

A 90-minute meeting

~13,500 words → ≈ 18,000 tokens. Fine alone; painful if you also attach the slides.

A 300-page novel

~100,000 words → ≈ 133,000 tokens. Fits in a large window, with room to spare for questions.

A mid-size codebase

40,000 lines → ≈ 400,000 tokens. This is where retrieval stops being optional.

Part 3 — The five places tokenization gets weird

This is the part of the article I’d tell my past self to read first. Almost every “the AI is stupid” complaint I have investigated turned out to be a tokenizer artefact, not a reasoning failure.

1. The model cannot reliably count letters

Ask a model how many times the letter R appears in “strawberry” and you may get “two.” People post screenshots of this as proof that AI is a parlour trick. What actually happened is subtler: the model never received the letters. It received something like str + aw + berry — three opaque ID numbers. Asking it to count Rs is like asking you to count the letters in a word someone spelled out in Morse code, at speed, without writing anything down. Not impossible, but a genuinely awkward task given the input.

Fix it in practice

Force the letters apart before asking: s-t-r-a-w-b-e-r-r-y. Hyphenating breaks the word into single-character tokens and accuracy jumps immediately. Same trick works for reversing words, counting syllables, and checking palindromes.

2. Numbers split in unhelpful places

Depending on the tokenizer, 148392 might become 148+392, or 1+48+39+2. The digits do not line up in neat place-value columns the way they do on paper, which is a large part of why models were historically shaky at long arithmetic. It also means an invoice number, a PAN, an order ID, or a phone number can be far more expensive than its length suggests — and is easier to mis-copy.

3. A trailing space quietly poisons your prompt

If your prompt ends with "The answer is " — with a space after “is” — you have handed the model a dangling space token and asked it to continue. But the natural next token is " 42", which already includes its own leading space. You’ve created a conflict the model must work around, and quality drops for no visible reason. Fifteen years in, and I still occasionally lose twenty minutes to a stray space at the end of a template string.

4. Whitespace is a real line item in code

Deeply indented code, four-space tabs, blank lines between functions — every bit of that costs tokens. A well-formatted 500-line Python file can cost noticeably more than the same logic minified. This is not an argument for writing ugly code; it is an argument for sending the model the three functions that matter instead of the whole file.

5. Rare and mixed-script text costs a fortune

Scientific nomenclature, chemical formulas, Sanskrit terms, transliterated place names, base64 blobs, UUIDs, and minified JavaScript all tokenize horribly. A single UUID can eat 20+ tokens. If you are pasting logs full of them, you are burning most of your budget on strings the model does not need to read carefully.

Every unusual character you send is a small tax. Every ordinary English word is a discount. That asymmetry is baked into the tokenizer, and no amount of prompt engineering removes it.

Part 4 — The context window: the desk, not the brain

Now the second half. You know what tokens are; the question is how many the model can look at simultaneously.

My favourite analogy comes from a colleague who used to work in an architecture office. Picture a draughtsman at a drawing board. The board is a fixed size. Everything he needs — the client brief, the site survey, last week’s revisions, the sheet he is drawing on right now — has to be laid out on that board at once. Anything that doesn’t fit goes on the floor. And here is the crucial part: he cannot remember what’s on the floor. Not “remembers it vaguely.” Cannot see it at all.

That board is the context window. It is measured in tokens, and it holds four things simultaneously:

ONE CONTEXT WINDOW — 100% OF WHAT THE MODEL CAN SEE Systempromptrules, persona Attached files & retrieved docsPDFs, database rows, search results,tool outputs, images-as-tokens Conversation historyevery earlier message from both sides,resent in full on every single turn Reserved forthe replyoutput tokens ANYTHING THAT DOESN’T FIT Dropped, truncated, or summarised away The model has no awareness that this content ever existed. It cannot ask for it back.
The four tenants of every context window. They compete for the same fixed space — grow one and you shrink the others.

Read that diagram twice, because it contains the single most misunderstood fact about chatbots: the conversation history is re-sent, in full, on every turn. The model is not sitting there remembering you between messages. It is stateless. Each time you press enter, the application quietly bundles up the entire transcript so far, appends your new message, and ships the whole parcel off again. That is why turn 40 of a conversation costs far more than turn 2, and why a long chat gradually slows down.

Watch a conversation fall off the edge

The simulator below runs a customer-support chat. Drag the slider to shrink or grow the window and watch which messages survive. The system prompt is pinned — it is always sent — and the newest messages have priority. Everything greyed out is on the floor.

Context window simulator

drag the slider
system prompt history in window free space 0 messages dropped

Shrink the window far enough and the model loses the customer’s order number — then confidently asks for it again, or worse, invents one. That “sudden amnesia” moment is not a bug in the model. It is arithmetic.

Part 5 — Who is eating your window?

When a team tells me “we have a 128,000 token window, we’ll never hit it,” I ask them to write down the budget. It is always tighter than they expect. Here’s a real-shaped example — an internal HR assistant:

Line itemTokensNotes
System prompt (tone, rules, escalation policy)1,400Sent on every single turn, forever.
Tool / function definitions2,100Six tools with parameter schemas.
Few-shot examples1,800Four demonstration Q&A pairs.
Retrieved policy documents (8 chunks)6,400The RAG payload.
Employee’s uploaded payslip PDF3,200Tables tokenize badly.
Conversation history (turn 18)9,700Grows every turn, never shrinks by itself.
Reserved for the reply2,000If you forget this, generation gets cut off mid-sentence.
Total26,600And this is a simple assistant.

Notice what dominates: not the user’s question, which is maybe 30 tokens. The scaffolding dominates. That is the normal state of affairs, and it’s why the highest-leverage optimisation is almost never “write a shorter question.”

The reservation nobody makes

Input and output share the same window. If you fill 199,000 of a 200,000-token window with a document and then ask for a detailed 5-page report, there is no room left to write it in. The response gets truncated mid-sentence and everyone blames the model. Always leave headroom for the answer — I budget 10–15% by default.

Input tokens and output tokens are not the same product

Every provider charges more per output token than per input token, often 3–5×, and beginners assume this is arbitrary. It isn’t. Reading your input happens in one parallel pass — the whole prompt goes through the model at once. Writing the reply happens one token at a time, sequentially, with a full pass through the network for each token produced. Output is genuinely the expensive half.

The practical takeaway: a request that reads 50,000 tokens and returns a 200-token summary is cheap. A request that reads 500 tokens and generates a 4,000-word essay may cost more. If your bill is climbing, look at what you are asking the model to write, not just what you are feeding it.

What actually fits in a window?

pick a size
0English words
0Pages of prose
0Lines of code
0Minutes of transcript
0Business emails
0Hindi words

Part 6 — Why bigger windows didn’t solve everything

Around the time million-token windows arrived, a lot of people declared retrieval dead. Just dump everything in! It did not play out that way, for four reasons I now explain in every architecture review.

Attention cost grows faster than the input

In a standard transformer, every token compares itself with every other token. Double the input and you roughly quadruple that work. Modern implementations soften the curve considerably, but the shape of the problem remains: long contexts are disproportionately expensive in compute and in memory. That cost lands on you as latency and as money.

Information gets lost in the middle

Researchers have repeatedly measured a U-shaped accuracy curve: models are excellent at recalling material near the beginning of the context and near the end, and noticeably weaker on material buried in the middle. Put the critical clause on page 40 of a 90-page contract and recall genuinely suffers. It is the reading equivalent of remembering the first and last speaker at a conference and losing the eleven in between.

Two habits that follow from this

First: put your instructions after the long document, not before it — the tail position is a strong one. Second: for anything critical, state it twice, once at the top and once at the bottom. It feels redundant. It measurably works.

More context means more distraction

Give a model 50 pages when the answer lives in one paragraph, and you have added 49 pages of plausible-looking, semantically similar noise. Precision drops. I have watched a support bot’s accuracy improve by 12 points simply by retrieving four document chunks instead of twenty. Less, but better, beat more.

You pay for every token, every turn

A 300,000-token prompt sent on each of 20 conversational turns is six million input tokens for a single conversation. Multiply by a thousand users. This is the bill that surprises startups in month three.

A large context window is a bigger desk, not a better draughtsman. What you place on the desk still decides the quality of the drawing.

Part 7 — What happens when you overflow

Four different things, and knowing which one your tool does explains a lot of otherwise baffling behaviour.

Hard rejection

The API refuses the request outright with a “maximum context length exceeded” error. Honest and annoying — typical of direct API calls.

Silent truncation

The oldest content is chopped off without telling anyone. The model answers confidently using half the information. This is the dangerous one.

Sliding window

Old turns drop off the back as new ones arrive, like a conveyor belt. Chat apps often do this. It’s why long chats “forget” the beginning.

Rolling summarisation

Older turns get compressed into a paragraph of notes that stays in context. Cheapest in tokens, but detail is permanently lost.

Here’s the failure I see most often in production, told as a small story. A logistics company built an assistant that read a shipment manifest and answered questions about it. It worked beautifully in testing. In production it started confidently reporting wrong container weights. The cause: their largest customers had manifests that pushed past the window, their framework silently truncated the head of the file — including the column headers — and the model, doing its best with headerless numbers, guessed which column was which. No error was ever logged. Nobody had built a token counter into the pipeline.

Count your tokens before you send them. That is the whole lesson. It takes four lines of code and it prevents an entire genus of bug.

Part 8 — The practical playbook

Nine tactics, roughly in the order I reach for them.

TacticWhat you actually doBest when
Chunk and retrieveSplit documents into 300–800 token passages, embed them, and pull only the handful that match the question.Your corpus is bigger than any window — knowledge bases, manuals, archives.
Summarise and carryEvery ~10 turns, compress the conversation into a short state note and drop the raw transcript.Long-running assistants and agents.
Sandwich your instructionsState the task before the document and repeat it after.Any prompt over ~10,000 tokens.
Reserve output spaceCap input at 85% of the window; leave the rest for the reply.Always. Non-negotiable.
Strip the noiseRemove HTML tags, boilerplate footers, base64 blobs, repeated log timestamps, license headers.Scraped web content and log files — often a 40% saving.
Keep the stable parts firstPut the system prompt and fixed examples at the very start, variable content after.You’re using prompt caching — cache hits need an identical prefix.
Ask for structureRequest JSON or a bounded list instead of free prose.Output tokens are your cost driver.
Split the jobThree focused calls beat one giant call that tries to do everything.Multi-step analysis; also improves accuracy.
Right-size the modelRoute simple classification to a small model, reserve the big window for the hard step.Cost is out of control and latency matters.

A worked example: 200 support tickets

Say you want themes across 200 support tickets averaging 400 words each. Naive approach: paste all of them, about 107,000 tokens, into one prompt and ask for themes. It fits in a large window — and produces a bland, shallow answer, because the middle 150 tickets get skimmed.

What actually works: batch the tickets in groups of 20. For each batch, ask for a compact structured summary — five themes, each with a one-line description and a count. That’s ten calls of ~11,000 input tokens each, returning ~300 tokens apiece. Then a final call takes those ten summaries (3,000 tokens total) and merges them into the master list. Total input is similar, output is small, and every ticket got real attention rather than a glance. This map-then-reduce shape is the workhorse pattern of practical LLM engineering, and it exists entirely because of context limits.

Part 9 — Five myths worth deleting

“The model remembers our previous conversations.”

By default, no. Each request is stateless. If a product appears to remember you across sessions, an application layer is storing notes in a database and quietly pasting the relevant ones into the context window before the model ever sees your message. The memory lives in the product, not in the model.

“A bigger context window means the AI is smarter.”

Window size measures capacity, not capability. A model with a million-token window can still reason worse than a model with 32,000. They’re independent specifications — like confusing the size of a desk with the skill of the person sitting at it.

“One token is one word.”

Only by coincidence, and mostly for short common English words. Average English runs about 1.3 tokens per word; a rare surname might be five tokens; a Devanagari sentence can be three or four times its English equivalent. The splitter above makes this obvious in ten seconds.

“Images and files don’t use tokens.”

They absolutely do. Images are converted into token-equivalents based on their dimensions — a high-resolution screenshot can cost well over a thousand. PDFs are extracted to text and tokenized like anything else, and tables and scanned pages are especially expensive. Audio and video are worse still.

“If it fits in the window, the model reads it all equally.”

Fitting is necessary, not sufficient. Attention is uneven — beginnings and endings dominate. Fitting a document into context guarantees the model can see it, never that it will weigh every paragraph the same.

Quick reference

TermIn one line
TokenThe smallest unit of text a model reads; usually a word fragment.
TokenizerThe component that converts text into token IDs and back again.
VocabularyThe fixed list of all tokens a model knows — typically 50K–200K entries.
BPEByte Pair Encoding — the merge-the-most-frequent-pair algorithm that builds that list.
Context windowMaximum tokens the model can hold at once, input and output combined.
Input tokensEverything you send: prompt, history, files, tool definitions.
Output tokensEverything the model writes back. More expensive, generated one at a time.
TruncationCutting content that doesn’t fit — sometimes silently.
RAGRetrieval-augmented generation: fetch only the relevant passages, then answer.
Prompt cachingReusing the processed form of an unchanged prompt prefix to cut cost and latency.
KV cacheStored intermediate values for tokens already processed; grows with context length.
Lost in the middleThe measured tendency to recall the start and end of a long context better than the middle.

Check yourself

Five questions. No score is recorded anywhere — this is just for you.

Frequently asked questions

How many tokens is 1,000 words?

About 1,300 tokens for ordinary English prose. Technical writing with lots of code, names, or numbers runs higher — budget 1,500. Hindi, Tamil, Arabic or Korean text of the same length can reach 3,000–5,000.

How do I count tokens exactly?

Use the tokenizer library published for your specific model family — the count is model-specific, so a number from one vendor’s tool won’t match another’s precisely. For planning, the four-characters-per-token estimate is close enough; for billing and hard limits, count properly in code before you send.

Does a longer chat cost more even if my messages are short?

Yes, and this surprises almost everyone. The full history is re-sent every turn, so input cost grows roughly with the square of conversation length. Starting a fresh chat for a new topic is not just tidier — it is cheaper and usually produces better answers.

What’s the difference between context window and training data?

Training data is what shaped the model’s weights months ago — permanent, general, and unchangeable at chat time. The context window is working memory for right now — temporary, specific, and gone when the session ends. A model can be trained on the whole internet and still not know what’s in a document you haven’t pasted.

Can I make my text use fewer tokens?

Yes, meaningfully. Strip boilerplate and markup, drop repeated headers and footers, replace long IDs with short labels, summarise older conversation turns, send excerpts instead of whole files, and prefer plain common vocabulary over ornate phrasing. Compressing prompts by 30–50% with no loss of meaning is routine once you look for it.

Why do models struggle with counting letters and long arithmetic?

Because tokenization hides the internal structure. The model sees IDs for word fragments, not individual characters or place-value digits. Spacing the characters out (s-t-r-a-w) or asking it to use a calculator tool both fix it, and both work because they change what the tokenizer produces.

Where this leaves you

Two ideas, and everything downstream follows from them. Text becomes tokens — fragments, not words, priced by how ordinary they are. Tokens live inside a window — a hard-edged desk, not a memory, holding your instructions, your documents, your entire chat history and the answer being written, all at the same time.

Once those two things are solid, the rest of the field stops looking like magic. Retrieval is a technique for choosing what goes on the desk. Prompt caching is a technique for not re-reading the same corner of it. Summarisation buys space. Chunking buys attention. Even the odd failures — the miscounted letters, the sudden amnesia at message 40, the report that stops mid-sentence — become predictable, and therefore preventable.

Try this before you close the tab: take a prompt you use regularly, paste it into the splitter near the top of this page, and look at the number. Most people discover their standard prompt is two or three times more expensive than they assumed, and that a third of it is boilerplate the model never needed. That’s a five-minute experiment that has saved teams I’ve worked with real money — and it starts with just looking at the tokens.

tokenscontext windowtokenizationBPEprompt engineeringLLM basics

The post What Are Tokens and Context Windows? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-are-tokens-and-context-windows/feed/ 0 814