Foundations

Loss functions and cross-entropy

Cross-entropy scores the probability a model assigned to what actually happened — and in Qwen3.8-27B that is one 248,320-way choice per token, where the difference between a good and a bad model is a couple of nats.

Updated

01 · Concept

Concept

A model has just read the prefix “The capital of France is” and must produce a number saying how well it did. What number? “Right or wrong” is nearly useless: it cannot distinguish a model that ranked the correct continuation second from one that ranked it two hundred thousandth, and a flag has no gradient to descend. The scoring rule has to reward probability mass placed on what actually happened, and it has to punish confident mistakes harder than uncertain ones. That rule is cross-entropy, and this lesson makes it concrete at the scale the rest of the course works in.

A loss function turns model output and target into a single scalar that optimization can reduce. For classification the network emits one logit ziz_i per class — an unrestricted score, not a probability. Softmax converts the logits into a distribution:

pi=ezijezj.p_i=\frac{e^{z_i}}{\sum_j e^{z_j}}.

Adding the same constant to every logit changes nothing, so only relative scores matter. If the observed class is yy, one-hot cross-entropy is simply

L=logpy.L=-\log p_y.

Probability near one gives loss near zero; probability near zero gives an enormous loss. The asymmetry is the useful part.

Now scale it. In Qwen3.8-27B the classes are vocabulary entries, and there are 248,320 of them (Qwen3.8-27B Model Card, 2026). Every token position is a 248,320-way classification, and the final linear layer that produces those logits is a matrix mapping the 5120-dimensional hidden state to 248,320 outputs — about 1.271 billion parameters, held separately from the embedding table because this model does not tie the two.

Work out what the numbers mean, step by step. First establish the baseline: a model that has learned nothing spreads probability uniformly, giving every entry 1/248,3201/248{,}320, so its loss is log(1/248,320)=ln(248,320)12.42-\log(1/248{,}320)=\ln(248{,}320)\approx12.42 nats per token. That is the uniform baseline, the cost of pure ignorance; it is not a ceiling, because assigning the observed token still less probability produces arbitrarily larger loss. Now suppose training brings the average loss to 2.0 nats. Exponentiate to get perplexity: e2.07.4e^{2.0}\approx7.4. Read that as an effective branching factor — on average the model behaves as though it were choosing uniformly among about seven or eight candidates rather than a quarter of a million. The 12.42 nats of raw uncertainty have been cut to 2.0.

Keep going, because the geometry of nats is not linear. Reaching 1.9 nats sounds like a rounding difference; in perplexity it is e1.96.7e^{1.9}\approx6.7, a reduction of nearly ten percent in effective candidates. Each nat removed divides the branching factor by e2.72e\approx2.72. This is why loss curves that look flat late in training still represent real progress, and equally why a tenth of a nat is worth arguing about.

Here is the classic wrong turn, and it survives into published comparisons. Two models report average cross-entropy of 2.0 and 2.3 nats. It is tempting to conclude the first is better. It may not be comparable at all: if the second model uses a coarser tokenizer, its tokens carry more text each, so it makes fewer, harder predictions over the same document. Loss per token is not loss per unit of text. The correction is to normalize by something tokenizer-independent — bits per byte or bits per character, as lesson 1.7 set up — before comparing across vocabularies. Within one tokenizer, loss per token is exactly the right currency; across tokenizers, it is a category error.

Numerical stability is the other place implementations go wrong. Exponentiating large logits overflows, and tiny softmax probabilities underflow to zero before a logarithm can be taken. Libraries therefore fuse log-softmax with negative log-likelihood using the log-sum-exp identity, usually by subtracting the maximum logit first. Two failure modes follow from ignoring this: passing already-softmaxed probabilities into a primitive that expects logits, which silently applies softmax twice and flattens the distribution, and taking the log of a materialized zero, which yields an infinity that propagates through the whole batch.

Two details of reduction deserve care because they quietly change the objective. Batch loss is a mean or sum over examples and, for language models, over token positions; padded positions and ignored labels need a mask so they contribute neither to the numerator nor the denominator. Averaging per token weights every token equally, while averaging per sequence weights every sequence equally — different objectives, and the difference is visible whenever lengths vary. Soft targets change the problem again: with a target distribution qq the loss becomes L=iqilogpiL=-\sum_i q_i\log p_i, which is how label smoothing and knowledge distillation work. These are modelling decisions, not numerical conveniences.

A practical audit uses logits you can compute by hand. Verify that raising the correct-class logit lowers the loss, that shifting all logits by one constant changes nothing, that ignored positions contribute nothing, and that the reported mean uses the denominator you intended. Those four invariants catch double-softmax, off-by-one label shifts, and padding bugs that a long, smoothly decreasing curve will otherwise hide for days.

02 · Analogy

Analogy

A navigation coach does not merely mark a driver wrong; the score must say how strongly the chosen route conflicted with the destination. Cross-entropy is especially strict when the driver assigns almost no chance to the road that turns out to be correct. Averaging scores over trips creates a training objective. The coach's score shapes practice, but it is not the whole quality of driving: comfort, safety, and fairness may need separate measures.

03 · Teach it back

Teach it back

Explain logits, softmax, and one-hot cross-entropy, then interpret an average training loss of 2.0 nats for a model whose vocabulary holds 248,320 entries.

Minimum: 80 characters and 15 words. Your writing stays only in this browser.

Waiting for your explanation.

Compare with a model answer

The model emits one unrestricted logit per vocabulary entry; softmax converts relative logits into a distribution; for the observed token the loss is −log p. A uniform guess over 248,320 entries costs ln(248,320) ≈ 12.42 nats, so that is the do-nothing baseline. An average of 2.0 nats corresponds to a perplexity of e² ≈ 7.4: on average the model has narrowed a quarter-million-way choice down to roughly seven or eight effective candidates. The remaining gap is not small — each further nat removed is a factor of e in effective branching — and losses are only comparable between models that share a tokenizer.

04 · Check your understanding

Check your understanding

01Lesson 2.3 described activations as elementwise curves applied independently to each coordinate. Why does softmax not belong to that family?
Answer and explanation

Its denominator sums over every logit, so changing one coordinate changes all outputs — it couples the whole vector — That coupling is exactly what makes the outputs a distribution summing to one, and it is why softmax lives in the loss rather than between layers.

02A language model with a 248,320-entry vocabulary reports an average loss of 2.0 nats. What does that mean concretely?
Answer and explanation

Perplexity of about 7.4 — the model has narrowed a quarter-million-way choice to roughly seven or eight effective candidates — Perplexity is the exponential of the mean negative log-likelihood; a uniform guess would cost ln(248,320) ≈ 12.42 nats instead.

03Why should training code usually pass logits to a cross-entropy primitive rather than probabilities?
Answer and explanation

The combined log-softmax computation is numerically stable, avoiding overflow, underflow, and log of zero — Materializing tiny softmax probabilities and then taking their logarithm loses precision the fused form preserves, and it invites applying softmax twice.

Complete the teach-back and answer the quiz correctly to finish this lesson.

◎ · Evidence marker

Sources

  1. Claude E. Shannon (1948). A Mathematical Theory of Communication.
  2. Qwen Team (2026). Qwen3.8-27B Model Card.