Diffusion Language Models › Worked Example: An Exact Bound on a Two-Token Language

Michael BrenndoerferNovember 17, 20265 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 136Diffusion Language Models › Worked Example: An Exact Bound on a Two-Token Language
Reading section 6 of 13 · Worked Example: An Exact Bound on a Two-Token Language · 5 minSection 6 of 13 · 5 min

Section 6 of 13 · 5 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The gap between data surprisal, model likelihood, and the model's bound is visible with just two positions. Take V={a,b}V=\{a,b\} and the following data distribution.

Data distribution over the four two-token strings.
StringData mass
aaaa0.50.5
abab0.30.3
baba0.20.2
bbbb00

Use the exact data conditional as each position prediction, then draw positions independently whenever they are revealed in the same step. This specifies the reverse model. For T=2T=2 the reveal probability is 1/21/2 at the first reverse step and 11 at the last. Each position independently has a 1/21/2 chance to reveal at each of these two steps. Thus the probability of a simultaneous reveal is 1/21/2.

  • If the two positions reveal together, the prediction at each is its unconditional marginal. The first position is aa with probability 0.80.8 and the second is aa with probability 0.70.7. The model assigns 0.560.56 to aaaa on these paths.
  • If they reveal separately, the second prediction sees the first token. In either order the chain rule gives the data probability 0.50.5 for aaaa.

The model's probability of aaaa is the average of these two numbers, 0.530.53. Its NLL is −log⁡0.53≈0.63488-\log 0.53 \approx 0.63488. The bound averages negative logs along the paths, yielding [−log⁡0.56−log⁡0.5]/2≈0.63648[-\log 0.56-\log 0.5]/2\approx 0.63648. Data surprisal is −log⁡0.5≈0.69315-\log 0.5\approx 0.69315. For this particular sequence the model has assigned more probability than the data distribution.

Under a linear TT-step schedule each position has a uniform reveal step from 11 through TT, so the probability of collision is 1/T1/T. The calculation extends directly. For bbbb, the model assigns mass (0.2)(0.3)/T=0.06/T(0.2)(0.3)/T=0.06/T. This string has zero data probability.

Let's compute the model NLL and the bound from these paths, then cross-check the bound against the masked loss formula. With aaaa as target, the negative log likelihood for simultaneous paths and both one-at-a-time orders remains finite.

PythonIn [5]
CollapseExpand
import itertools
import math

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_num_threads(1)
torch.manual_seed(0)
np.random.seed(0)

# The toy language: four possible two-token strings, one of them impossible.
STRINGS = [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")]
PRIOR = np.array([0.5, 0.3, 0.2, 0.0])
L_TOY = 2
X0 = ("a", "a")  # the sequence whose likelihood we will bound

The example evaluates one position-factorized reverse model. It predicts each missing token from the exact data marginal conditional on the visible tokens. With both positions masked, those predictions reduce to the prior marginals. When both positions reveal together, independent draws from those marginals can miss their dependence.

PythonIn [6]
CollapseExpand
def population_marginal(mask, position, token, visible=X0):
    compatible = np.array(
        [
            all(mask[j] or state[j] == visible[j] for j in range(L_TOY))
            for state in STRINGS
        ]
    )
    chosen = np.array([state[position] == token for state in STRINGS])
    support = PRIOR[compatible].sum()
    if support == 0:
        raise ValueError("Visible values have zero probability in the toy data")
    return PRIOR[compatible & chosen].sum() / support


def exact_nelbo(T):
    total = 0.0
    for k in range(1, T + 1):
        t = k / T
        for mask in itertools.product([False, True], repeat=L_TOY):
            count = sum(mask)
            pattern_mass = t**count * (1 - t) ** (L_TOY - count)
            if pattern_mass == 0 or count == 0:
                continue
            loss = sum(
                -math.log(population_marginal(mask, i, X0[i]))
                for i in range(L_TOY)
                if mask[i]
            )
            total += pattern_mass * loss / k
    return total

We can compute the model likelihood without sampling. Enumerate both reveal steps for each position, multiply the assigned token probabilities along each path and average the products. The corresponding path bound averages their negative logs.

PythonIn [7]
CollapseExpand
def path_scores(T):
    joint_prob = PRIOR[STRINGS.index(X0)]
    independent_prob = math.prod(
        population_marginal((True, True), i, token)
        for i, token in enumerate(X0)
    )
    path_probabilities = np.array(
        [
            independent_prob if first == second else joint_prob
            for first, second in itertools.product(range(T), repeat=2)
        ]
    )
    return -math.log(path_probabilities.mean()), -np.log(
        path_probabilities
    ).mean()


toy_steps = [1, 2, 4, 8, 16, 32, 64]
sweep = pd.DataFrame(
    [
        {"steps": T, "NLL": path_scores(T)[0], "NELBO": exact_nelbo(T)}
        for T in toy_steps
    ]
)
for row in sweep.itertuples():
    assert math.isclose(row.NELBO, path_scores(row.steps)[1], abs_tol=1e-10)
    assert row.NLL <= row.NELBO + 1e-12
data_surprisal = -math.log(PRIOR[STRINGS.index(X0)])
ConsoleOut [8]
CollapseExpand
Data surprisal of ('a', 'a'): 0.69315 nats
 steps     NLL   NELBO
     1 0.57982 0.57982
     2 0.63488 0.63648
     4 0.66359 0.66482
     8 0.67826 0.67898
    16 0.68568 0.68606
    32 0.68940 0.68961
    64 0.69127 0.69138
VisualizationOut [9]
CollapseExpand
The exact model NLL and dashed negative ELBO curves approach the dotted data surprisal reference from below.
For the string aa, exact model NLL and its negative ELBO approach the data surprisal as simultaneous reveals become less frequent.

At a single step there is only one reveal grouping and the two numbers for the model coincide. At intermediate step counts, paths can assign different probabilities to the same string. The negative ELBO is then above its exact model NLL. Both approach the data surprisal for this string as the chance of a collision goes to zero. The bound gap compares two quantities for the same model. The distance from the data surprisal is a separate comparison.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy