My account

Math for ML

To read a model you need only a little math: vectors, the dot product, matrices and their shapes, matrix multiply and softmax. With these you can count how much memory a model needs and how much work one token costs, which is the daily job of an inference engineer.

Not reviewedWritten with AI helpReading time: 11 minShop assistant exampleNumPy

Author: bezzad

Contents

Why an inference engineer needs this math

Our shop runs a support assistant on an open-weight 8B model. People on the team ask questions like:

  1. “Will this model fit on one GPU?”
  2. “How many tokens per second can we get?”
  3. “Why did this code crash with a shape error?”

You do not need calculus to answer them. You need to know what a vector and a matrix are, how they are multiplied, and how to count the numbers and the work. That is all this lesson teaches.

Vectors: a list of numbers

A vector is a list of numbers. In a language model, every token becomes a vector before the model can work with it.

import numpy as np

token = np.array([0.12, -0.80, 0.33, 0.05])  # a tiny vector of 4 numbers
print(token.shape)   # (4,)

In our 8B model, each token is a vector of 4,096 numbers. This size is called the hidden size. You will see it everywhere in the model’s config.

The dot product: how similar are two vectors?

The dot product multiplies two vectors number by number and adds the results.

a = np.array([1.0, 2.0, 3.0])
b = np.array([4.0, 5.0, 6.0])
print(a @ b)   # 1*4 + 2*5 + 3*6 = 32.0
  1. Same direction, big result. When two vectors point the same way, the dot product is large.
  2. Opposite, negative result. When they point opposite ways, it is negative.
  3. Unrelated, near zero.

Attention, the heart of a transformer, uses dot products to decide which earlier tokens matter for the current one. So when you hear “attention score”, think “dot product”.

Matrices and shapes

A matrix is a table of numbers with rows and columns. Its shape is written (rows, columns).

W = np.zeros((4096, 14336))   # 4,096 rows, 14,336 columns
print(W.shape)   # (4096, 14336)
print(W.size)    # 58,720,256 numbers

The weights of a model are mostly matrices like this one. In our model, this is the size of one matrix inside one layer. Counting numbers is counting memory: 58.7 million numbers × 2 bytes (BF16) is about 117 MB, just for this one matrix.

Matrix multiply: the one rule

Almost all the work in a model is matrix multiply. There is one rule to remember:

@=(m, k)(k, n)(m, n)one rowone columnone result numberThe inner sizes (k and k) must match. The result takes the outer sizes (m and n).
The inner sizes must be the same. The result takes the outer sizes.
  1. (m, k) @ (k, n) gives (m, n). The two inner sizes (k and k) must match.
  2. If they do not match, the code crashes with a shape error.
  3. Each number in the result is one dot product of a row from the left and a column from the right.
x = np.ones((8, 4096))        # 8 tokens, 4,096 numbers each
W = np.ones((4096, 14336))    # one weight matrix
y = x @ W
print(y.shape)                # (8, 14336)

Here the 8 rows can be 8 tokens of one prompt, or one token each from 8 users. The same weights serve all rows. Keep this in mind: it is the reason batching works.

Counting work: FLOPs

The work of a matrix multiply is counted in FLOPs (floating point operations).

  1. For (m, k) @ (k, n): each of the m × n results needs k multiplies and k adds, so about 2 × m × k × n FLOPs.
  2. For a whole model, one token: about 2 × parameters FLOPs. Each weight is used once: one multiply and one add.
  3. Our 8B model: about 2 × 8 billion = 16 GFLOPs per token (plus a little for attention, which grows with chat length).
params = 8e9
flops_per_token = 2 * params
print(flops_per_token / 1e9)   # 16.0 GFLOPs

This number lets you compare with what the GPU can do per second. The lesson on GPUs shows why, for one user, memory, not FLOPs, is usually the limit.

Softmax: from scores to chances

A model ends with one score for every token in its vocabulary. These scores are called logits. Softmax turns them into chances (probabilities) that are all positive and add up to 1.

Scores (logits)After softmaxsoftmax2.01.00.166%24%10%yessurenoyessurenoSame order. All positive. They add up to 100%.
Softmax keeps the order of the scores, but makes them positive and makes them add up to 1. A big score takes most of the chance.
def softmax(scores):
    e = np.exp(scores - scores.max())  # subtract the max: no overflow
    return e / e.sum()

print(softmax(np.array([2.0, 1.0, 0.1])))
# about [0.66, 0.24, 0.10]

Two things to remember:

  1. Subtract the max first. exp(1000) is infinity. Subtracting the biggest score gives the same result without overflow.
  2. Softmax is used twice in a transformer: to pick the next token, and inside attention to turn dot products into weights.

Common mistakes

Mistake Result Right way
Ignoring the shape A crash, or a wrong but quiet result after broadcasting. Print .shape at each step; check (m, k) @ (k, n).
Mixing up parameters and bytes Memory guesses off by 2 or 4 times. Bytes = parameters × bytes per number (BF16 = 2).
Counting FLOPs only Thinking one user can get thousands of tokens per second. Also count bytes read from memory.
Softmax without subtracting the max nan or inf with big scores. exp(x - max(x)).

Summary in five lines

  1. A token becomes a vector; in our model it has 4,096 numbers.
  2. The dot product tells how similar two vectors are; attention is built on it.
  3. (m, k) @ (k, n) gives (m, n); the inner sizes must match.
  4. One token costs about 2 × parameters FLOPs; memory = parameters × bytes per number.
  5. Softmax turns scores into chances that add up to 1; subtract the max first.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.