TExcelTAD
Home › Information Theory › The Kraft Inequality

The Kraft Inequality

Short codewords are precious: there are only two codewords of length 1, four of length 2, and using a short one blocks every longer codeword that starts with it. The Kraft inequality turns this into a budget. It tells us exactly which lists of codeword lengths are possible, and it leads directly to the entropy bound for symbol codes.

The inequality

A binary prefix code with codeword lengths ℓ1,…,ℓN\ell_1, \dots, \ell_N exists if and only if

∑i=1N2−ℓi≤1\sum_{i=1}^N 2^{-\ell_i} \le 1

Think of the full binary tree: a codeword of length ℓ\ell claims a subtree containing a fraction 2−ℓ2^{-\ell} of all leaves at any deep level. Prefix-freeness means the subtrees do not overlap, so the fractions add to at most 1. A code with ∑2−ℓi=1\sum 2^{-\ell_i} = 1 is complete: no codeword can be added.

McMillan's theorem extends the inequality to all uniquely decodable codes, so restricting ourselves to prefix codes costs nothing.

python · try it yourself
import numpy as np

for name, lengths in [("{0, 10, 11}", [1, 2, 2]), ("{0, 10, 110, 111}", [1, 2, 3, 3]),
                      ("lengths 1, 2, 2, 3", [1, 2, 2, 3]), ("lengths 2, 2, 3, 3, 3", [2, 2, 3, 3, 3])]:
    k = sum(2.0 ** -l for l in lengths)
    status = "complete" if k == 1 else ("possible" if k < 1 else "impossible")
    print(f"{name:22s} Kraft sum = {k:.3f}  {status}")
{0, 10, 11}            Kraft sum = 1.000  complete
{0, 10, 110, 111}      Kraft sum = 1.000  complete
lengths 1, 2, 2, 3     Kraft sum = 1.125  impossible
lengths 2, 2, 3, 3, 3  Kraft sum = 0.875  possible

Building a code from lengths

The proof of the "if" direction is constructive: sort the lengths, and give each symbol the next available codeword of its length (a canonical code). This is how DEFLATE transmits Huffman codes: only the lengths are sent.

python · try it yourself
def canonical_code(lengths):
    assert sum(2.0 ** -l for l in lengths) <= 1, "Kraft inequality violated"
    order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
    code, value, prev = {}, 0, lengths[order[0]]
    for i in order:
        value <<= lengths[i] - prev; prev = lengths[i]
        code[i] = format(value, f"0{lengths[i]}b")
        value += 1
    return code

for lengths in ([2, 1, 3, 3], [3, 3, 2, 2, 3, 4, 4]):
    print(lengths, "->", canonical_code(lengths))
[2, 1, 3, 3] -> {1: '0', 0: '10', 2: '110', 3: '111'}
[3, 3, 2, 2, 3, 4, 4] -> {2: '00', 3: '01', 0: '100', 1: '101', 4: '110', 5: '1110', 6: '1111'}

The entropy bound

For any uniquely decodable code, the expected length is at least the entropy:

L(C,X)=∑xP(x)ℓ(x)≥H(X)L(C, X) = \sum_x P(x)\ell(x) \ge H(X)

Proof. Let z=∑x2−ℓ(x)≤1z = \sum_x 2^{-\ell(x)} \le 1 and define Q(x)=2−ℓ(x)zQ(x) = \frac{2^{-\ell(x)}}{z}. Then ℓ(x)=log⁡21Q(x)−log⁡2z\ell(x) = \log_2 \frac{1}{Q(x)} - \log_2 z and

L=∑xP(x)log⁡21Q(x)−log⁡2z=H(X)+DKL(P∥Q)+log⁡21z≥H(X)L = \sum_x P(x)\log_2 \frac{1}{Q(x)} - \log_2 z = H(X) + D_{\text{KL}}(P \parallel Q) + \log_2 \frac{1}{z} \ge H(X)

using Gibbs' inequality and z≤1z \le 1. Equality needs Q=PQ = P and z=1z = 1, that is, ℓ(x)=log⁡21P(x)\ell(x) = \log_2 \frac{1}{P(x)} exactly (Optimal Code Lengths).

python · try it yourself
import numpy as np

P = np.array([0.4, 0.3, 0.2, 0.1])
H = -np.sum(P * np.log2(P))
rng = np.random.default_rng(0)
best = np.inf
for _ in range(20000):
    lengths = rng.integers(1, 7, size=4)
    if np.sum(2.0 ** -lengths) <= 1:
        best = min(best, float(P @ lengths))
print(f"entropy {H:.4f}; shortest expected length among random valid length lists: {best:.4f}")
entropy 1.8464; shortest expected length among random valid length lists: 1.9000

The best lengths, (1,2,3,3)(1, 2, 3, 3), give 1.9 bits, about 0.05 above the entropy, because the probabilities are not powers of 12\frac{1}{2}.

In software

  • Canonical codes need only the length list in the header; both sides rebuild the same code with the function above. DEFLATE, JPEG and many formats do this.
  • A decoder can check a received length list with the Kraft sum before building the code, rejecting corrupt headers.

Exercises

Exercise 1: Possible?

Can a prefix code have lengths (1,2,3,3,3)(1, 2, 3, 3, 3)?

Answer

No.

Solution

12+14+3⋅18=1.125>1\frac{1}{2} + \frac{1}{4} + 3 \cdot \frac{1}{8} = 1.125 > 1.

Exercise 2: Room for more

A prefix code has lengths (2,2,3)(2, 2, 3). How many more codewords of length 3 can be added?

Answer
Solution

The Kraft sum is 14+14+18=58\frac{1}{4} + \frac{1}{4} + \frac{1}{8} = \frac{5}{8}. The remaining 38\frac{3}{8} fits three codewords of length 3.

Exercise 3: Canonical code (code)

Build the canonical code for lengths (3,2,3,2,2)(3, 2, 3, 2, 2).

Answer

Symbols 1, 3, 4 get 00, 01, 10; symbols 0, 2 get 110, 111.

Solution
python · try it yourself
def canonical_code(lengths):
    order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
    code, value, prev = {}, 0, lengths[order[0]]
    for i in order:
        value <<= lengths[i] - prev; prev = lengths[i]
        code[i] = format(value, f"0{lengths[i]}b")
        value += 1
    return dict(sorted(code.items()))

print(canonical_code([3, 2, 3, 2, 2]))
{0: '110', 1: '00', 2: '111', 3: '01', 4: '10'}

Test yourself

A prefix code with lengths ℓi\ell_i exists if and only if…

  1. ∑2−ℓi≤1\sum 2^{-\ell_i} \le 1
  2. ∑ℓi≤N\sum \ell_i \le N
  3. all ℓi\ell_i are distinct
  4. ∑2ℓi≤1\sum 2^{\ell_i} \le 1

McMillan's theorem says that…

  1. uniquely decodable codes satisfy the Kraft inequality too
  2. Huffman codes are optimal
  3. every code is prefix-free
  4. arithmetic coding beats entropy

The expected length of any uniquely decodable code is at least…

  1. the entropy
  2. the number of symbols
  3. 1 bit
  4. the raw bit content