Deep Learning Note 4: Softmax, Competition, and Entropy
We now know why we might want normalized, non-negative weights. The next question is how to obtain them from arbitrary real-valued compatibility scores. Suppose our scores are
We might initially think that the simplest solution is to divide every score by the sum of all the scores.
For this particular example, the result is
The weights are non-negative and sum to one. But what happens when the compatibility scores contain negative numbers? Consider
Their sum is one, so our normalized weights become
The weights still sum to one, but they no longer represent non-negative proportions. An even more problematic example is
The sum of the scores is zero. Dividing by their sum is undefined. Our dot products can naturally take positive, negative, or zero values, so directly normalizing them is not a reliable solution. We could attempt to solve this by applying a function that removes negative values, such as ReLU.
We could then normalize the resulting non-negative numbers.
This can work when at least one score is positive. However, all negative scores become exactly zero, even if one negative score represents much stronger relative compatibility than another. For example, the scores and both become zero. The difference between them is lost. If every score is negative, the denominator also becomes zero. There are ways of designing alternative attention mechanisms around such functions, but let us continue searching for a smooth transformation that works naturally for every finite real-valued input.
Exponentiation and softmax
The exponential function offers us a particularly elegant solution.
The first useful property of this function is that it is strictly positive for every finite real number.
Even if our original compatibility score is negative, exponentiation produces a positive quantity. For example,
Positive scores produce values greater than one.
This allows us to preserve differences between negative scores rather than collapsing them to zero. A score of still receives a larger transformed value than a score of . The second useful property is that the exponential function is strictly increasing.
Exponentiation therefore preserves the ranking of the compatibility scores. If the model believes that the first key is more compatible with the query than the second key, the exponential transformation does not reverse that preference. The third property is particularly interesting: the exponential function transforms additive differences into multiplicative differences.
This means that a fixed increase in a score corresponds to multiplying its transformed value by a fixed factor. For example,
Every increase of one in a score multiplies its exponentiated value by approximately . Every increase of two multiplies it by approximately . Every increase of five multiplies it by approximately . This gives us a powerful way of translating the model's relative preferences into differences in the strength with which information is retrieved. Why should we want such behaviour? Imagine that one key is clearly more useful than the others. We may want its associated value vector to dominate the retrieved information rather than simply receive a slightly larger contribution. On the other hand, if several keys receive similar scores, we may want their information to be blended together.
The exponential function gives us a smooth way to transition between these behaviours. It is useful to compare this with directly transforming positive scores into linear weights. Suppose two pieces of information receive scores of 10 and 11. If we normalize these scores directly, their weights become
The second piece of information receives only a slightly greater share. But suppose we exponentiate the scores first.
We can divide the numerator and denominator of both expressions by .
The same score difference of one now creates a considerably more pronounced preference. This matters because attention is supposed to perform selective information retrieval. If the model learns to produce a meaningful score gap between relevant and irrelevant information, exponentiation allows that gap to translate into a strong difference in their contributions. However, strong selectivity is not always desirable. Some computations genuinely require information from several different tokens. Excessively large score differences can prevent useful alternatives from participating and make the attention weights difficult to adjust during training. We will therefore eventually need to understand how the magnitude and spread of the scores are controlled.
For now, we have transformed arbitrary real-valued compatibility scores into strictly positive quantities. Our remaining task is to make these positive quantities sum to exactly one. Suppose we define
Since , their total
is also strictly positive. Now divide each transformed score by this total.
Substituting the definition of ,
This is softmax. It is worth stopping to understand exactly why the result must sum to one. The denominator is the same for every . Therefore,
Consequently,
There is nothing mysterious happening here. We are taking each positive quantity and expressing it as a fraction of the total. Imagine that three people possess 20, 30, and 50 coins. The total number of coins is 100. Their respective shares are
These shares must sum to one because together they account for the entire collection of coins. Softmax follows exactly the same principle. The exponential operation determines the positive quantities from which the shares are constructed. The division determines each quantity's share of the total. This distinction is important. Exponentiation is not responsible for making the probabilities sum to one. Normalization is responsible for that. Exponentiation gives us positive, smoothly increasing quantities with a particular form of competition. Dividing by their total converts those quantities into proportions. Indeed, if we had any strictly positive numbers , defining
would always produce weights summing to one. Softmax is the particular choice where . Let us work through an example completely. Suppose the compatibility scores are
Exponentiating each score gives
The total transformed quantity is
Dividing each quantity by this total gives
Our original scores have now become relative proportions of a total attention budget. The first value vector receives approximately 66.52% of the attention, the second receives approximately 24.47%, and the third receives approximately 9%. These are not necessarily calibrated probabilities that a token is objectively relevant. They are mathematically valid probability weights used to determine the relative contribution of the value vectors. Our attention output is consequently
We can interpret this computation as taking the expected value of a vector under a probability distribution. Imagine a random variable that selects a token position according to the probabilities .
The expected value of the selected value vector would be
This is exactly the attention output.
Standard softmax attention does not actually need to randomly sample a token from this distribution. Instead, it calculates the expected vector directly. This connects attention to the concept of a mean that we explored earlier. Ordinary averaging corresponds to taking an expectation under a uniform distribution, where every available outcome is equally likely. Attention corresponds to taking an expectation under a learned, query-dependent distribution, where different outcomes receive different weights. In this sense, an attention head computes a learned, context-dependent mean of the available value vectors. We are no longer asking what the average of all available information is. We are asking what the average information looks like when we assign greater importance to the pieces that are relevant to our current computation.
There is another important consequence of the normalization step. Because every transformed score participates in the same denominator, the attention weight belonging to one token depends not only on that token's own score, but also on the scores of all the other tokens. Suppose we start with three identical scores.
Softmax produces
Now increase only the first score from zero to two, leaving the other two scores completely unchanged.
The new probabilities become
The first token's weight has increased substantially. But something more interesting has happened. The weights of the second and third tokens have decreased, even though their own compatibility scores have not changed at all. Why? Because the total amount of transformed quantity in the denominator has increased. Previously, the second token possessed one unit out of a total of three units. Now it possesses the same one unit out of a total of approximately 9.389 units. Its absolute transformed score has remained unchanged, but its share of the total has decreased. This is precisely what we mean when we say that softmax creates competition.
An increase in the attention allocated to one value necessarily reduces the total attention available to the other values.
If increases by some positive amount , then the combined contribution of the remaining probabilities must decrease by .
This is not a metaphorical interpretation of competition. It is a direct mathematical consequence of the constraint. The important thing to understand is that the value vectors themselves are not performing the competition. The competition occurs among the query-key compatibility scores. Each key is being evaluated according to its compatibility with the current query. The associated value receives a share of the attention determined by the outcome of that competition. The keys compete to determine how strongly their corresponding values participate in the output. This becomes particularly clear when we write the attention computation explicitly:
For the moment, we are leaving out the scaling factor that will appear later. Notice the separation of responsibilities. The query and keys determine the coefficients. The values determine the actual information being combined. Suppose the first value contains information that helps resolve the pronoun it, while the other values contain unrelated information. When the first key receives a greater score, its corresponding value receives a greater share of attention. The unrelated values simultaneously receive less influence. This means that the model is not merely amplifying relevant information. It is also reducing the relative participation of competing information.
Returning to our discussion of cancellation, this can help prevent a useful signal from being diluted or cancelled by unrelated contributions. Of course, an attention head can still retrieve contradictory information, and normalized weighting does not guarantee that its output is useful. The ability to retrieve useful information depends on what the model learns. The architecture simply provides a differentiable mechanism through which such selective retrieval can be learned. This also helps us understand why using separate independent gates would produce a different kind of attention. Suppose we used the sigmoid function on every score independently:
Every gate would lie between zero and one, but there would be no requirement that the gates sum to one. If all three scores were very large, all three gates could become close to one simultaneously.
The resulting output would be approximately
Alternatively, if all three scores were sufficiently negative, all three gates could become close to zero.
The output could become approximately zero. Independent sigmoid gates therefore give the model the ability to decide separately whether each piece of information should participate. Softmax instead asks the model how a fixed total amount of influence should be distributed among the available pieces of information. These are two genuinely different mathematical designs. Neither is universally superior. The important point is to recognise the consequences of the particular choice being made. Softmax introduces relative competition, controlled total weight, and a weighted-average structure. In exchange, it does not provide a direct way to turn every attention coefficient off simultaneously.
This trade-off will later help us understand the emergence of attention sinks.
The geometry of the simplex
Let us now look at this same normalization constraint geometrically. Suppose we have two probabilities, and . They must satisfy
with both probabilities non-negative. If we choose , the second probability cannot be chosen independently. It must be
Likewise, if we choose , the second probability must be . Although we are writing two coordinates, there is only one quantity that we are free to choose. We can represent all possible distributions over these two outcomes as the points
where . Geometrically, these points form a line segment connecting and . The endpoints represent complete preference for one outcome or the other. The midpoint represents equal preference. Although this line segment exists inside the two-dimensional coordinate plane , the line segment itself is one-dimensional. We need only one number, , to identify any point on it. This distinction between the dimension of the surrounding space and the dimension of an object within that space is important. Imagine drawing a straight line on a sheet of paper. The sheet of paper is two-dimensional, but the line is one-dimensional because we only need one coordinate measuring our position along the line. Now suppose we have three probabilities.
We can choose and , provided they are non-negative and their sum is no greater than one. Once we have chosen them, the third probability is automatically determined.
If we choose and , then . We have three coordinates, but only two independent degrees of freedom. Geometrically, the possible distributions form a triangular region inside three-dimensional space. Its three vertices are
Each vertex represents complete preference for one of the three possible outcomes. The centre of the triangle is
which represents equal preference for every outcome. Every other valid probability distribution corresponds to a point somewhere inside the triangle or on its boundary. For example, lies close to the first vertex because most of the probability belongs to the first outcome. The distribution lies on the edge joining the first and second vertices because the third outcome receives no probability. The distribution lies inside the triangle because all three outcomes receive positive probability. This triangular region is called a simplex. More generally, a simplex is the simplest geometric object with a particular dimension that is formed by taking the convex hull of affinely independent vertices.
A zero-dimensional simplex is a single point. A one-dimensional simplex is a line segment. A two-dimensional simplex is a filled triangle. A three-dimensional simplex is a filled tetrahedron. The same construction extends into higher dimensions, even though we can no longer easily draw it. The probability simplex is the special simplex whose points represent all possible probability distributions over a finite collection of outcomes. For outcomes, it is defined as
Let us carefully unpack what this notation means. The expression tells us that a probability distribution is represented by a vector with real-valued coordinates. The condition restricts the coordinates to non-negative values. The condition restricts the vector to those points whose coordinates add up to one. The intersection of these restrictions produces the probability simplex. But why do we write rather than ? Because the sum-to-one constraint removes one independent degree of freedom. In general,
Once the first probabilities have been chosen appropriately, the final probability is determined. The vector has coordinates, but only independent degrees of freedom. If we have 128 possible outcomes, the probability simplex has 127 dimensions. If we have 10,000 possible outcomes, it has 9,999 dimensions. Here, the number of outcomes refers to the number of available tokens being attended to. It is not the same as the query-key dimension . For one query attending to 10,000 tokens with 128-dimensional keys, the query belongs to , while the attention probability distribution belongs to a 9,999-dimensional probability simplex embedded in .
These are two entirely different spaces. One is the space in which queries and keys are compared. The other is the space of all possible distributions of attention over the available tokens. Softmax is the mathematical function that maps the raw compatibility scores into this second space.
Here, denotes the relative interior of the simplex. For finite, unmasked logits, every exponential is strictly positive. Consequently, every attention weight is also strictly positive. Softmax therefore produces points inside the simplex rather than directly on its boundary. It can get arbitrarily close to a vertex, but it cannot produce an exact vertex using finite logits in exact arithmetic. In actual implementations, masking and floating-point underflow can produce exact zero weights. But mathematically, ordinary softmax over finite scores produces strictly positive weights. Now consider how this probability simplex connects to the value vectors themselves.
Suppose we have three value vectors, , , and . Our attention output is
Because the coefficients are non-negative and sum to one, this operation is called a convex combination. A convex combination produces a point within the convex hull of the vectors being combined. For two value vectors, every possible convex combination lies on the line segment connecting the two vectors.
If , the output is . If , the output is . If , the output lies exactly halfway between them. For three non-collinear value vectors, the possible outputs form a filled triangle connecting those vectors. This triangle does not have to be the same shape or size as the probability simplex. The probability simplex describes the coefficients. The convex hull describes the possible retrieved representations. The attention mechanism maps points in the first space to points in the second space.
This gives us a geometric interpretation of what an attention head is doing. As the query changes, the compatibility scores change. As the compatibility scores change, softmax moves the probability vector to a different location within the probability simplex. That movement changes the convex combination of the value vectors, which moves the retrieved representation towards different pieces of information. The model can continuously navigate among the available value representations. There is something particularly elegant about this. What began as the seemingly abstract requirement that probabilities sum to one has become a geometric description of how a neural network retrieves and blends information.
Exponential competition and score differences
However, we still have not fully understood why the exponential function is such a natural choice for constructing this distribution. Let us examine its relationship with differences between scores. Suppose two keys receive compatibility scores of 2 and 1.
Softmax gives them probabilities
Now suppose the scores become 102 and 101.
The absolute scores are dramatically larger. But the difference between them remains one.
What should happen to the attention distribution? If our goal is to distribute a fixed amount of attention according to relative compatibility, there is a compelling argument that the distribution should remain unchanged. The first key is still preferred over the second key by exactly the same margin. Nothing has changed about their relationship. Softmax has precisely this property. Suppose we add a constant to every score. The new score associated with token is
The resulting softmax probability becomes
Using the exponential identity
we can rewrite this as
The factor is common to every term in the denominator, so we can factor it out.
The common factor cancels.
Consequently,
This property is called shift invariance. The vector represents a vector containing ones in every coordinate. Multiplying it by and adding it to simply shifts every score by the same amount. Shift invariance tells us that softmax is indifferent to the common numerical location of its inputs. But why is this useful? To understand this, imagine that our query-key comparisons contain two different components. One component is a shared feature that contributes equally to every key. The other component distinguishes between individual keys. For instance,
Here, is a shared component present in every key, while is the component that distinguishes key from the others. The dot product becomes
The quantity is the same for every key. It adds a common offset to every compatibility score. Consequently,
The shared contribution cancels during normalization. This makes intuitive sense. A feature that increases the compatibility of every available key by exactly the same amount does not help us decide which key should receive a greater share of attention. If every piece of information becomes equally more attractive, their relative proportions need not change. Softmax removes this common component of the scores automatically. This should not be interpreted as saying that absolute compatibility can never be useful. Sometimes we may want to know whether any available information is sufficiently relevant at all. Standard softmax cannot distinguish a collection of uniformly poor matches from a collection of uniformly excellent matches when their relative scores are identical. For example,
Both produce
The first collection might intuitively represent three terrible matches. The second might represent three excellent matches. Softmax only knows how to distribute its fixed budget among them. It has no independent notion of whether the entire budget should be used. This limitation will become particularly important when we discuss attention heads that have nothing useful to retrieve. For now, let us concentrate on the benefit of shift invariance: it allows the model to express preference using relative differences rather than requiring every score to occupy some particular absolute numerical scale. We can understand this relationship even more directly by comparing two softmax probabilities.
and
Taking their ratio,
Therefore,
This is one of the most revealing equations in our entire discussion of softmax. It tells us exactly how the difference between two compatibility scores translates into their relative shares of attention. If their scores are identical, then
and
Both values receive equal coefficients. If their score difference is one,
The first value receives approximately 2.718 times as much attention as the second. If their score difference is five,
If their score difference is ten,
The relationship between score differences and relative contributions is exponential. This is what we mean by exponential competition. Imagine that two token positions both contain some information useful to the current query, but one is considerably more relevant. If the learned query-key projections produce a meaningful score difference, softmax can translate that difference into a very large difference in their relative contributions. This gives an attention head the ability to behave somewhat like a selective lookup operation. However, when the scores are close together, their probabilities remain relatively close together, allowing the model to blend information from several sources.
The same mathematical operation can therefore support both distributed information retrieval and highly selective information retrieval. Importantly, this does not mean that a score advantage of ten necessarily gives a token almost all the attention. A token competes against the entire collection of available keys, not merely one other key. For example, suppose one key receives a score of 10, while each of 10,000 other keys receives a score of zero. The preferred key's attention probability is
Since , we obtain
Although the preferred key receives more than 22,000 times the probability of each individual competitor, all the competitors together still account for approximately 31.22% of the total attention. This is another beautiful connection to our first bridge. A large number of individually small contributions can collectively become significant. Here, however, the contributions in the denominator are all positive. They do not cancel one another. Their combined effect grows with the number of competitors. If one preferred key receives a score of , and other keys all receive scores of zero, its probability is
Rearranging this equation gives
Therefore,
Taking the natural logarithm,
This tells us how large the preferred key's score advantage must be to obtain a desired share of attention under these simplified conditions. To obtain exactly half the attention, we set .
Consequently,
As the number of competing keys increases, the score margin needed to dominate their collective contribution also increases. This provides a mathematical reason why selective retrieval can become more challenging as context length increases. Even individually weak competitors may create substantial collective competition. Real attention scores are not uniformly zero, so the precise behaviour depends on their distribution. We will encounter the same phenomenon again when studying the output softmax of language models, where a correct token must compete against an entire vocabulary.
Why the exponential function is unique
Let us now ask a deeper question. Is the exponential function merely a convenient choice, or is there a more fundamental reason for using it? Suppose we want to construct weights by transforming each score using some positive function and normalizing the results.
The ratio between two probabilities is
Suppose we want this ratio to depend only on the difference , rather than on the individual numerical locations of the scores. In other words, we want
for every common shift . Setting , we obtain
Rearranging,
We can remove the arbitrary overall scale by defining
Our condition becomes
This is the defining functional relationship of the exponential function. Under ordinary continuity and positivity assumptions, its solutions have the form
where is a constant. If we want higher scores to receive higher weights, we choose . The arbitrary overall scale of cancels during normalization, leaving
This is a temperature-scaled softmax. We have arrived at the exponential function by starting with a desired property of relative competition. We wanted the ratio between two weights to depend on their score difference and remain unchanged under common shifts. Under these assumptions, exponentiation arises naturally. This is not a proof that softmax is the only reasonable attention mechanism. Rather, it shows that softmax is a particularly natural consequence of a specific collection of mathematical design choices. There is another, perhaps even more beautiful, way of understanding why softmax appears. Imagine that we already know the compatibility scores , and we must choose a probability distribution over them. The average compatibility obtained under a distribution is
Suppose our only objective is to maximize this expected compatibility.
What would be the best distribution? We would assign all the probability to whichever score is largest. If is the unique largest score, the optimal solution is
There is no benefit to allocating probability to lower-scoring alternatives because doing so would reduce the expected compatibility. This is hard selection, commonly represented by the argmax operation.
The resulting information retrieval mechanism would simply return
Hard selection can be useful. However, it introduces a challenge when we want to learn the scores through gradient descent. Imagine two scores, and . Hard selection retrieves the first value. If we increase slightly, the selected value remains exactly the same. If we decrease slightly but it remains larger than , the selected value still remains exactly the same. But the moment the second score becomes larger than the first, the retrieved information changes abruptly from one value vector to another. As a function of the scores, ordinary hard selection is constant within regions and discontinuous at their boundaries.
Its gradient with respect to the selection scores is zero almost everywhere and undefined at the switching boundaries. This makes it difficult to learn the routing mechanism using ordinary backpropagation without additional techniques. What we would like instead is a smooth version of selection. If one score is slightly better than another, perhaps it should receive slightly more weight. If it is substantially better, perhaps it should receive considerably more weight. We can obtain such behaviour by adding another objective that encourages us not to become unnecessarily concentrated. This objective involves entropy. The entropy of a probability distribution is defined as
Entropy describes how spread out a probability distribution is, or equivalently, how uncertain we are about which outcome will be selected. For a distribution concentrated entirely on one outcome,
the entropy is zero.
There is no uncertainty about which outcome will be chosen. For a uniform distribution,
the entropy becomes
This is the maximum possible entropy for a distribution over outcomes. Instead of maximizing only the expected compatibility, we can maximize a combination of expected compatibility and entropy.
The positive constant determines how much we value maintaining a spread-out distribution. The first term encourages us to place more probability on high-scoring keys. The second term encourages us to preserve some probability for competing alternatives. These two objectives pull in different directions. If we care only about maximizing compatibility, we obtain hard selection. If we care overwhelmingly about entropy, we obtain a nearly uniform distribution. Between these extremes, we obtain a distribution that balances selectivity and flexibility. Remarkably, the solution to this optimization problem is exactly softmax with temperature .
We can derive this using a Lagrange multiplier, which is a mathematical technique for optimizing a function subject to a constraint. Our constraint is
We construct the following expression:
Differentiating with respect to an individual probability ,
At the optimum, this derivative is zero.
Rearranging,
Exponentiating both sides,
The second exponential is a constant shared by every probability. Let us call it .
We still need the probabilities to sum to one.
Therefore,
Substituting this back,
Softmax is the unique optimum for this entropy-regularized objective when . This gives us a substantially deeper interpretation of the function. Softmax can be understood as the distribution that prefers high-scoring alternatives while avoiding the complete elimination of uncertainty. The temperature controls how strongly we value the second objective. This is a mathematical characterization of softmax, rather than a claim that an ordinary attention head explicitly solves a separate optimization problem during its forward pass. The attention head simply evaluates the softmax formula. The optimization interpretation helps us understand the particular behaviour that formula implements.