Search

Search papers and lessons

Hierarchical Softmax

Level 3 · 10 min read

Hierarchical softmax replaces one big softmax over every class with a short chain of binary decisions down a tree, so each prediction costs about log V steps instead of V.

On this page

  • Colour = topic mix
  • Neural network basics
  • Algorithms
  • Language & LLMs
  • Discrete math
  • Probability
  • Sign in to see your progress

TL;DR

A softmax over VV classes needs VV scores and a sum over all of them, so every prediction costs time proportional to VV. With a vocabulary of hundreds of thousands of words, that is the bottleneck. Hierarchical softmax arranges the classes as the leaves of a binary tree. To predict a class, the model makes one yes-or-no decision at each internal node on the path from the root to that leaf. The probability of the class is the product of those decisions, and only the nodes on one path are ever computed.

Because a balanced tree over VV leaves has depth about log⁡2V\log_2 V, the cost drops from VV to about log⁡2V\log_2 V per prediction. The probabilities still sum to one over all classes, so it is a true distribution, not an approximation.

Where you'll see it: in word2vec-style training of word embeddings, and in older neural language models with very large vocabularies, where it made training practical before fast hardware made the full softmax cheap enough.

Intuition

Twenty questions instead of a long list

Imagine guessing a word from a dictionary by asking yes-or-no questions. You could check every entry one at a time, which takes as long as the dictionary is long. Or you could ask "is it in the first half of the alphabet?", then "in the first half of that?", and so on. Each answer halves the candidates, so about log⁡2V\log_2 V questions identify any entry. Hierarchical softmax does exactly that, except that each question is a learned probability rather than a fact.

The classes are the leaves of a binary tree. Each internal node holds a small learned classifier that decides between its left and right subtree. The model does not compute a score for every class. It computes one score per node on the path it cares about.

flowchart TD
  R["Root: animal or vehicle?"] -->|left| A["Node: mammal or bird?"]
  R -->|right| B["Node: car or boat?"]
  A -->|left| C["cat"]
  A -->|right| D["dog"]
  B -->|left| E["car"]
  B -->|right| F["boat"]

To find the probability of "cat", the model multiplies the probability of going left at the root by the probability of going left at the mammal node. It never touches the car, boat or bird parts of the tree.

Why the tree shape matters

The leaves can be arranged in any binary tree, and the arrangement changes the cost. A balanced tree gives every class the same path length. A Huffman tree, built by repeatedly merging the two least frequent items until one tree remains, gives frequent words short paths and rare words long ones. The average path length then stays within one step of the Entropy (in bits) of the word distribution, so the common words that dominate the training data are the cheapest to predict. Rare words still work, just at a higher cost.

What the tree does not change

The output is still a full probability distribution over all VV classes. Hierarchical softmax is an exact reparameterisation, not a sampling trick. It changes how the probabilities are factored, and it changes how many numbers are touched to compute one of them.

The math

Setup

Let h∈RD\mathbf{h} \in \mathbb{R}^{D} be the hidden vector that the network produces for one prediction, such as the context around a word. Let the classes be the leaves of a binary tree TT. Each internal node nn has a learned vector vn∈RD\mathbf{v}_n \in \mathbb{R}^{D}. Put a score on each node:

zn=vn⊤h.z_n = \mathbf{v}_n^{\top} \mathbf{h}.

Here vn⊤h\mathbf{v}_n^{\top}\mathbf{h} is the dot product between the node's vector and the hidden vector, a single real number. There are V−1V - 1 internal nodes in a binary tree with VV leaves, so the number of output parameters is about the same as in a flat softmax, which has VV output vectors.

Decisions at a node

At each internal node, the probability of going left is the sigmoid of its score, and the probability of going right is one minus that. Writing s=+1s = +1 for a left move and s=−1s = -1 for a right move, both cases fit one formula:

P(move s at node n)=σ ⁣(s zn),σ(u)=11+e−u.P(\text{move } s \text{ at node } n) = \sigma\!\left(s \, z_n\right), \qquad \sigma(u) = \frac{1}{1 + e^{-u}}.

Check the two cases: σ(zn)\sigma(z_n) is the left probability and σ(−zn)=1−σ(zn)\sigma(-z_n) = 1 - \sigma(z_n) is the right probability. They add to 1, as they must.

Probability of a class

Let the path from the root to leaf ww pass through internal nodes n1,…,nL(w)n_1, \ldots, n_{L(w)}, with moves s1,…,sL(w)s_1, \ldots, s_{L(w)} along the way. The probability of class ww is

P(w∣h)=∏j=1L(w)σ ⁣(sj vnj⊤h).P(w \mid \mathbf{h}) = \prod_{j=1}^{L(w)} \sigma\!\left(s_j \, \mathbf{v}_{n_j}^{\top} \mathbf{h}\right).

Here L(w)L(w) is the depth of leaf ww, the number of decisions on its path. Each factor is one decision.

The probabilities sum to one. Take any internal node. Its left and right children receive probabilities σ(z)\sigma(z) and 1−σ(z)1 - \sigma(z), which add to 1. Apply this at the root: the probabilities of all leaves in the left subtree sum to σ(zroot)\sigma(z_{\text{root}}), and those in the right subtree to 1−σ(zroot)1 - \sigma(z_{\text{root}}). Recursively, each subtree's leaves sum to one. So ∑wP(w∣h)=1\sum_{w} P(w \mid \mathbf{h}) = 1.

Cost

For a flat softmax, computing one probability needs all VV scores for the normaliser, so the cost is O(VD)O(VD). For hierarchical softmax, computing P(w∣h)P(w \mid \mathbf{h}) needs only the L(w)L(w) nodes on one path, each a dot product of length DD:

cost=O ⁣(L(w) D).\text{cost} = O\!\left(L(w) \, D\right).

For a balanced tree, L(w)≈log⁡2VL(w) \approx \log_2 V for every ww, so the cost is O(Dlog⁡V)O(D \log V).

Training

Training maximises the log-likelihood log⁡P(w∣h)\log P(w \mid \mathbf{h}) of the observed class ww. This is a sum over the path:

log⁡P(w∣h)=∑j=1L(w)log⁡σ ⁣(sjznj).\log P(w \mid \mathbf{h}) = \sum_{j=1}^{L(w)} \log \sigma\!\left(s_j z_{n_j}\right).

The derivative of log⁡σ(sz)\log \sigma(s z) with respect to zz is s (1−σ(sz))s\,(1 - \sigma(s z)). Each node on the path therefore receives an update of size proportional to how wrong its own decision was. Nodes off the path receive no gradient for this example, which is the source of the speed-up in training.

Worked examples

Example
Four classes, by hand

Take a balanced tree with four leaves A,B,C,DA, B, C, D. The root n0n_0 splits {A,B}\{A, B\} from {C,D}\{C, D\}. Node n1n_1 splits AA from BB, and node n2n_2 splits CC from DD. Suppose the hidden vector gives scores zn0=0.5z_{n_0} = 0.5, zn1=1.0z_{n_1} = 1.0 and zn2=−0.5z_{n_2} = -0.5.

  1. Look up the sigmoids. σ(0.5)≈0.6225\sigma(0.5) \approx 0.6225, σ(1.0)≈0.7311\sigma(1.0) \approx 0.7311, σ(−1.0)≈0.2689\sigma(-1.0) \approx 0.2689, σ(−0.5)≈0.3775\sigma(-0.5) \approx 0.3775.
  2. Class AA is left at n0n_0 and left at n1n_1: P(A)=0.6225×0.7311≈0.455P(A) = 0.6225 \times 0.7311 \approx 0.455.
  3. Class BB is left at n0n_0 and right at n1n_1: P(B)=0.6225×0.2689≈0.167P(B) = 0.6225 \times 0.2689 \approx 0.167.
  4. Class CC is right at n0n_0 and left at n2n_2: P(C)=0.3775×0.3775≈0.143P(C) = 0.3775 \times 0.3775 \approx 0.143.
  5. Class DD is right at n0n_0 and right at n2n_2: P(D)=0.3775×0.6225≈0.235P(D) = 0.3775 \times 0.6225 \approx 0.235.
  6. Check the total: 0.455+0.167+0.143+0.235=1.0000.455 + 0.167 + 0.143 + 0.235 = 1.000.

Interpretation: the root score favours the left pair, and the node n1n_1 score favours AA over BB. The four numbers form a proper distribution, computed with three sigmoids instead of four exponentials and a normaliser. For four classes the saving is small, but the same arithmetic shows why the method scales: a path of length two costs two sigmoids regardless of what the other branches contain.

Example
A realistic vocabulary

A language model has a vocabulary of V=1,000,000V = 1{,}000{,}000 words and hidden size D=300D = 300.

  1. Flat softmax per prediction: V×D=1,000,000×300=3×108V \times D = 1{,}000{,}000 \times 300 = 3 \times 10^{8} multiply-adds, just to compute the normaliser.
  2. Balanced hierarchical softmax: depth ⌈log⁡21,000,000⌉=20\lceil \log_2 1{,}000{,}000 \rceil = 20. Cost 20×300=6,00020 \times 300 = 6{,}000 multiply-adds.
  3. Ratio: 3×108/6×103=50,0003 \times 10^{8} / 6 \times 10^{3} = 50{,}000. The tree is about fifty thousand times cheaper per prediction.
  4. With a Huffman tree the average depth for natural text is much smaller than 20, because most tokens are common words near the root. The exact saving depends on the word frequencies.

Interpretation: at this vocabulary size the flat softmax dominates the training time, and the tree removes almost all of that cost. The price is that the path probabilities must be learned well for every internal node, which is harder to tune than a single output matrix.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Small vocabulary, a few thousand classesThe tree saves little, and the extra indirection can hurt accuracyA plain softmax
You need the full distribution at inference timeComputing every class's probability still touches every node, so the saving disappearsA plain softmax, which is well optimised on GPUs
Very large output layer with a fast GPUMatrix multiplication is cheap, so the saving matters lessFull softmax, or sampled softmax
Training with a very large vocabulary on modest hardwareNothing: this is the favourable case, since gradients reach only the nodes on each pathHierarchical softmax, often with a Huffman tree
Words are poorly grouped by the treeA wrong decision near the root cannot be undone further downA tree built from frequency or from clustering that reflects meaning

Failure modes are mostly about the tree. A poor split near the root forces every related word to share an early mistake. Rare words sit deep in a Huffman tree, so they get fewer gradient updates and their vectors can stay noisy. Also, hierarchical softmax is a training speed-up that can give a different model than the full softmax, so comparing perplexities across the two needs care: both should be computed the same way at evaluation.

History

The idea of grouping classes into a hierarchy to speed up maximum-entropy models was studied by Joshua Goodman in 2001 under the name class-based models. Frederic Morin and Yoshua Bengio applied a binary-tree factorisation of the output layer to a neural language model at the 2005 AISTATS conference. Their goal was practical: a neural model over a large vocabulary was too slow to train with a full softmax.

Andriy Mnih and Geoffrey Hinton followed with a scalable hierarchical language model around 2008 and 2009, which learned the tree and the word vectors together. The method gained wide use when Tomas Mikolov and colleagues built word2vec in 2013. Their papers used a Huffman tree over word frequencies, so common words were predicted with short paths. That choice made training on billions of words feasible at the time, and it made hierarchical softmax a standard tool for word embeddings. Later work tended to use negative sampling for embeddings and full softmax for large language models on modern hardware, but the tree idea remains the clearest way to see why output-layer cost can be reduced.

Check yourself

QuestionRecall: what does the probability of one class equal in hierarchical softmax?Show answer

It is the product of the probabilities of the decisions on the path from the root to that class's leaf. Each decision is a sigmoid of the node's score, taken with the sign that matches the direction of the move. Nodes off the path do not appear in the product.

QuestionComputation: a class is reached through three decisions with probabilities 0.8, 0.5 and 0.9. What is its probability?Show answer

Multiply the three: 0.8×0.5×0.9=0.360.8 \times 0.5 \times 0.9 = 0.36. Each decision is a probability in (0,1)(0,1), so the product is smaller than any single factor, which is why deep leaves get small probabilities unless their decisions are confident.

QuestionWhy: why do the probabilities of all leaves sum to exactly one?Show answer

At each internal node the two children receive σ(z)\sigma(z) and 1−σ(z)1 - \sigma(z), which sum to one. Starting at the root and recursing down, the total mass of every subtree is split between its two children with nothing lost or created. So the leaves of the whole tree sum to one. The proof uses only the rule at each node, so it holds for any tree shape.

QuestionApplied: a model has a vocabulary of 50,000 words and hidden size 512. Roughly how much cheaper is a balanced hierarchical softmax per prediction than a flat softmax?Show answer

The flat softmax costs about 50,000×512=25.650{,}000 \times 512 = 25.6 million multiply-adds. A balanced tree has depth ⌈log⁡250,000⌉=16\lceil \log_2 50{,}000 \rceil = 16, costing 16×512=8,19216 \times 512 = 8{,}192. The ratio is 25,600,000/8,192=3,12525{,}600{,}000 / 8{,}192 = 3{,}125, so roughly three thousand times cheaper per prediction. A Huffman tree would be cheaper again on average for natural text.

Sources

  • Morin and Bengio, Hierarchical Probabilistic Neural Network Language Model (AISTATS, 2005), PMLR
  • Mikolov et al., Efficient Estimation of Word Representations in Vector Space (2013), arXiv:1301.3781
  • Mikolov et al., Distributed Representations of Words and Phrases and their Compositionality (2013), arXiv:1310.4546
  • Softmax function (Wikipedia)