Cross entropy has always been the standard loss function for LLM pre-training and fine-tuning. But can this 'standard' be changed? If we want to change it, what choices do we have? And what impacts will follow once it is changed?
Many readers have probably never scrutinized these questions carefully. On the one hand, cross entropy is concise and effective, backed by information-theoretic interpretations, which makes us feel it is so 'taken for granted' that we gladly accept it. On the other hand, changing the loss function is something where 'a single move affects the entire situation'—after switching, all loss-based comparisons are no longer valid, leaving us to compare only downstream task performance, which requires an immense engineering effort.
However, 'taken for granted' does not mean 'there is no other choice.' Thinking through the underlying principles not only helps us better understand the model's optimization process, but may also bring new perspectives for improving performance.
More precisely, cross entropy is the standard loss function for classification problems, and LLM training looks like token-by-token classification, so cross entropy loss was adopted as a natural carryover. Seen this way, is it enough just to switch to another classification loss function?
Unfortunately, no. Unlike standard classification problems, patterns in natural language are one-to-many. For instance, after 'white-cut', one can follow not only with 'chicken', but also 'duck', 'dog', 'sheep', etc. Thus, what we want to model is the complete distribution, rather than simply predicting a single label. In other words, we need to estimate the probabilities of following 'white-cut' with 'chicken', 'duck', 'dog', 'sheep', etc., rather than merely outputting one correct answer—there is no unique correct answer.
And the core difficulty here is that the training corpus is fed into the model in a 'piecemeal' manner: this time comes 'white-cut chicken', next time might be 'white-cut duck', and later another 'white-cut chicken' may appear. We cannot compute the complete frequency distribution in advance, which requires the loss function to have the ability to be converted into a sampled form. In mathematical terms, this requires the loss function with respect to the target distribution to be linear, that is,
where represent the target distribution and predicted distribution, respectively; the condition after indicates that once is fixed, the minimizer of is , which is the basic requirement for a loss function. The linearity constraint rules out many common probability metrics, such as Total Variation:
To estimate it via sampling, we need to compute , yet cannot be known in advance, so Total Variation cannot be adapted into a form for LLM training.
Now let us solve for the objective . According to the basic requirements of a loss function, after fixing , the minimum value of is , and thus we can write
Now let us focus our attention on the variable . Evidently, is linear with respect to , so when we fix , the left-hand side describes a hyperplane while the right-hand side describes a hypersurface, and they intersect at . If we further assume, or require, that the minimum point is unique, then this intersection is actually tangency—that is, is the tangent plane of at !
Since the above inequality holds identically, this is equivalent to saying that always lies below its tangent plane, which is precisely the definition of a concave function! Therefore, we can confirm that is a concave function. Conversely, if we choose a concave function of , denoted by , then its tangent plane at is
where the equality utilizes the constraint (that the components sum to 1), "" denotes the inner product, and adding a scalar to a vector is treated element-wise. According to the preceding derivation, the above expression is precisely our desired , so we can directly read off
This is the general form of (allowing the addition or subtraction of a constant and multiplication by a positive constant), where denotes the component of at index , and is the one-hot vector with 1 at position . It is easy to see that is linear with respect to , and the linear interpolation of two concave functions remains a concave function, so the linear interpolation of two scoring functions is still a scoring function.
The above results actually have a specialized name, known as Proper Scoring Rules; we will not trace where this name came from. Below, several classic examples are given:
It is worth pointing out that the latter three scoring functions all degenerate into the logarithmic score as , which means they are all generalizations of cross-entropy to some extent. In particular, if we further require that depends only on , namely , then cross-entropy is the only choice. This is not difficult to prove: in this case, , which, substituted into Eq. , yields
where the term is also equivalent to a constant for an individual , so this equation is equivalent to , which is easily solved to give , yielding the logarithmic score.
Note: The argument here is actually somewhat lacking in rigor. Due to the constraint , the notion of "depending only on " is itself not so straightforward. For example, with , we cannot simply claim that depends only on .
A similar confusion arises in the argument of whether " depends on ". A relatively rigorous formulation here is to require only the first values of to satisfy , being eliminated via , which leaves only relatively independent variables. implies that the first terms of are equal to the same expression containing , but also depends at most on , so this expression can only be a constant, thereby yielding .
All of these scoring functions can be extended to continuous distributions, simply by replacing the discrete variable with a continuous variable , and replacing summation with integration. However, the difficulty with continuous distributions often lies in the intractability of computing the normalizing constant. Since all of these scoring functions require an explicit probability density, they are usually not that "easy to use." In such scenarios, one needs scoring functions that do not depend on the normalizing constant (which typically rely on gradients, a feature unique to continuous distributions), but we will not expand on that here.
As mentioned earlier, the last three scoring functions are all generalizations of cross entropy. Intuitively, then, as long as we fine-tune , would we have a chance of achieving improvements in downstream tasks? However, things are not so simple.
In general, a model can only predict an unbounded logit vector , and we need to apply an activation function to project it into a probability distribution , where the common choice of activation function is Softmax. Since we can only use gradient-based optimizers, the convexity and gradient properties of the loss function with respect to become especially important. Taking the logarithmic score and the Brier score as examples, under the Softmax activation function, the gradients of the loss with respect to are respectively
Clearly, the gradient of cross entropy looks "cleaner": it is zero if and only if , which indicates that as long as the target has not been reached, it provides an effective gradient, and the farther from the target, the larger the gradient; squared loss introduces an extra transformation term . When , this term also becomes zero, indicating that when the model is "confidently wrong," its gradient also vanishes.
This property is a double-edged sword: in the early-to-mid stages, most of the model's predictions are inaccurate, which means learning with squared loss is extremely inefficient; in the later stages, however, the model has largely stabilized, and samples that remain "confidently wrong" at this point are likely extremely difficult or mislabeled, so skipping them may be more beneficial to overall performance. Therefore, cross entropy has higher learning efficiency and should serve as the primary loss, while squared loss has better noise robustness and can be experimented with in the later stages.
These can also be understood in terms of the convexity of with respect to . It can be proved that under the Softmax activation, cross entropy is convex with respect to , which means the optimal point is unique and the gradient at any point points toward the target point ; however, the squared loss is non-convex with respect to , so none of these desirable properties are guaranteed to exist, and the model may enter a saturation dilemma of being 'both wrong and unable to escape'.
Of course, even if convexity with respect to holds, still has parameters, and in deep models the loss function with respect to the parameters can generally only be non-convex. Our requirement for the convexity of the loss function with respect to is mostly out of consideration of not causing extra trouble for the model—optimization in deep learning is already difficult enough, and there is no need to add another obstacle at the final layer.
The results in the previous section all had a prerequisite—the Softmax activation—but what if it is not the Softmax activation? Or conversely, for a given scoring function, can we derive the 'optimal' activation function suitable for that scoring function?
The first question to consider is: how should 'optimal' be defined? Looking at the 'Softmax + cross entropy' combination, it has two advantages: first, its convexity with respect to , and second, that the gradient is relatively 'clean'. In fact, the second point is stronger and more practical, so we start our consideration from the second point. That is, we hope to find a transformation such that for a given , we have
Notice that , so the above equation can also be written as , which indicates that there exists, independent of , a scalar function such that
Rearranging terms gives . Multiplying both sides by and then summing yields
Rearranging terms further yields , which holds for any , so is an upper bound for all . Then substituting into the above expression gives , that is, equality is attained when , so is the 'supremum' of all , namely
This is precisely the convex function 's convex conjugate, and putting together the content of these sections gives precisely the classic Fenchel-Young Losses framework.
In this section, we will likewise derive the optimal activation functions corresponding to the several scoring rules mentioned earlier. It is not difficult to see that their corresponding all share the same structure: , so we can solve them in a unified way. Let , then , where
Introducing the Lagrangian , taking the derivative with respect to and setting it to 0 gives
For each individual component, and are shared "constants"; our goal is simply to tune these two constants so that becomes a valid distribution. Note that has only two possibilities: and ; the latter is trivial, so we only need to analyze the former. Also notice that for , we have , while for , , so we can write
where , but for this truncation is redundant, because in this case the exponent is negative, and negative powers of zero are undefined, so the truncation will never take effect. This also indicates that corresponds to a sparse distribution, while corresponds to a dense distribution. As for , it is determined by the equation . Clearly, corresponds precisely to the classical Softmax; when , for the Tsallis scoring rule we have , so can be solved using the condition via bisection. When , the result is precisely Sparsemax, while the other cases are called Entmax-. When and , admits exact solution methods that are more efficient than bisection, which we also introduced in Road to Probability Distributions: A Review of Softmax and Its Alternatives. As for the results for the other scoring rules, they are slightly more complicated and are left for readers to try.
In this post, from the two perspectives of "learning distributions" and "allowing sampling", we derived a general construction for LM loss. Subsequently, in conjunction with the activation functions used for the predictive distribution, we calculated the gradients and convexity of these losses to simply assess their pros and cons. Finally, starting from a given loss, we attempted to reverse-derive its accompanying optimal activation function, and the optimal activation function for cross entropy is precisely Softmax—which explains why the two almost always appear as a pair.