Techniquecore
Hierarchical softmax
Also called tree softmax.
Replace the softmax over V words by the product of the binary logistic decisions on the path to the word in a binary tree. A balanced tree has paths of length at most ceil(log2 V).
The hierarchical softmax computes the probability of one word out of without a sum over the vocabulary. The words are the leaves of a binary tree. Each inner node holds a vector, and the probability of a word is the product of the probabilities of the left or right turns on the path from the root to its leaf, each a logistic function of a dot product. A prediction costs one dot product per node on the path, so of them in a balanced tree. The leaf probabilities sum to 1 by construction, so the model stays normalized. Morin and Bengio (2005) introduced it for a neural probabilistic language model. Mikolov et al. (2013) used a Huffman tree over the word counts in word2vec, which gives frequent words short paths.
In plain words
To pick one word out of a million, the normal way scores every word. The hierarchical softmax plays a game of twenty questions instead.
Put all the words at the bottom of a tree that splits in two at each step. At each split, the model asks a yes or no question about the input and gets a chance for "left" and a chance for "right" that add up to one. The chance of a word is the product of the chances along the way down to it.
Because the two chances at each split add up to one, the chances of all the words add up to one too. Only the splits on one path need work, which is about twenty for a million words. If common words sit near the top, the usual path is even shorter.
When it applies
Use it when a model ends in a softmax over a large discrete set, here the vocabulary, and you need a normalized distribution or an exact log-likelihood at a lower cost. The signals are a training loss of the form for one target word at a time, a vocabulary of thousands to millions of words, and a fixed tree, or one that you can build once from counts. When you need the probabilities of all words, for example to sample or to rank the whole vocabulary, the cost is again and a plain softmax is simpler. When you need only vectors, negative sampling is simpler still.
The template
The holes are the tree, the vector of each inner node and the input vector (the word vector in skip-gram, the mean of the context vectors in CBOW). The tree is a full binary tree with the words as leaves, so it has inner nodes. The path of word is the list of pairs of an inner node and the bit of the child taken. With , the child 0 of node has probability and the child 1 has probability , where . Then
HS-LOG-PROB(h, u, path of w)- 1
for each (n, b) on the path of w, from the root do - 2
s ← u_n · h - 3
total ← total + log σ(s) if b = 0, else total + log σ(-s) - 4
return total ▷ log P(w | h)
The gradient of comes from the same loop. With for each node on the path,
Only the node vectors on the path change in a training step.
The probabilities sum to 1. Claim. For every inner node , the products of the factors from down to each leaf below sum to 1. Proof by induction on the height of . The product below a leaf is empty, so it is 1. For an inner node with subtrees whose sums are by the hypothesis, the sum below is , since . At the root this gives for every and every choice of the node vectors.
The proof needs every inner node to have two children. A node with one child would lose the mass of the other branch.
Example. Take four words and the tree whose paths are a , b , c and d . With , and node values , , :
| word | factors | probability |
|---|---|---|
| a | 0.6225 | |
| b | 0.1015 | |
| c | 0.2431 | |
| d | 0.0329 |
The sum is 1. Word a costs one dot product, and words c and d cost three.
Path lengths. In a balanced tree every path has or fewer nodes. In a Huffman tree built from the word counts, the expected path length per token is the expected length of an optimal binary prefix code, so , where is the entropy in base 2 of the word distribution. For the counts the Huffman path lengths are , and , against 2 for the balanced tree. The cost of the training pass per token is , so frequent words are cheap. The worst path in a Huffman tree can have nodes, for example for counts that grow like powers of 2. So one prediction with a Huffman tree costs in the worst case and on average over the tokens, and the extra memory is for the tree and the paths.
Classic examples
- Neural probabilistic language model. Morin and Bengio replaced the output softmax of the model by a tree built from the WordNet hierarchy, to make the language model faster to train and to evaluate.
- Skip-gram model. word2vec uses a Huffman tree over the word counts, with the center word vector as , and predicts each context word along its path.
- Continuous bag-of-words. The same tree, with the mean of the context vectors as and the center word as the target.
- DeepWalk. Skip-gram on random walks over a graph, trained with a hierarchical softmax whose leaves are the vertices.
Variations
- The choice of tree. A balanced tree gives the best worst case. A Huffman tree gives the shortest expected path for the training tokens. A tree built from word similarity (from WordNet or by clustering word vectors) puts similar words in the same subtree, and each decision is then easier to learn. A random tree trains, but the decisions near the root then mix unrelated words.
- Two levels. Splitting the vocabulary into about classes and predicting the class and then the word in the class costs per prediction. It is a tree of depth 2 with a softmax at each node.
- Sampled methods. Negative sampling and noise-contrastive estimation also avoid the full sum, but by sampling. The hierarchical softmax is exact and needs no sampling, at the price of a fixed tree.
Pitfalls
- The sign convention. Line L3 must use for one child and for the other. If both children use , the sum over the leaves is no longer 1 and the model is not normalized. The word2vec code stores the bit as a label , which is the same convention written differently.
- The cost of all probabilities. The fast path is for one target word. Computing for every word still costs , so ranking or sampling the whole vocabulary does not get faster.
- Unbalanced worst case. With a Huffman tree a rare word can have a path much longer than . The average cost is low, but a single prediction of a rare word is not.
- Comparing losses. The log-likelihood of the tree model is a different model from the flat softmax, and its value depends on the tree. Compare models by perplexity on held-out data, not by the training loss of two different trees.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hierarchical-softmax/. The authors are listed in prov/5QHTPW.jsonl.
"""Hierarchical softmax over a binary tree, with a Huffman tree as in word2vec.
The |V| words are the leaves of a full binary tree with |V| - 1 inner nodes.
Each inner node n has a vector u_n. The path of word w is a list of
(node, bit) pairs from the root. At node n the walk goes to child 0 with
probability sigma(u_n . h) and to child 1 with probability sigma(-u_n . h),
so P(w | h) is the product of these factors along the path.
"""
import heapq
import math
from typing import Sequence
def sigmoid(x: float) -> float:
if x >= 0:
return 1.0 / (1.0 + math.exp(-x))
e = math.exp(x)
return e / (1.0 + e)
def log_sigmoid(x: float) -> float:
return -math.log1p(math.exp(-x)) if x >= 0 else x - math.log1p(math.exp(x))
def huffman_paths(counts: Sequence[int]) -> list[list[tuple[int, int]]]:
"""Path of (inner node, bit) pairs from the root to each word; nodes are numbered 0 to |V| - 2."""
n = len(counts)
if n == 1:
return [[]]
heap = [(c, i, ("leaf", i)) for i, c in enumerate(counts)]
heapq.heapify(heap)
children = []
tie = n
while len(heap) > 1:
c0, _, a = heapq.heappop(heap)
c1, _, b = heapq.heappop(heap)
children.append((a, b))
heapq.heappush(heap, (c0 + c1, tie, ("node", len(children) - 1)))
tie += 1
root = len(children) - 1
paths: list[list[tuple[int, int]]] = [[] for _ in range(n)]
stack = [(root, [])]
while stack:
node, path = stack.pop()
for bit, child in enumerate(children[node]):
step = path + [(root - node, bit)] # renumber so that the root is node 0
if child[0] == "leaf":
paths[child[1]] = step
else:
stack.append((child[1], step))
return paths
def balanced_paths(n: int) -> list[list[tuple[int, int]]]:
"""Paths in a tree that splits the words in halves (depth ceil(log2 n))."""
paths: list[list[tuple[int, int]]] = [[] for _ in range(n)]
counter = [0]
def build(lo: int, hi: int, path):
if hi - lo == 1:
paths[lo] = path
return
node = counter[0]
counter[0] += 1
mid = (lo + hi + 1) // 2
build(lo, mid, path + [(node, 0)])
build(mid, hi, path + [(node, 1)])
build(0, n, [])
return paths
def log_prob(h: Sequence[float], nodes, path) -> float:
"""log P(w | h) for the word with this path."""
total = 0.0
for n, bit in path: # @line L1
s = sum(a * b for a, b in zip(nodes[n], h)) # @line L2
total += log_sigmoid(s if bit == 0 else -s) # @line L3
return total # @line L4
def loss_gradient(h: Sequence[float], nodes, path):
"""(-log P(w | h), gradient of h, dict of gradients of the inner node vectors)."""
d = len(h)
gh = [0.0] * d
gn: dict[int, list[float]] = {}
for n, bit in path:
s = sum(a * b for a, b in zip(nodes[n], h))
e = sigmoid(s) - (1.0 if bit == 0 else 0.0) # d(-log factor)/ds
row = gn.setdefault(n, [0.0] * d)
for k in range(d):
gh[k] += e * nodes[n][k]
row[k] += e * h[k]
return -log_prob(h, nodes, path), gh, gn
def expected_length(counts: Sequence[int], paths) -> float:
total = sum(counts)
return sum(c * len(p) for c, p in zip(counts, paths)) / total
def entropy_bits(counts: Sequence[int]) -> float:
total = sum(counts)
return -sum(c / total * math.log2(c / total) for c in counts if c > 0)
test_hierarchical_softmax.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hierarchical-softmax/. The authors are listed in prov/5QHTPW.jsonl.
import itertools
import math
import random
from hierarchical_softmax import (
balanced_paths,
entropy_bits,
expected_length,
huffman_paths,
log_prob,
loss_gradient,
)
def is_prefix_free(paths):
codes = [tuple(b for _, b in p) for p in paths]
return all(a[: len(b)] != b for a in codes for b in codes if a is not b and len(a) >= len(b))
def test_hand_example():
paths = [[(0, 0)], [(0, 1), (1, 0)], [(0, 1), (1, 1), (2, 0)], [(0, 1), (1, 1), (2, 1)]]
nodes = [[0.5], [-1.0], [2.0]]
p = [math.exp(log_prob([1.0], nodes, q)) for q in paths]
assert [round(x, 4) for x in p] == [0.6225, 0.1015, 0.2431, 0.0329]
assert abs(sum(p) - 1.0) < 1e-12
def test_huffman_lengths_and_entropy():
counts = [5, 2, 1, 1]
paths = huffman_paths(counts)
assert sorted(len(p) for p in paths) == [1, 2, 3, 3]
assert len(paths[0]) == 1
assert abs(expected_length(counts, paths) - 15 / 9) < 1e-12
assert round(entropy_bits(counts), 4) == 1.6577
def test_probabilities_sum_to_one_over_vocabulary():
rng = random.Random(1)
for v in (2, 3, 7, 16, 50):
counts = [rng.randint(1, 100) for _ in range(v)]
for paths in (huffman_paths(counts), balanced_paths(v)):
assert is_prefix_free(paths)
nodes_used = {n for p in paths for n, _ in p}
assert nodes_used == set(range(v - 1))
nodes = [[rng.gauss(0, 2) for _ in range(5)] for _ in range(v - 1)]
for _ in range(3):
h = [rng.gauss(0, 1) for _ in range(5)]
total = sum(math.exp(log_prob(h, nodes, p)) for p in paths)
assert abs(total - 1.0) < 1e-12
def test_balanced_depth():
for v in range(2, 51):
assert max(len(p) for p in balanced_paths(v)) == math.ceil(math.log2(v))
def test_huffman_is_optimal_against_all_length_vectors():
rng = random.Random(2)
for v in (2, 3, 4, 5, 6):
for _ in range(5):
counts = [rng.randint(1, 30) for _ in range(v)]
best = min(
sum(c * l for c, l in zip(counts, lengths))
for lengths in itertools.product(range(1, v), repeat=v)
if sum(2.0 ** -l for l in lengths) <= 1.0
)
got = sum(c * len(p) for c, p in zip(counts, huffman_paths(counts)))
assert got == best
h = entropy_bits(counts)
assert h <= expected_length(counts, huffman_paths(counts)) < h + 1
def test_gradient_against_finite_differences():
rng = random.Random(3)
counts = [9, 4, 4, 2, 1, 1]
paths = huffman_paths(counts)
nodes = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(5)]
h = [rng.uniform(-1, 1) for _ in range(4)]
eps = 1e-6
for path in paths:
_, gh, gn = loss_gradient(h, nodes, path)
for vec, grad in [(h, gh)] + [(nodes[n], gn.get(n, [0.0] * 4)) for n in range(5)]:
for k in range(4):
old = vec[k]
vec[k] = old + eps
up = -log_prob(h, nodes, path)
vec[k] = old - eps
down = -log_prob(h, nodes, path)
vec[k] = old
assert abs((up - down) / (2 * eps) - grad[k]) < 1e-5
Exercises
- Show that a full binary tree with leaves has exactly inner nodes, so the hierarchical softmax has the same number of output vectors as the flat softmax, less one.
- Build the Huffman tree for the counts , compute the expected path length and compare it with the entropy of the distribution.
- Show that with all node vectors equal to zero, every word gets the probability , and use the Kraft inequality to show that these sum to 1 for a full binary tree.
References
- Morin and Bengio 2005, the decomposition of the conditional word probability into binary decisions along a tree, and the tree built from the WordNet hierarchy
- Mikolov, Chen, Corrado and Dean 2013, Section 2 (the hierarchical softmax with a Huffman tree over the word frequencies, and the log2(V) term of the training complexity)
- Mikolov, Sutskever, Chen, Corrado and Dean 2013, the hierarchical softmax for the skip-gram model, written with the sign of each step on the path, and the Huffman tree
- Thomas M. Cover and Joy A. Thomas, Elements of Information Theory, second edition, Wiley, 2006, Chapter 5 (the Kraft inequality, the bound H <= L < H + 1 on the expected length of an optimal prefix code, and the optimality of Huffman codes)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 5QHTPW Edit this page History Report an error Markdown