A hierarchical softmax replaces a -way softmax by a binary tree of sigmoid decisions, so the probability of one class costs instead of .
1. build_huffman_tree(freqs): build a Huffman tree over the classes. Give leaves the ids in input order. Repeatedly remove the two nodes with the smallest frequency (ties broken by the smaller id), and merge them into a new internal node whose frequency is their sum; internal nodes get ids in creation order. The first node removed becomes the left child. The last node created is the root. Return a list paths of length , where paths[c] is the list of (k, bit) pairs from the root down to leaf : k is the internal node's index (its id minus ) and bit is 0 for a left turn, 1 for a right turn. Assume .
2. hsoftmax_proba(h, node_weights, paths): h is a hidden vector (H,), node_weights is (C-1, H) with row k belonging to internal node k. At node k go left with probability and right with . Return the length- vector of leaf probabilities (product along each path).
3. log_prob(h, y, node_weights, paths): return for one class, touching only the nodes on its path. Use a numerically stable log-sigmoid.