Algorithm Search⌘K

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 ∣V∣|V| 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 ⌈log⁡2∣V∣⌉\lceil \log_2 |V| \rceil 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 −log⁡P(w∣h⃗)-\log P(w \mid \vec h) 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 O(∣V∣d)O(|V| d) 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 u⃗n\vec u_n of each inner node nn and the input vector h⃗\vec h (the word vector in skip-gram, the mean of the context vectors in CBOW). The tree is a full binary tree with the ∣V∣|V| words as leaves, so it has ∣V∣−1|V| - 1 inner nodes. The path of word ww is the list of pairs (n1,b1),…,(nL,bL)(n_1, b_1), \ldots, (n_L, b_L) of an inner node and the bit of the child taken. With sn=u⃗n⋅h⃗s_n = \vec u_n \cdot \vec h, the child 0 of node nn has probability σ(sn)\sigma(s_n) and the child 1 has probability σ(−sn)\sigma(-s_n), where σ(x)=1/(1+e−x)\sigma(x) = 1/(1 + e^{-x}). Then

P(w∣h⃗)=∏j=1Lσ((1−2bj) snj).P(w \mid \vec h) = \prod_{j=1}^{L} \sigma\big((1 - 2b_j)\, s_{n_j}\big).
  1. HS-LOG-PROB(h, u, path of w)
  2. 1for each (n, b) on the path of w, from the root do
  3. 2s ← u_n · h
  4. 3total ← total + log σ(s) if b = 0, else total + log σ(-s)
  5. 4return total ▷ log P(w | h)

The gradient of −log⁡P(w∣h⃗)-\log P(w \mid \vec h) comes from the same loop. With en=σ(sn)−[b=0]e_n = \sigma(s_n) - [b = 0] for each node on the path,

∂∂u⃗n=en h⃗,∂∂h⃗=∑(n,b) on the pathen u⃗n.\frac{\partial}{\partial \vec u_n} = e_n\,\vec h, \qquad \frac{\partial}{\partial \vec h} = \sum_{(n, b) \text{ on the path}} e_n\,\vec u_n.

Only the LL node vectors on the path change in a training step.

The probabilities sum to 1. Claim. For every inner node nn, the products of the factors from nn down to each leaf below nn sum to 1. Proof by induction on the height of nn. The product below a leaf is empty, so it is 1. For an inner node nn with subtrees whose sums are S0=S1=1S_0 = S_1 = 1 by the hypothesis, the sum below nn is σ(sn)S0+σ(−sn)S1=σ(sn)+σ(−sn)=1\sigma(s_n) S_0 + \sigma(-s_n) S_1 = \sigma(s_n) + \sigma(-s_n) = 1, since σ(x)+σ(−x)=1\sigma(x) + \sigma(-x) = 1. At the root this gives ∑w∈VP(w∣h⃗)=1\sum_{w \in V} P(w \mid \vec h) = 1 for every h⃗\vec h and every choice of the node vectors. ■\blacksquare

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 =(0,0)= (0, 0), b =(0,1),(1,0)= (0, 1), (1, 0), c =(0,1),(1,1),(2,0)= (0, 1), (1, 1), (2, 0) and d =(0,1),(1,1),(2,1)= (0, 1), (1, 1), (2, 1). With d=1d = 1, h=1h = 1 and node values u0=0.5u_0 = 0.5, u1=−1u_1 = -1, u2=2u_2 = 2:

word factors probability
a σ(0.5)\sigma(0.5) 0.6225
b σ(−0.5) σ(−1)\sigma(-0.5)\,\sigma(-1) 0.1015
c σ(−0.5) σ(1) σ(2)\sigma(-0.5)\,\sigma(1)\,\sigma(2) 0.2431
d σ(−0.5) σ(1) σ(−2)\sigma(-0.5)\,\sigma(1)\,\sigma(-2) 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 ⌈log⁡2∣V∣⌉\lceil \log_2 |V| \rceil or fewer nodes. In a Huffman tree built from the word counts, the expected path length per token Lˉ=∑wpwLw\bar L = \sum_w p_w L_w is the expected length of an optimal binary prefix code, so H≤Lˉ<H+1H \le \bar L < H + 1, where HH is the entropy in base 2 of the word distribution. For the counts (5,2,1,1)(5, 2, 1, 1) the Huffman path lengths are (1,2,3,3)(1, 2, 3, 3), Lˉ=15/9=1.6667\bar L = 15/9 = 1.6667 and H=1.6577H = 1.6577, against 2 for the balanced tree. The cost of the training pass per token is dLˉd \bar L, so frequent words are cheap. The worst path in a Huffman tree can have ∣V∣−1|V| - 1 nodes, for example for counts that grow like powers of 2. So one prediction with a Huffman tree costs O(d∣V∣)O(d|V|) in the worst case and O(d(H+1))O(d(H + 1)) on average over the tokens, and the extra memory is O(∣V∣)O(|V|) 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 h⃗\vec h, and predicts each context word along its path.
  • Continuous bag-of-words. The same tree, with the mean of the context vectors as h⃗\vec h 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 ∣V∣\sqrt{|V|} classes and predicting the class and then the word in the class costs O(∣V∣ d)O(\sqrt{|V|}\, d) 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 σ(s)\sigma(s) for one child and σ(−s)\sigma(-s) for the other. If both children use σ(s)\sigma(s), the sum over the leaves is no longer 1 and the model is not normalized. The word2vec code stores the bit as a label 1−b1 - b, which is the same convention written differently.
  • The cost of all probabilities. The fast path is for one target word. Computing P(w∣h⃗)P(w \mid \vec h) for every word still costs O(∣V∣d)O(|V| d), 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 log⁡2∣V∣\log_2 |V|. 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.

hierarchical_softmax.pyI0RawGitHub
# 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

  1. Show that a full binary tree with ∣V∣|V| leaves has exactly ∣V∣−1|V| - 1 inner nodes, so the hierarchical softmax has the same number of output vectors as the flat softmax, less one.
  2. Build the Huffman tree for the counts (8,4,2,1,1)(8, 4, 2, 1, 1), compute the expected path length and compare it with the entropy of the distribution.
  3. Show that with all node vectors equal to zero, every word gets the probability 2−Lw2^{-L_w}, and use the Kraft inequality to show that these sum to 1 for a full binary tree.

References

  1. 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
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises