- Key idea
- The logarithm, and why models use log-probabilities
- Real world
- Sound volume in decibels. Every +10 dB is ten times the power. A logarithmic scale fits a whisper and a jet engine on the same ruler.
- In an LLM
- A 1,000-token answer can have probability around 10⁻⁵⁰. Its log-probability is about −115: an ordinary number you can add, compare and take gradients of.
What a logarithm is
The logarithm answers "what power do I raise the base to, to get this number?"
- because .
- because .
- The natural log, , uses base . It's the default in ML.
The one property that matters most:
Multiplying turns into adding.
Logs of probabilities
Probabilities are between 0 and 1, so their logs are zero or negative:
| Probability | ln(probability) |
|---|---|
| 1 | 0 |
| 0.5 | −0.69 |
| 0.1 | −2.30 |
| 0.01 | −4.61 |
| 0.001 | −6.91 |
Each time the probability gets 10 times smaller, the log drops by the same amount, 2.30. Certain is 0; impossible is minus infinity.
A quiet room is about 30 dB and a busy street about 70 dB. The difference of 40 dB means the street carries times the sound power. Adding 40 on the log scale is the same as multiplying by 10,000 on the ordinary one.
The model writes three tokens with probabilities 0.5, 0.8 and 0.9.
- Probability of the answer:
- Log-probability: , which is
Same information, but the second is a sum, one term per token. Training code works with these per-token log-probabilities directly.
Try it
The two charts show the same answer both ways. The probability crashes to almost 0 within a few dozen tokens, and below a low enough per-token probability it drops under the smallest number a computer can store (the red line) and becomes exactly 0. The log-probability is a straight line that never runs out of room.
Why ML uses logs everywhere
- No underflow. Products of thousands of probabilities become too small for a computer to store. Sums of logs don't.
- Sums are easy to work with. The loss of a whole answer is the sum of per-token losses, and gradients of sums are sums of gradients.
- Ratios become differences. . Every probability ratio in RL (PPO, KL, DPO) is computed as a difference of log-probabilities.
Where this shows up
- Policy-gradient updates push up : policy gradient.
- Ratios are computed as
exp(logp_new - logp_old): PPO, importance sampling. - Every loss on the next pages is a log: cross-entropy.
Rules
The derivative of is . That's why the gradient of a log-probability is large when the probability is small: the model is pushed hardest on tokens it found unlikely.