Recent from talks
Contribute something
Nothing was collected or created yet.
Softmax function
View on Wikipedia| Part of a series on |
| Machine learning and data mining |
|---|
The softmax function, also known as softargmax[1]: 184 or normalized exponential function,[2]: 198 converts a tuple of K real numbers into a probability distribution over K possible outcomes. It is a generalization of the logistic function to multiple dimensions, and is used in multinomial logistic regression. The softmax function is often used as the last activation function of a neural network to normalize the output of a network to a probability distribution over predicted output classes.
Definition
[edit]The softmax function takes as input a tuple z of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers. That is, prior to applying softmax, some tuple components could be negative, or greater than one; and might not sum to 1; but after applying softmax, each component will be in the interval , and the components will add up to 1, so that they can be interpreted as probabilities. Furthermore, the larger input components will correspond to larger probabilities.
Formally, the standard (unit) softmax function , where , takes a tuple and computes each component of vector with
In words, the softmax applies the standard exponential function to each element of the input tuple (consisting of real numbers), and normalizes these values by dividing by the sum of all these exponentials. The normalization ensures that the sum of the components of the output vector is 1. The term "softmax" derives from the amplifying effects of the exponential on any maxima in the input tuple. For example, the standard softmax of is approximately , which amounts to assigning almost all of the total unit weight in the result to the position of the tuple's maximal element (of 8).
In general, instead of e a different base b > 0 can be used. As above, if b > 1 then larger input components will result in larger output probabilities, and increasing the value of b will create probability distributions that are more concentrated around the positions of the largest input values. Conversely, if 0 < b < 1 then smaller input components will result in larger output probabilities, and decreasing the value of b will create probability distributions that are more concentrated around the positions of the smallest input values. Writing or [a] (for real β)[b] yields the expressions:[c]
A value proportional to the reciprocal of β is sometimes referred to as the temperature: , where k is typically 1 or the Boltzmann constant and T is the temperature. A higher temperature results in a more uniform output distribution (i.e. with higher entropy; it is "more random"), while a lower temperature results in a sharper output distribution, with one value dominating.
In some fields, the base is fixed, corresponding to a fixed scale,[d] while in others the parameter β (or T) is varied.
Interpretations
[edit]Smooth arg max
[edit]The Softmax function is a smooth approximation to the arg max function: the function whose value is the index of a tuple's largest element. The name "softmax" may be misleading. Softmax is not a smooth maximum (that is, a smooth approximation to the maximum function). The term "softmax" is also used for the closely related LogSumExp function, which is a smooth maximum. For this reason, some prefer the more accurate term "softargmax", though the term "softmax" is conventional in machine learning.[3][4] This section uses the term "softargmax" for clarity.
Formally, instead of considering the arg max as a function with categorical output (corresponding to the index), consider the arg max function with one-hot representation of the output (assuming there is a unique maximum arg): where the output coordinate if and only if is the arg max of , meaning is the unique maximum value of . For example, in this encoding since the third argument is the maximum.
This can be generalized to multiple arg max values (multiple equal being the maximum) by dividing the 1 between all max args; formally 1/k where k is the number of arguments assuming the maximum. For example, since the second and third argument are both the maximum. In case all arguments are equal, this is simply Points z with multiple arg max values are singular points (or singularities, and form the singular set) – these are the points where arg max is discontinuous (with a jump discontinuity) – while points with a single arg max are known as non-singular or regular points.
With the last expression given in the introduction, softargmax is now a smooth approximation of arg max: as , softargmax converges to arg max. There are various notions of convergence of a function; softargmax converges to arg max pointwise, meaning for each fixed input z as , However, softargmax does not converge uniformly to arg max, meaning intuitively that different points converge at different rates, and may converge arbitrarily slowly. In fact, softargmax is continuous, but arg max is not continuous at the singular set where two coordinates are equal, while the uniform limit of continuous functions is continuous. The reason it fails to converge uniformly is that for inputs where two coordinates are almost equal (and one is the maximum), the arg max is the index of one or the other, so a small change in input yields a large change in output. For example, but and for all inputs: the closer the points are to the singular set , the slower they converge. However, softargmax does converge compactly on the non-singular set.
Conversely, as , softargmax converges to arg min in the same way, where here the singular set is points with two arg min values. In the language of tropical analysis, the softmax is a deformation or "quantization" of arg max and arg min, corresponding to using the log semiring instead of the max-plus semiring (respectively min-plus semiring), and recovering the arg max or arg min by taking the limit is called "tropicalization" or "dequantization".
It is also the case that, for any fixed β, if one input is much larger than the others relative to the temperature, , the output is approximately the arg max. For example, a difference of 10 is large relative to a temperature of 1: However, if the difference is small relative to the temperature, the value is not close to the arg max. For example, a difference of 10 is small relative to a temperature of 100: As , temperature goes to zero, , so eventually all differences become large (relative to a shrinking temperature), which gives another interpretation for the limit behavior.
Statistical mechanics
[edit]In statistical mechanics, the softargmax function is known as the Boltzmann distribution (or Gibbs distribution):[5]: 7 the index set are the microstates of the system; the inputs are the energies of that state; the denominator is known as the partition function, often denoted by Z; and the factor β is called the coldness (or thermodynamic beta, or inverse temperature).
Applications
[edit]The softmax function is used in various multiclass classification methods, such as multinomial logistic regression (also known as softmax regression),[2]: 206–209 [6] multiclass linear discriminant analysis, naive Bayes classifiers, and artificial neural networks.[7] Specifically, in multinomial logistic regression and linear discriminant analysis, the input to the function is the result of K distinct linear functions, and the predicted probability for the jth class given a sample tuple x and a weighting vector w is:
This can be seen as the composition of K linear functions and the softmax function (where denotes the inner product of and ). The operation is equivalent to applying a linear operator defined by to tuples , thus transforming the original, probably highly-dimensional, input to vectors in a K-dimensional space .
Neural networks
[edit]The standard softmax function is often used in the final layer of a neural network-based classifier. Such networks are commonly trained under a log loss (or cross-entropy) regime, giving a non-linear variant of multinomial logistic regression.
Since the function maps a tuple and a specific index to a real value, the derivative needs to take the index into account:
This expression is symmetrical in the indexes and thus may also be expressed as
Here, the Kronecker delta is used for simplicity (cf. the derivative of a sigmoid function, being expressed via the function itself).
To ensure stable numerical computations subtracting the maximum value from the input tuple is common. This approach, while not altering the output or the derivative theoretically, enhances stability by directly controlling the maximum exponent value computed.
If the function is scaled with the parameter , then these expressions must be multiplied by .
See multinomial logit for a probability model which uses the softmax activation function.
Reinforcement learning
[edit]In the field of reinforcement learning, a softmax function can be used to convert values into action probabilities. The function commonly used is:[8]
where the action value corresponds to the expected reward of following action a and is called a temperature parameter (in allusion to statistical mechanics). For high temperatures (), all actions have nearly the same probability and the lower the temperature, the more expected rewards affect the probability. For a low temperature (), the probability of the action with the highest expected reward tends to 1.
Computational complexity and remedies
[edit]In neural network applications, the number K of possible outcomes is often large, e.g. in case of neural language models that predict the most likely outcome out of a vocabulary which might contain millions of possible words.[9] This can make the calculations for the softmax layer (i.e. the matrix multiplications to determine the , followed by the application of the softmax function itself) computationally expensive.[9][10] What's more, the gradient descent backpropagation method for training such a neural network involves calculating the softmax for every training example, and the number of training examples can also become large. The computational effort for the softmax became a major limiting factor in the development of larger neural language models, motivating various remedies to reduce training times.[9][10]
Approaches that reorganize the softmax layer for more efficient calculation include the hierarchical softmax and the differentiated softmax.[9] The hierarchical softmax (introduced by Morin and Bengio in 2005) uses a binary tree structure where the outcomes (vocabulary words) are the leaves and the intermediate nodes are suitably selected "classes" of outcomes, forming latent variables.[10][11] The desired probability (softmax value) of a leaf (outcome) can then be calculated as the product of the probabilities of all nodes on the path from the root to that leaf.[10] Ideally, when the tree is balanced, this would reduce the computational complexity from to .[11] In practice, results depend on choosing a good strategy for clustering the outcomes into classes.[10][11] A Huffman tree was used for this in Google's word2vec models (introduced in 2013) to achieve scalability.[9]
A second kind of remedies is based on approximating the softmax (during training) with modified loss functions that avoid the calculation of the full normalization factor.[9] These include methods that restrict the normalization sum to a sample of outcomes (e.g. Importance Sampling, Target Sampling).[9][10]
Numerical algorithms
[edit]The standard softmax is numerically unstable because of large exponentiations. The safe softmax method calculates insteadwhere is the largest factor involved. Subtracting by it guarantees that the exponentiations result in at most 1.
The attention mechanism in Transformers takes three arguments: a "query vector" , a list of "key vectors" , and a list of "value vectors" , and outputs a softmax-weighted sum over value vectors:The standard softmax method involves several loops over the inputs, which would be bottlenecked by memory bandwidth. The FlashAttention method is a communication-avoiding algorithm that fuses these operations into a single loop, increasing the arithmetic intensity. It is an online algorithm that computes the following quantities:[12][13]and returns . In practice, FlashAttention operates over multiple queries and keys per loop iteration, in a similar way as blocked matrix multiplication. If backpropagation is needed, then the output vectors and the intermediate arrays are cached, and during the backward pass, attention matrices are rematerialized from these, making it a form of gradient checkpointing.
Mathematical properties
[edit]Geometrically the softmax function maps the Euclidean space to the boundary of the standard -simplex, cutting the dimension by one (the range is a -dimensional simplex in -dimensional space), due to the linear constraint that all output sum to 1 meaning it lies on a hyperplane.
Along the main diagonal softmax is just the uniform distribution on outputs, : equal scores yield equal probabilities.
More generally, softmax is invariant under translation by the same value in each coordinate: adding to the inputs yields , because it multiplies each exponent by the same factor, (because ), so the ratios do not change:
Geometrically, softmax is constant along diagonals: this is the dimension that is eliminated, and corresponds to the softmax output being independent of a translation in the input scores (a choice of 0 score). One can normalize input scores by assuming that the sum is zero (subtract the average: where ), and then the softmax takes the hyperplane of points that sum to zero, , to the open simplex of positive values that sum to 1, analogously to how the exponent takes 0 to 1, and is positive.
By contrast, softmax is not invariant under scaling. For instance, but
The standard logistic function is the special case for a 1-dimensional axis in 2-dimensional space, say the x-axis in the (x, y) plane. One variable is fixed at 0 (say ), so , and the other variable can vary, denote it , so the standard logistic function, and its complement (meaning they add up to 1). The 1-dimensional input could alternatively be expressed as the line , with outputs and
Gradients
[edit]The softmax function is also the gradient of the LogSumExp function:where the LogSumExp function is defined as .
The gradient of softmax is thus .
History
[edit]The softmax function was used in statistical mechanics as the Boltzmann distribution in the foundational paper Boltzmann (1868),[14] formalized and popularized in the influential textbook Gibbs (1902).[15]
The use of the softmax in decision theory is credited to R. Duncan Luce,[16]: 1 who used the axiom of independence of irrelevant alternatives in rational choice theory to deduce the softmax in Luce's choice axiom for relative preferences.[citation needed]
In machine learning, the term "softmax" is credited to John S. Bridle in two 1989 conference papers, Bridle (1990a):[16]: 1 and Bridle (1990b):[3]
We are concerned with feed-forward non-linear networks (multi-layer perceptrons, or MLPs) with multiple outputs. We wish to treat the outputs of the network as probabilities of alternatives (e.g. pattern classes), conditioned on the inputs. We look for appropriate output non-linearities and for appropriate criteria for adaptation of the parameters of the network (e.g. weights). We explain two modifications: probability scoring, which is an alternative to squared error minimisation, and a normalised exponential (softmax) multi-input generalisation of the logistic non-linearity.[17]: 227
For any input, the outputs must all be positive and they must sum to unity. ...
Given a set of unconstrained values, , we can ensure both conditions by using a Normalised Exponential transformation: This transformation can be considered a multi-input generalisation of the logistic, operating on the whole output layer. It preserves the rank order of its input values, and is a differentiable generalisation of the 'winner-take-all' operation of picking the maximum value. For this reason we like to refer to it as softmax.[18]: 213
Example
[edit]With an input of (1, 2, 3, 4, 1, 2, 3), the softmax is approximately (0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175). The output has most of its weight where the "4" was in the original input. This is what the function is normally used for: to highlight the largest values and suppress values which are significantly below the maximum value. But note: a change of temperature changes the output. When the temperature is multiplied by 10, the inputs are effectively (0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3) and the softmax is approximately (0.125, 0.138, 0.153, 0.169, 0.125, 0.138, 0.153). This shows that high temperatures de-emphasize the maximum value.
Computation of this example using Python code:
>>> import numpy as np
>>> z = np.array([1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0])
>>> beta = 1.0
>>> np.exp(beta * z) / np.sum(np.exp(beta * z))
array([0.02364054, 0.06426166, 0.1746813, 0.474833, 0.02364054,
0.06426166, 0.1746813])
Alternatives
[edit]The softmax function generates probability predictions densely distributed over its support. Other functions like sparsemax or α-entmax can be used when sparse probability predictions are desired.[19] Also the Gumbel-softmax reparametrization trick can be used when sampling from a discrete-discrete distribution needs to be mimicked in a differentiable manner.
See also
[edit]- Softplus
- Multinomial logistic regression
- Dirichlet distribution – an alternative way to sample categorical distributions
- Partition function
- Exponential tilting – a generalization of Softmax to more general probability distributions
Notes
[edit]- ^ Positive β corresponds to the maximum convention, and is usual in machine learning, corresponding to the highest score having highest probability. The negative −β corresponds to the minimum convention, and is conventional in thermodynamics, corresponding to the lowest energy state having the highest probability; this matches the convention in the Gibbs distribution, interpreting β as coldness.
- ^ The notation β is for the thermodynamic beta, which is inverse temperature: ,
- ^ For (coldness zero, infinite temperature), , and this becomes the constant function , corresponding to the discrete uniform distribution.
- ^ In statistical mechanics, fixing β is interpreted as having coldness and temperature of 1.
References
[edit]- ^ Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron (2016). "6.2.2.3 Softmax Units for Multinoulli Output Distributions". Deep Learning. MIT Press. pp. 180–184. ISBN 978-0-26203561-3.
- ^ a b Bishop, Christopher M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 0-387-31073-8.
- ^ a b Sako, Yusaku (2018-06-02). "Is the term "softmax" driving you nuts?". Medium.
- ^ Goodfellow, Bengio & Courville 2016, pp. 183–184: The name "softmax" can be somewhat confusing. The function is more closely related to the arg max function than the max function. The term "soft" derives from the fact that the softmax function is continuous and differentiable. The arg max function, with its result represented as a one-hot vector, is not continuous nor differentiable. The softmax function thus provides a "softened" version of the arg max. The corresponding soft version of the maximum function is . It would perhaps be better to call the softmax function "softargmax," but the current name is an entrenched convention.
- ^ LeCun, Yann; Chopra, Sumit; Hadsell, Raia; Ranzato, Marc’Aurelio; Huang, Fu Jie (2006). "A Tutorial on Energy-Based Learning" (PDF). In Gökhan Bakır; Thomas Hofmann; Bernhard Schölkopf; Alexander J. Smola; Ben Taskar; S.V.N Vishwanathan (eds.). Predicting Structured Data. Neural Information Processing series. MIT Press. ISBN 978-0-26202617-8.
- ^ "Unsupervised Feature Learning and Deep Learning Tutorial". ufldl.stanford.edu. Retrieved 2024-03-25.
- ^ ai-faq What is a softmax activation function?
- ^ Sutton, R. S. and Barto A. G. Reinforcement Learning: An Introduction. The MIT Press, Cambridge, MA, 1998. Softmax Action Selection
- ^ a b c d e f g Onal, Kezban Dilek; Zhang, Ye; Altingovde, Ismail Sengor; Rahman, Md Mustafizur; Karagoz, Pinar; Braylan, Alex; Dang, Brandon; Chang, Heng-Lu; Kim, Henna; McNamara, Quinten; Angert, Aaron (2018-06-01). "Neural information retrieval: at the end of the early years". Information Retrieval Journal. 21 (2): 111–182. doi:10.1007/s10791-017-9321-y. hdl:11245.1/008d6e8f-df13-4abf-8ae9-6ff2e17377f3. ISSN 1573-7659. S2CID 21684923.
- ^ a b c d e f Chen, Wenlin; Grangier, David; Auli, Michael (August 2016). "Strategies for Training Large Vocabulary Neural Language Models". Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). Berlin, Germany: Association for Computational Linguistics: 1975–1985. arXiv:1512.04906. doi:10.18653/v1/P16-1186. S2CID 6035643.
- ^ a b c Morin, Frederic; Bengio, Yoshua (2005-01-06). "Hierarchical Probabilistic Neural Network Language Model" (PDF). International Workshop on Artificial Intelligence and Statistics. PMLR: 246–252.
- ^ Milakov, Maxim; Gimelshein, Natalia (2018). "Online normalizer calculation for softmax". arXiv:1805.02867 [cs.PF].
- ^ Dao, Tri; Fu, Dan; Ermon, Stefano; Rudra, Atri; Ré, Christopher (2022-12-06). "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness". Advances in Neural Information Processing Systems. 35: 16344–16359.
- ^ Boltzmann, Ludwig (1868). "Studien über das Gleichgewicht der lebendigen Kraft zwischen bewegten materiellen Punkten" [Studies on the balance of living force between moving material points]. Wiener Berichte. 58: 517–560.
- ^ Gibbs, Josiah Willard (1902). "Elementary Principles in Statistical Mechanics". Nature. 66 (1708): 291. Bibcode:1902Natur..66..291B. doi:10.1038/066291a0.
- ^ a b Gao, Bolin; Pavel, Lacra (2017). "On the Properties of the Softmax Function with Application in Game Theory and Reinforcement Learning". arXiv:1704.00805 [math.OC].
- ^ Bridle, John S. (1990a). Soulié F.F.; Hérault J. (eds.). Probabilistic Interpretation of Feedforward Classification Network Outputs, with Relationships to Statistical Pattern Recognition. Neurocomputing: Algorithms, Architectures and Applications (1989). NATO ASI Series (Series F: Computer and Systems Sciences). Vol. 68. Berlin, Heidelberg: Springer. pp. 227–236. doi:10.1007/978-3-642-76153-9_28.
- ^ Bridle, John S. (1990b). D. S. Touretzky (ed.). Training Stochastic Model Recognition Algorithms as Networks can Lead to Maximum Mutual Information Estimation of Parameters. Advances in Neural Information Processing Systems 2 (1989). Morgan-Kaufmann.
- ^ "Speeding Up Entmax" by Maxat Tezekbayev, Vassilina Nikoulina, Matthias Gallé, Zhenisbek Assylbekov, https://arxiv.org/abs/2111.06832v3
Softmax function
View on GrokipediaDefinition
Mathematical Definition
The softmax function, first termed and applied in the context of probabilistic interpretation of neural network outputs by Bridle (1989), is mathematically defined for a finite-dimensional input vector (with ) as the output vector whose -th component is given by [4][5] The exponential function plays a crucial role in this formulation by mapping each real-valued input to a strictly positive value , thereby ensuring all components of the output vector are positive before normalization.[5][6] In machine learning literature, the input vector is conventionally denoted as to represent the pre-activation logits (unbounded real values produced by a linear layer), while typically denotes the original feature inputs to the model; this distinction highlights the softmax's role as an output activation applied to logits.[6] For the scalar case where , the definition simplifies trivially to , yielding a constant output.[5] When , the softmax reduces to the binary logistic (sigmoid) function up to a shift, as , analogous to the standard sigmoid applied to the logit difference.[6][5]Basic Interpretations
The softmax function serves as a normalized exponential transformation that converts a vector of unbounded real-valued inputs, often called logits or scores, into a discrete probability distribution over multiple categories. By applying the exponential function to each input and dividing by the sum of exponentials across all inputs, it ensures that the outputs are strictly positive and sum to exactly one, thereby mapping the inputs onto the probability simplex. This normalization aspect makes the softmax particularly useful for interpreting raw model outputs as probabilities in multi-class settings, where the relative magnitudes of the inputs determine the likelihood assigned to each class.[7][3] The outputs of the softmax function directly parameterize the probability mass function of a categorical distribution, where each component represents the probability of a specific category in a multinomial setting. This connection arises because the softmax enforces the constraints of a valid probability distribution—non-negativity and normalization—allowing it to model the probabilities of mutually exclusive and exhaustive outcomes. In statistical terms, if the inputs are the natural logarithms of the unnormalized probabilities, the softmax recovers the normalized form, aligning with the parameterization used in multinomial logistic regression models.[3] The use of exponentials in the softmax provides an intuitive amplification of differences among the input values, transforming subtle variations in scores into more pronounced probabilistic preferences. For instance, a larger input value leads to exponentially higher output probability compared to smaller ones, which promotes decisive distributions where the highest-scoring category receives the majority of the probability mass, while still allowing for some uncertainty in closer cases. This non-linear scaling ensures that the function is sensitive to relative differences rather than absolute values, enhancing its effectiveness in representing confidence levels across categories.[3] A generalized variant of the softmax introduces a temperature parameter to modulate the sharpness of the resulting distribution, defined as When , it recovers the standard softmax; lower values of sharpen the distribution toward the maximum input (approaching a Dirac delta), while higher values flatten it toward uniformity, providing flexibility in controlling the trade-off between confidence and entropy in probabilistic outputs.[3]Advanced Interpretations
Smooth Approximation to Argmax
The argmax operation, denoted as , selects the index corresponding to the maximum value in a vector , producing a one-hot encoded vector where the entry at the maximum position is 1 and all others are 0.[8] However, this operation is non-differentiable almost everywhere, which poses challenges for gradient-based optimization in machine learning, as it cannot be directly incorporated into differentiable computational graphs.[8] The softmax function addresses this limitation by serving as a smooth, differentiable approximation to argmax, often referred to as "softargmax."[8] Defined with a temperature parameter , the softmax maps the input vector to a probability distribution over the categories, where the probabilities concentrate more sharply on the largest entries as decreases.[8] In the limit of vanishing temperature, the softmax output converges pointwise to the one-hot vector aligned with the argmax: if (assuming no ties in ), and 0 otherwise.[8] This smoothing property enables the use of gradient-based methods to approximate discrete decision-making processes that would otherwise rely on non-differentiable argmax operations.[8] For instance, in techniques like straight-through estimators, the forward pass may employ a hard argmax for discrete selection, while the backward pass approximates gradients through a low-temperature softmax to propagate signals effectively during training.[9]Relation to Boltzmann Distribution
In statistical mechanics, the Boltzmann distribution describes the probability of a system occupying a particular state with energy at thermal equilibrium temperature , given by where is Boltzmann's constant and the sum in the denominator runs over all possible states .[10] This distribution was first formulated by Ludwig Boltzmann in 1868 as part of his foundational work on the statistical mechanics of gases, deriving the equilibrium probabilities through combinatorial arguments for particle distributions.[11][12] The softmax function bears a direct mathematical resemblance to the Boltzmann distribution, arising from the mapping , which transforms the energies into logits scaled by the inverse temperature ; thus, softmax outputs precisely model the equilibrium probabilities in the canonical ensemble of statistical mechanics.[2] Consequently, the softmax inherits key concepts from the Boltzmann framework, including the partition function (the normalizing denominator ) that ensures probabilities sum to unity, and the interpretation of inputs as energy-based scores for probabilistic state selection.[10]Properties
Key Mathematical Properties
The softmax function , defined componentwise as , exhibits several fundamental mathematical properties that ensure it maps inputs to the interior of the probability simplex.[3] A primary property is normalization, whereby the outputs sum to unity: for all . This follows directly from the definitional structure, as the exponential terms in the numerator and denominator cancel out in the summation. Complementing this is non-negativity, with for all and , since exponentials are strictly positive and the denominator is a positive sum. These traits position softmax outputs as valid probability distributions over categories.[8][3] The function is also strictly monotonic in each component: if , then . This order-preserving behavior arises because increasing relative to amplifies the corresponding exponential term more than others, without altering the total sum due to normalization. Additionally, softmax is invariant to translation by a constant vector: for any , where is the all-ones vector. This holds because adding to each input multiplies both numerator and denominator by , which cancels out.[8][3] Finally, the softmax function is unique as the mapping from to the interior of the simplex that satisfies normalization, non-negativity, monotonicity, and translation invariance. This uniqueness stems from its characterization as the maximum-entropy distribution subject to moment constraints on the expected inputs, derived via Lagrange multipliers. To see this, maximize the entropy over with and (for fixed mean ). The Lagrangian is . Setting partial derivatives to zero yields , so . Applying the normalization constraint normalizes the exponentials, recovering the softmax form; strict convexity of the negative entropy ensures this solution is unique.[3]Gradient Computations
The gradients of the softmax function play a central role in backpropagation algorithms for training neural networks, enabling the efficient computation of how perturbations in the input logits propagate to changes in the output probabilities , where denotes the -dimensional probability simplex.[13] Consider the component-wise definition , where . To derive the partial derivatives, apply the quotient rule and chain rule. For , since . For the case , as the numerator derivative includes both the direct term from and the indirect term through . Combining these yields the general component-wise form of the Jacobian entries: where is the Kronecker delta ( if , else 0).[14] In matrix notation, the full Jacobian is which is symmetric and positive semidefinite with rank at most .[15][13] This structure admits a clear interpretation: the diagonal elements capture self-reinforcement, where an increase in boosts proportionally to its current value, while the off-diagonal elements (for ) encode inter-class competition, as an increase in diminishes to maintain the normalization .[15] Consequently, each row (and column) of sums to zero, preserving the simplex constraint under infinitesimal changes.[13] In practice, forming the explicit Jacobian requires space and time, which is prohibitive for large . However, during backpropagation, only the Jacobian-vector product is typically needed for a downstream gradient vector , and this can be evaluated in time via avoiding materialization of the full matrix and enabling scalable computation in deep learning frameworks.[14]Numerical Considerations
Complexity and Challenges
The computation of the softmax function for an input vector involves exponentiating each of the elements, computing their sum, and performing element-wise division for normalization, yielding a time complexity of . This linear dependence on the dimension poses challenges in high-dimensional settings, such as natural language processing where corresponds to vocabulary sizes often exceeding 50,000, leading to substantial per-instance costs during inference and training. The space complexity is likewise , required for storing the input vector, intermediate exponentials, and output probabilities, though computing in log-space via the log-sum-exp trick can avoid temporary storage of large exponential values, modestly reducing peak memory usage. A primary numerical challenge stems from the exponential operation in the softmax formula, , which is susceptible to overflow when any is large and positive, causing to approach infinity and rendering the denominator undefined. Conversely, when all are large and negative, underflow occurs as rounds to zero for all terms, resulting in loss of precision and a denominator near zero. These instabilities can propagate to produce NaN values in the probabilities or degenerate distributions where one probability approaches 1 and others 0, thereby distorting gradients during backpropagation as outlined in the gradient computations section.Stable Numerical Methods
Computing the softmax function directly can lead to numerical overflow when input values are large, as the exponential terms grow rapidly. A standard technique to mitigate this is the subtract-max trick, which shifts all inputs by their maximum value before exponentiation. This ensures that all exponents are less than or equal to zero, bounding the terms and preventing overflow while preserving the original probabilities. The adjusted computation is given by where . This method is equivalent to the standard softmax because the shift factor cancels out in the ratio.[16] For applications requiring the logarithm of softmax probabilities, such as in cross-entropy loss computations, the log-sum-exp (LSE) trick provides numerical stability. The log-softmax for each component is Direct evaluation of the sum can still cause underflow for large negative inputs, so a stabilized LSE incorporates the subtract-max: , where . This formulation avoids both overflow in the exponentials and underflow in the summation, enabling accurate computation even for extreme input ranges. Stable implementations of logsumexp are essential in probabilistic modeling and optimization.[17] In high-dimensional settings, such as attention mechanisms in transformers where the vocabulary size or sequence length is very large (e.g., thousands), full softmax computation becomes computationally prohibitive due to or quadratic scaling. To address this, approximations like sparsemax replace the dense softmax with a sparse variant that thresholds small probabilities to zero, producing a sparse probability distribution while maintaining differentiability. Sparsemax is particularly useful in multi-label classification and attention, as it focuses computation on the most relevant elements. Additionally, sampling-based methods, such as those in sparse transformers, approximate the softmax by evaluating only a subset of keys or using low-rank approximations, reducing memory and time complexity to near-linear in sequence length. These techniques preserve much of the expressive power of full softmax for large-scale applications. Major numerical libraries incorporate these stability measures into their softmax implementations. For instance, SciPy'sscipy.special.softmax applies the subtract-max trick internally to handle a wide range of input scales reliably. Similarly, PyTorch's torch.nn.functional.softmax uses dimension-specific stable computation, subtracting the maximum along the specified axis to ensure robustness in deep learning workflows. These built-in functions allow practitioners to compute softmax without manual intervention for stability.[18]
Applications
In Neural Networks
In neural networks, the softmax function serves as a key activation in the output layer for multi-class classification tasks, transforming a vector of raw scores, or logits, into a probability distribution over multiple classes that sums to one. This normalization enables the network to produce interpretable outputs representing the likelihood of each class, facilitating decision-making in applications such as image recognition and natural language processing.[7] The softmax output is typically paired with the cross-entropy loss during training, which measures the divergence between the predicted probability distribution and the true one-hot encoded target . The loss is defined as , where is the number of classes, and this combination yields computationally efficient gradients for backpropagation, specifically for the -th logit. This simplification arises because the derivatives of the softmax and the negative log-likelihood cancel in a manner that avoids explicit Jacobian computations, accelerating optimization in multi-class settings. The adoption of softmax in neural networks gained prominence in the late 1980s and 1990s, as researchers sought probabilistic interpretations for feedforward classifiers amid the resurgence of connectionist models. John Bridle's work introduced the term "softmax" and advocated its use for modeling conditional probabilities in classification networks, bridging statistical pattern recognition with neural architectures. This era's emphasis on probabilistic outputs helped establish softmax as a standard for supervised learning paradigms.[7] A notable variant involves scaling the logits by a temperature parameter before applying softmax, yielding , which controls the distribution's sharpness. When , the output softens, distributing probability more evenly across classes to aid in model calibration or knowledge distillation from larger teacher networks to smaller students. In distillation, the softened teacher probabilities guide the student via a distillation loss, improving generalization while compressing model size, as demonstrated in seminal work on transferring knowledge across neural networks. For calibration, post-hoc temperature scaling adjusts overconfident predictions in trained models, enhancing reliability without retraining.In Reinforcement Learning
In reinforcement learning, the softmax function plays a central role in parameterizing stochastic policies for discrete action spaces, enabling agents to select actions probabilistically based on estimated action values. Specifically, the policy is defined as , where denotes the action-value function for state and action , and is a temperature parameter that scales the logits before applying the softmax.[19] This formulation ensures that the policy outputs a valid probability distribution over actions, with higher -values receiving proportionally greater probability mass.[19] The temperature parameter governs the balance between exploration and exploitation in the policy. A high flattens the distribution, promoting exploration by assigning more uniform probabilities to actions and encouraging the agent to try suboptimal options to discover better long-term rewards. Conversely, a low sharpens the distribution toward the action with the maximum -value, favoring exploitation to maximize immediate expected returns. This adjustability allows softmax policies to adapt dynamically during training, often starting with higher for broad search and annealing to lower values for refinement.[19] Softmax policies are integral to several policy gradient algorithms, particularly actor-critic methods for discrete actions. In REINFORCE, a foundational Monte Carlo policy gradient algorithm, the softmax parameterization facilitates direct optimization of the policy parameters via stochastic gradient ascent on the expected return, using complete episode trajectories to estimate gradients.[20] Similarly, in Proximal Policy Optimization (PPO), a widely adopted on-policy method, the policy network outputs logits that are passed through softmax to yield action probabilities, enabling clipped surrogate objectives for stable updates over multiple epochs while handling discrete environments like Atari games.[21] The primary advantages of softmax parameterization in these algorithms stem from its differentiability, which permits efficient gradient-based optimization of the expected reward without requiring value function approximations for policy updates. This smoothness supports convergence guarantees under certain conditions and allows seamless integration with neural network actors, making it suitable for high-dimensional state spaces.[19]In Modern Architectures
In modern architectures, the softmax function plays a pivotal role in the self-attention mechanisms of transformer models, where it normalizes the similarities between query and key vectors to produce attention weights. Specifically, in scaled dot-product attention, the attention weights are computed as , where denotes the softmax operation, and are the query and key vectors, and is the dimensionality of the keys; this scaling by mitigates the vanishing gradients that would otherwise arise from high-dimensional dot products before softmax normalization.[22] This formulation enables the model to weigh and aggregate input representations dynamically, allowing transformers to capture long-range dependencies in sequences without relying on recurrent structures. The transformer architecture, which relies on this softmax-based attention as its core component, was introduced in the seminal work demonstrating its superiority over recurrent and convolutional models for machine translation tasks.[22] Despite its effectiveness, the quadratic complexity of softmax attention with respect to sequence length —stemming from the need to compute pairwise similarities—poses significant challenges for processing long sequences, leading to high memory and computational demands in large-scale models. To address this, researchers have developed efficient variants such as sparse attention, which factorizes the attention matrix to focus on a subset of connections, reducing complexity to or better while preserving expressive power for tasks like sequence generation.[23] Similarly, linear attention approximations replace the softmax with kernel-based formulations that enable associative rearrangements, achieving complexity and enabling faster autoregressive prediction on very long sequences without substantial performance degradation.[24] These innovations have been crucial for scaling transformers to handle inputs exceeding thousands of tokens, where traditional softmax attention becomes prohibitive. The integration of softmax attention has been central to the success of influential models like GPT and BERT, which have revolutionized natural language processing by leveraging transformer architectures for pre-training on vast corpora and fine-tuning across diverse tasks. For instance, GPT employs decoder-only transformers with softmax-normalized attention to generate coherent text autoregressively, achieving state-of-the-art results in unsupervised language modeling.[25] BERT, using encoder-only transformers, applies bidirectional softmax attention to learn contextual embeddings, markedly improving performance on benchmarks like GLUE and SQuAD.[26] As of 2025, softmax-based attention remains foundational in these and subsequent architectures, underpinning advancements in multimodal and long-context models while inspiring ongoing optimizations for efficiency and scalability.[22]Historical Context
Early Foundations
The foundational ideas underlying the softmax function emerged in the realm of statistical mechanics in the 19th century. In 1868, Ludwig Boltzmann developed a probabilistic framework for describing the distribution of energy among particles in a gas at thermal equilibrium. In his seminal paper "Studien über das Gleichgewicht der lebendigen Kraft zwischen bewegten materiellen Punkten," Boltzmann established that the relative probability of a particle occupying a state with energy is proportional to , where is Boltzmann's constant and is the absolute temperature; this exponential form arises from maximizing entropy under energy constraints, providing the first rigorous basis for normalized exponential probabilities in physical systems.[27] This distribution, now known as the Boltzmann distribution, laid the groundwork for later probabilistic normalizations by linking microscopic energy states to macroscopic equilibrium behaviors in gases and other systems.[28] By the mid-20th century, the exponential normalization concept transitioned into statistics, particularly through the evolution of logistic regression models. During the 1950s and 1960s, statisticians generalized the binary logit model—initially used for dichotomous outcomes—to handle multinomial cases with multiple categories. David Cox's 1958 paper "The Regression Analysis of Binary Sequences" introduced binary logistic regression, where the log-odds are linear in covariates.[29] Extensions to multinomial models followed in the 1960s, including work by Cox in 1966, proposing formulations where the log-odds of category probabilities are linear in covariates, resulting in probabilities given by normalized exponentials: for categories , the probability is .[30] This formulation allowed for the analysis of categorical data in fields like bioassay and social sciences, building on earlier probit models but favoring the logit for its mathematical tractability and interpretability. The approach gained traction as a tool for regression with discrete responses, emphasizing the normalization step to ensure probabilities sum to one. These statistical developments found early applications in econometrics and behavioral choice modeling, where the normalized exponential form proved useful for predicting selections among discrete alternatives. A key contribution came from R. Duncan Luce's 1959 work "Individual Choice Behavior: A Theoretical Analysis," which introduced the choice axiom stating that the probability of selecting an alternative is proportional to its inherent "scale value," independent of irrelevant options; this leads to choice probabilities of the form , where represents the strength of alternative in choice set .[31] Luce's model, often implemented with exponential scale values for positive homogeneity, was applied to empirical data in psychology and economics to model decision processes, such as consumer preferences or perceptual judgments, and influenced subsequent work in discrete choice theory.[32] In these contexts, the function was typically termed the "multinomial logit" or referred to simply as exponential normalization, without the designation "softmax," which emerged later in machine learning literature.Development in AI
The softmax function emerged as a key component in artificial intelligence during the late 1980s, building on earlier probabilistic interpretations to enable normalized outputs in neural networks for classification tasks. Although the mathematical form predates AI applications, its explicit adoption in machine learning contexts began with precursors in multi-layer perceptrons, where similar exponential normalizations were implied for producing probability distributions over multiple classes. For instance, the influential 1986 work by Rumelhart, Hinton, and Williams on backpropagation through networks implicitly relied on such normalizations to handle multi-class problems in supervised learning, marking an early integration into neural network architectures despite the term not yet being coined. The term "softmax" was formally introduced by John S. Bridle in his 1989 paper presented at the Neural Information Processing Systems conference, where he described it as a "normalized exponential" or "softmax" output stage for stochastic model recognition algorithms trained as networks. Bridle emphasized its role in maximizing mutual information between inputs and probabilistic outputs, positioning it as a natural extension of the logistic function for multi-class scenarios in probabilistic neural networks. This coinage solidified softmax as a standard activation for generating interpretable probability distributions at the output layer of feedforward networks, facilitating applications in pattern recognition and speech processing during the resurgence of connectionist approaches in the early 1990s. Softmax gained widespread prominence during the deep learning renaissance post-2010, becoming integral to convolutional neural networks and subsequent architectures. Its pivotal role was highlighted in the 2012 AlexNet model by Krizhevsky, Sutskever, and Hinton, which employed softmax in the final layer to classify ImageNet images into 1000 categories, contributing to a breakthrough error rate reduction that catalyzed the adoption of deep networks in computer vision. By 2017, softmax was embedded in the transformer architecture introduced by Vaswani et al., where it normalizes attention scores to weigh token importance in sequence modeling, underpinning advancements in natural language processing and enabling scalable training of models like BERT and GPT series. As of 2025, while the core softmax formulation remains unchanged, ongoing research focuses on scalable and hardware-efficient variants to address computational bottlenecks in large language models with billions of parameters. Innovations include approximate softmax implementations that reduce division operations and memory access, as explored in hardware-oriented algorithms for transformer-based LLMs, ensuring compatibility with edge devices and massive-scale training without altering the function's probabilistic essence. Recent 2025 developments feature variants like adaptive sparse softmax for efficient sampling in high-dimensional spaces and self-adjust softmax for dynamic normalization in long-sequence models.[33][34] These developments reflect softmax's enduring centrality in AI, adapting to efficiency demands rather than fundamental redesign.[35]Practical Aspects
Examples
To illustrate the softmax function, consider a vector of input logits . The softmax output is computed as , yielding probabilities approximately , which sum to 1 and emphasize the largest input value.[7] For numerical stability, especially to avoid overflow in exponential computations, the subtract-max trick shifts the inputs by their maximum value: let , so the adjusted vector is . The exponentials are then , , and , with their sum approximately 1.518. Dividing each exponential by this sum gives the same output . This stable approach is commonly implemented in programming languages. In Python using NumPy, the function can be defined as:import numpy as np
def softmax(z):
return np.exp(z - np.max(z)) / np.sum(np.exp(z - np.max(z)))
# Test on the example
z = np.array([2, 1, 0.1])
print(softmax(z)) # Output: [0.65900114 0.24243295 0.09856591]
import numpy as np
def softmax(z):
return np.exp(z - np.max(z)) / np.sum(np.exp(z - np.max(z)))
# Test on the example
z = np.array([2, 1, 0.1])
print(softmax(z)) # Output: [0.65900114 0.24243295 0.09856591]
