The Hierarchical Softmax

Table of contents
  1. Hierarchical Softmax
  2. Further Reading
  3. References and Notes
  4. Edit Log

The Hierarchical Softmax is useful for efficient classification as it has logarithmic time complexity in the number of output classes, log(N)log(N) for NN output classes. This utility is pronounced in the context of language modelling where words must be predicted over time steps to generate a sentence, for example, by a decoder that selects them from a vocabulary which could be in the order of ∣V∣=30,000\vert \mathbf{V} \vert = 30,000.

Small additions or modifications to the end of the article will be made when time allows in order to include remarks on use of Huffman coding with the Hierarchical Softmax and to draw links between the concepts introduced here and, for example, Noise Contrastive Estimation (NCE). This was was written on 29th March 2021, though published later.

The softmax classifier, which generalises logistic regression from a binary, {0∣1}\{0 \vert 1\}, model output to any arbitrary number of output classes, is computed by passing the so-called logit scores through the softmax function.

Given a vector of logit scores, z\mathbf{z}, the elements are exponentiated in the numerator to make them strictly positive and divided by the sum of this exponentiation over all elements to normalise the output vector to 11, rendering it a valid probability distribution.

σ(z)i=ezi∑j=1Kezj for i=1,…,K and z=(z1,…,zK)T∈RK\sigma(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}} \text{ for } i = 1, \dotsc , K \text{ and } \mathbf z=(z_1,\dotsc,z_K)^T \in\mathbb{R}^K

The softmax should arguably be called the softargmax as it computes a smooth approximation to the arg max⁡\argmax function, not the max⁡\max. The smooth property makes the function differentiable and therefore useful in neural networks as training can be done via reverse-mode automatic differentiation, specifically backpropagation [1].


Remark on Energy and the Boltzmann Distribution

It is interesting to note that the softmax is identical to the Boltzmann distribution where ziz_i corresponds to −ϵi/kT-\epsilon_i / kT and ϵi\epsilon_i is a state’s energy. The distribution is defined

pi=1Q⋅e−ϵi/kT=e−ϵi/kT∑j=1Me−ϵj/kTp_i = \frac{1}{Q} \cdot e^{-\epsilon_i/kT} = \frac{e^{- {\epsilon}_i / kT}}{\sum_{j=1}^{M} e^{- {\epsilon}_j / k T}}

Here kk is the Boltzmann constant, a physical constant relating the average relative kinetic energy of particles in a gas with the thermodynamic temperature of that gas that is largely specific to statistical mechanics. However, TT, which represents the thermodynamic temperature, is a commonly tweaked hyperparameter used in machine learning applications as it controls the entropy of the output distribution. Higher temperatures increase the entropy, distributing probability mass over more classes such that the softmax becomes the arg max⁡\argmax in the limit as temperature goes to zero: σT(z)→arg max⁡z{\sigma}_T(\mathbf{z}) \rightarrow \argmax \mathbf{z} for T→0T \rightarrow 0.

The fact that energy can be related to probabilities via the Boltzmann distribution is worth remembering in the context of Energy-Based Models (EBMs) [2].


Classification problems occur in language when models must generate probability distributions over a vocabulary of words, for example to predict the next word in language modelling. Typical vocabulary sizes could be around 30,00030,000.

When constructing language models, we might employ recurrent neural networks11 See Chris Olah’s fantastic blog post, Understanding LSTM Networks [13], for an explanation of long short-term memory networks, the most widely-used variant of RNNs, which uses gating to overcome the vanishing gradient problem. (RNNs) or transformer-based architectures22 Read the seminal Vaswani et al. (2017) Attention is All You Need [14] for full details, Jay Alammar’s The Illustrated Transformer [15] for a readable explanation or The Annotated Transformer [16] for details on implementation. . In this case, the logit scores would be computed using a similarity score between the final layer output, hh, and the each of the word embeddings, vwiv_{w_i}.


Remark on Similarity Scores

A common choice for similarity is the dot product, h⋅vwih \cdot v_{w_i}, which is equivalent to the cosine similarity for normalised vectors (i.e. of unit norm: ∥x∥2=1\Vert x \Vert_2 = 1). Other choices exist like the scaled dot product, (h⋅vwi)/d(h \cdot v_{w_i}) / d where dd is a scalar33 In their seminal paper on Transformers, Ashish Vaswani and colleagues used scaled dot-product attention with dk\sqrt{d_k}, where dkd_k is the feature size of the keys, to prevent the dot products from growing in magnitude thus pushing the softmax values to regions where the gradients are small and learning via backpropagation is difficult. See section 3.2.1 in Vaswani et al. (2017) Attention is All You Need [14]. , the general dot product h⋅W⋅vwih \cdot W \cdot v_{w_i}, with WW a matrix that permits differing dimensionality of hh and vwiv_{w_i} and others44 See Pascale Poupart’s lecture [17] for a nice explanation. .


