Sub topic 11
Hierarchical softmax
Prerequisites
This chapter assumes you know the skip-gram model and why the full softmax is expensive (the two chapters before this one). You should also be comfortable with the sigmoid function, binary trees, and the idea of a gradient step. Hierarchical softmax is a minor topic in practice, so this chapter is compact. It explains the mechanism and tells you when to choose it.
The problem it solves
Skip-gram predicts a context word c given a center word w. The full softmax computes
P(c | w) = exp(uc · vw) / Σ{j=1..V} exp(uj · v_w)
The denominator sums over every word in the vocabulary of size V. For V = 1,000,000, each training pair needs about a million dot products, and the same number of output vectors must be updated.
Negative sampling avoids this by turning the task into a few binary decisions. Hierarchical softmax keeps the original goal of modelling a proper probability distribution over the vocabulary. It makes the computation cheaper by changing how the distribution is parameterised.
The core idea: a path through a tree
Arrange all V words as the leaves of a binary tree. There are no separate output vectors for words. Instead, each internal node n has its own vector θ_n. The probability of a word is the probability of walking from the root to its leaf, and each step is a binary decision.
At an internal node n with the center word vector v_w, the probability of going left is
P(left | n, w) = σ(θn · vw)
and the probability of going right is 1 - σ(θ_n · v_w), which equals σ(-θ_n · v_w).
The probability of a context word c is the product of the step probabilities along its path:
P(c | w) = Π over the nodes n on the path to c of σ(±θn · vw)
The sign is positive when the path turns left at n and negative when it turns right.
The key point is that these probabilities sum to 1 over all leaves without any normalisation. At every internal node the left and right probabilities add to 1, so the total probability mass is conserved down the tree. You never compute a sum over V words.
In this tree, P(mat | w) = σ(-θ_1·v) · σ(-θ_3·v) · σ(-θ_4·v), because the path turns right at n1, n3 and n4. Three sigmoid evaluations replace a sum over all six words.
Cost
If the tree is balanced, a path has about log₂ V nodes. For V = 1,000,000 that is about 20 steps instead of a million. A training pair then costs about 20 dot products and 20 vector updates.
A balanced tree is not the best choice. word2vec builds a Huffman tree, which gives shorter paths to frequent words and longer paths to rare ones. The average path length is then close to the entropy of the unigram distribution, which is lower than log₂ V for natural text. Since frequent words appear in most training pairs, the average cost per pair drops further.
| Method | Cost per training pair | Output parameters |
|---|---|---|
| Full softmax | O(V) | One vector per word |
| Hierarchical softmax | O(log V), shorter on average with a Huffman tree | One vector per internal node (V − 1 nodes) |
| Negative sampling | O(k + 1) for k negatives | One vector per word |
A runnable sketch
The following code computes the probability of a word from its path. It uses a hand-built tree matching the diagram above. Each word is stored with the list of (node, direction) steps, where direction is +1 for left and -1 for right.
import numpy as np
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
rng = np.random.default_rng(0)
dim = 8
# Internal node vectors: n1, n2, n3, n4 (V - 1 = 4 nodes is not exact here
# because the tree has 6 leaves and 5 internal nodes; n5 is unused by this
# sketch, so we only define the four used by the paths below).
theta = {name: rng.normal(scale=0.1, size=dim) for name in ["n1", "n2", "n3", "n4"]}
paths = {
"cat": [("n1", +1), ("n2", +1)],
"dog": [("n1", +1), ("n2", -1)],
"sits": [("n1", -1), ("n3", +1)],
"on": [("n1", -1), ("n3", -1), ("n4", +1)],
"mat": [("n1", -1), ("n3", -1), ("n4", -1)],
}
def word_prob(word, v):
p = 1.0
for node, direction in paths[word]:
p *= sigmoid(direction * np.dot(theta[node], v))
return p
v = rng.normal(size=dim)
probs = {w: word_prob(w, v) for w in paths}
print(probs)
print(sum(probs.values())) # 1.0 over the five leaves defined hereThe five words in paths are the leaves of a valid tree: n1 splits {cat, dog} from {sits, on, mat}. Because every internal node splits its mass between two children, the printed sum is 1 (up to floating-point error). That is the property the full softmax achieves with an explicit denominator.
Training
The loss for a pair is the negative log of the path probability, so it is a sum of binary logistic losses, one per node on the path. The gradient with respect to θ_n and v_w is the usual logistic-regression gradient at each node. Only the nodes on the path are updated, so a step touches about log V output vectors and the one input vector.
Using it in gensim
Gensim enables hierarchical softmax with hs=1. It builds the Huffman tree itself from word counts. Negative sampling is controlled separately with negative, and you can use both at once, though most users pick one.
from gensim.models import Word2Vec
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
]
model = Word2Vec(
sentences=sentences,
vector_size=50,
window=2,
min_count=1,
sg=1,
hs=1,
negative=0, # turn negative sampling off so only hs is used
epochs=50,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)Trade-offs and edge cases
- Rare words. Rare words sit deep in the Huffman tree, and their paths share nodes with only a few other words. Hierarchical softmax is often reported to work better for infrequent words, while negative sampling tends to do better for frequent words and with low-dimensional vectors. Treat this as a tendency, not a rule, and test on your own data.
- Larger corpora. Negative sampling has become the common default because it is simple, and it parallelises well. Hierarchical softmax is mostly of historical and conceptual interest now.
- Tree structure matters. The tree places words with similar frequency near each other, not words with similar meaning. Some work builds trees from semantic clusters, but word2vec does not.
- Default setting. In gensim,
hs=0andnegative=5by default. If you seths=1and leavenegative=5, both objectives train together, which is rarely what you intend. - Output vectors. The node vectors
θ_nare not word vectors, so you cannot read a word's output embedding from them. The word vectors you keep are the input vectorsv_w.
Exercise
A vocabulary has 1,048,576 words (2^20). With a balanced tree, about how many sigmoid evaluations does hierarchical softmax need per training pair, and why does a Huffman tree usually need fewer on average?
Show answer
About 20, because a balanced binary tree over 2^20 leaves has depth 20. A Huffman tree gives frequent words short paths. Since frequent words account for most training pairs, the average path length per pair falls below 20.
Exercise
In the tree from the diagram, suppose σ(θ_1·v) = 0.7 at the root. What is the total probability of all words reached by going right at n1, and why?
Show answer
0.3. The probability of going right is 1 − 0.7 = 0.3, and the probabilities of the leaves below that branch sum to 0.3, because each internal node splits its mass between its two children.