For the very large numbers of output classes encountered in language modelling, the softmax becomes very computationally expensive as, in order to compute the probability of any single word being the next word in a sequence, we have to compute the denominator. The denominator is linear in the feature dimensionality as it is in effect the sum of elements after a matrix-vector multiplication between the word embedding matrix and the final layer output, V⋅h\mathbf{V} \cdot h. It is linear in the vocabulary size, VV.

Hierarchical Softmax

Frederic Morin and Yoshua Bengio (2005) [3] proposed the hierarchical softmax classifier, an approximation to the softmax which is logarithmic-time in the vocabulary size, O(log∣V∣)\mathcal{O}(log \vert V \vert) in place of O(∣V∣)\mathcal{O}(\vert V \vert), yielding an exponential speed-up by a factor of O(∣V∣log∣V∣)\mathcal{O}(\frac{\vert V \vert}{log\vert V \vert}).

The basic idea is to form a hierarchical description of a word as a sequence of O(log∣V∣)\mathcal{O}(log \vert V \vert) decisions, and to learn to take these probabilistic decisions instead of directly predicting each word’s probability. [3]

They extend the idea of Goodman [4] to define a clustering partition, KK, of words in the vocabulary and calculate the conditional probability of a word given its context via the chain rule. In other words, for word ww and context cc, with k(.)k(.) a mapping from words to clusters, instead of directly computing P(W=w∣C=c)P(W = w \vert C = c), instead decompose this as

P(W=w∣C=c)=P(W=w∣K=k(w),C=c)⋅P(K=k(w)∣C=c)P(W = w \vert C = c) = P(W = w \vert K = k(w), C = c) \cdot P(K=k(w) \vert C = c)

They also note that generalization could be better for choices of word clusters that “make sense”, i.e. those for which it easier to learn the second term, P(K=k(w)∣C=c)P(K=k(w) \vert C = c). We’ll see momentarily how clusters making sense is analogous to the notion of order in lists which we can search with binary search.

They follow this up with a concrete example55 I have tweaked the quote slightly to align it with the notation I introduced.

If WW can take 10,00010,000 values and we have 100100 classes [clusters] with 100100 words ww in each class, then instead of doing normalization over 10,00010,000 choices we only need to do two normalizations, each over 100100 choices. [3]

Performing a one-level decomposition provides at most a VV=V\frac{V}{\sqrt{V}} = \sqrt{V} speed-up when we create V\sqrt{V} clusters and so a hierarchical decomposition with log2(V)log_2(V) levels provides a Vlog2(V)\frac{V}{log_2(V)} exponential speed-up. Such a decomposition is represented as a balanced66 A tree is balanced if the following is true when applied recursively to subtrees: (1) The left and right subtrees’ heights differ by at most one, AND (2) The left subtree is balanced, AND (3) The right subtree is balanced. See https://stackoverflow.com/questions/8015630/definition-of-a-balanced-tree. binary tree.

Another important idea of this paper is to reuse the same model (i.e. the same parameters) for all those decisions (otherwise a very large number of models would be required and the whole model would not fit in computer memory), using a special symbolic input that characterizes the nodes in the tree of the hierarchical decomposition. [3]

Finally, we use prior knowledge in the WordNet lexical reference system to help define the hierarchy of word classes. [3]

Analogy to binary search in an ordered list. “We’ll see momentarily how clusters making sense is analogous to the notion of order in lists which we can search with binary search. ”

Tomas Mikolov and colleagues encountered this problem when using neural networks to compute word embeddings [5]. They used the pretext task77 Pretext tasks are dummy tasks whose predictions are not important in themselves but rather guide a model to learn useful feature representations. This is now commonly discussed in the context of self-supervised learning. See Ishan Misra’s Self-Supervised Learning - Pretext Tasks [18] from Deep Learning DS-GA 1008 · Spring 2020 · NYU Center for Data Science taught by Yann LeCun & Alfredo Canziani. of either predicting a word in a window given its context, the Continuous Bag of Words model (CBOW), or predicting the context words given an input word, the Skip-gram model.

Graphical representation of the CBOW model and Skip-gram models

Graphical representation of the CBOW model and Skip-gram model. In the CBOW model, the distributed representations of context (or surrounding words) are combined to predict the word in the middle. In the Skip-gram model, the distributed representation of the input word is used to predict the context. Image source: Exploiting Similarities among Languages for Machine Translation [6].

Further Reading

References and Notes

[1]
Atilim Gunes Baydin, Barak A. Pearlmutter, Alexey Andreyevich Radul, and Jeffrey Mark Siskind. 2018. Automatic differentiation in machine learning: a survey. Journal of Machine Learning Research, 18(153), 1–43. arXiv:1502.05767
[2]
Yann LeCun and Alfredo Canziani. 2020. Week 7, Lecture 1: Energy-Based Models. Lecture notes, DS-GA 1008: Deep Learning, NYU Center for Data Science. https://atcold.github.io/pytorch-Deep-Learning/en/week07/07-1/
[3]
Frederic Morin and Yoshua Bengio. 2005. Hierarchical Probabilistic Neural Network Language Model. In Proceedings of the Tenth International Workshop on Artificial Intelligence and Statistics, vol. R5, 246–252, PMLR. https://proceedings.mlr.press/r5/morin05a.html
[4]
J. Goodman. 2001. Classes for fast maximum entropy training. In 2001 IEEE International Conference on Acoustics, Speech, and Signal Processing. Proceedings (Cat. No.01CH37221), vol. 1, 561–564. https://doi.org/10.1109/ICASSP.2001.940893
[5]
Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean. 2013. Efficient Estimation of Word Representations in Vector Space. Workshop at the International Conference on Learning Representations (ICLR). arXiv:1301.3781
[6]
Tomas Mikolov, Quoc V. Le, and Ilya Sutskever. 2013. Exploiting Similarities among Languages for Machine Translation. arXiv preprint arXiv:1309.4168. arXiv:1309.4168
[7]
Sebastian Ruder. 2016. On Word Embeddings - Part 2: Approximating the Softmax. Blog post. https://ruder.io/word-embeddings-softmax/index.html
[8]
Sebastian Ruder. 2016. On Word Embeddings - Part 1. Blog post. https://ruder.io/word-embeddings-1/
[9]
Sebastian Ruder. 2016. On Word Embeddings - Part 3: The Secret Ingredients of Word2Vec. Blog post. https://ruder.io/secret-word2vec/
[10]
Lei Mao. 2019. Hierarchical Softmax. Blog post. https://leimao.github.io/article/Hierarchical-Softmax/
[11]
Lei Mao. 2019. Noise Contrastive Estimation. Blog post. https://leimao.github.io/article/Noise-Contrastive-Estimation/
[12]
Lei Mao. 2019. Entropy, Perplexity and Its Applications. Blog post. https://leimao.github.io/blog/Entropy-Perplexity/
[13]
Christopher Olah. 2015. Understanding LSTM Networks. Blog post. https://colah.github.io/posts/2015-08-Understanding-LSTMs/
[14]
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention Is All You Need. In Advances in Neural Information Processing Systems, vol. 30, 5998–6008. arXiv:1706.03762
[15]
Jay Alammar. 2018. The Illustrated Transformer. Blog post. http://jalammar.github.io/illustrated-transformer/
[16]
Alexander M. Rush. 2018. The Annotated Transformer. Blog post, Harvard NLP. https://nlp.seas.harvard.edu/2018/04/03/attention.html
[17]
Pascal Poupart. 2019. CS480/680 Lecture 19: Attention and Transformer Networks. YouTube video. https://youtu.be/OyFJWRnt_AY?t=1110
[18]
Ishan Misra. 2020. Self-Supervised Learning - Pretext Tasks. Lecture notes, DS-GA 1008: Deep Learning (Yann LeCun and Alfredo Canziani), NYU Center for Data Science. https://atcold.github.io/pytorch-Deep-Learning/en/week10/10-1/

Edit Log

  • 14 October 2026: corrected the Boltzmann correspondence (zi=−ϵi/kTz_i = -\epsilon_i / kT), the cost of the softmax denominator (linear, not quadratic, in the feature dimension), the statement of the speed-up, the cluster index k(w)k(w) and the attention scaling (dk\sqrt{d_k}); temperature controls the entropy, not the variance, of the output distribution.

Footnotes

  1. See Chris Olah’s fantastic blog post, Understanding LSTM Networks [13], for an explanation of long short-term memory networks, the most widely-used variant of RNNs, which uses gating to overcome the vanishing gradient problem. ↩

  2. Read the seminal Vaswani et al. (2017) Attention is All You Need [14] for full details, Jay Alammar’s The Illustrated Transformer [15] for a readable explanation or The Annotated Transformer [16] for details on implementation. ↩

  3. In their seminal paper on Transformers, Ashish Vaswani and colleagues used scaled dot-product attention with dk\sqrt{d_k}, where dkd_k is the feature size of the keys, to prevent the dot products from growing in magnitude thus pushing the softmax values to regions where the gradients are small and learning via backpropagation is difficult. See section 3.2.1 in Vaswani et al. (2017) Attention is All You Need [14]. ↩

  4. See Pascale Poupart’s lecture [17] for a nice explanation. ↩

  5. I have tweaked the quote slightly to align it with the notation I introduced. ↩

  6. A tree is balanced if the following is true when applied recursively to subtrees: (1) The left and right subtrees’ heights differ by at most one, AND (2) The left subtree is balanced, AND (3) The right subtree is balanced. See https://stackoverflow.com/questions/8015630/definition-of-a-balanced-tree. ↩

  7. Pretext tasks are dummy tasks whose predictions are not important in themselves but rather guide a model to learn useful feature representations. This is now commonly discussed in the context of self-supervised learning. See Ishan Misra’s Self-Supervised Learning - Pretext Tasks [18] from Deep Learning DS-GA 1008 · Spring 2020 · NYU Center for Data Science taught by Yann LeCun & Alfredo Canziani. ↩