Diffusion Language Models › Implementation: A Small Masked Diffusion Language Model

Michael BrenndoerferNovember 17, 202611 min read
Language AI HandbookAll chapters
Part 19 of 67Alternative Sequence and Generative Architectures
Chapter 136Diffusion Language Models › Implementation: A Small Masked Diffusion Language Model
Reading section 10 of 13 · Implementation: A Small Masked Diffusion Language Model · 11 minSection 10 of 13 · 11 min

Section 10 of 13 · 11 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

We now build a complete, if tiny, masked diffusion language model. The corpus is a synthetic grammar with a constraint in it, so that sample quality is measurable rather than a matter of taste.

Sentences have the form DET NOUN VERB DET NOUN ., with six tokens. Determiners come from {the, a} and nouns from {cat, cats, dog, dogs}. The verb agrees in number with the first noun. There are 2×4×1×2×4=642 \times 4 \times 1 \times 2 \times 4 = 64 valid strings among the 128 strings in the positional template. Uniformly choosing the verb within the valid template gives a 50 percent reference rate. The reported validity checks both the template and agreement. A sampler that repeats one valid sentence could score 100 percent, so use separate tests to measure whether it learned a dependency that generalizes.

PythonIn [13]
CollapseExpand
DETS = ["the", "a"]
NOUNS = ["cat", "cats", "dog", "dogs"]
VERB_OF = {"cat": "chases", "dog": "chases", "cats": "chase", "dogs": "chase"}

VOCAB = DETS + NOUNS + ["chases", "chase", "."] + ["[MASK]"]
K = len(VOCAB) - 1  # number of real tokens; the model never predicts [MASK]
MASK_ID = K
SEQ_LEN = 6
stoi = {w: i for i, w in enumerate(VOCAB)}


def make_corpus():
    rows = []
    for d1 in DETS:
        for n1 in NOUNS:
            for d2 in DETS:
                for n2 in NOUNS:
                    rows.append([d1, n1, VERB_OF[n1], d2, n2, "."])
    return torch.tensor([[stoi[w] for w in r] for r in rows])


corpus = make_corpus()
ConsoleOut [14]
CollapseExpand
vocabulary size (real tokens): 9
mask symbol index: 9
corpus size: 64 sentences of length 6
example: the cat chases the cat .

The denoiser is a bidirectional Transformer encoder with a time embedding broadcast to all positions. Its output head has one logit per lexical token. The product structure of the forward and model reverse transitions yields the sum over positions in the KL. Supplying the mask mass from the schedule leaves the revealed lexical distribution as the network's prediction.

PythonIn [15]
CollapseExpand
class Denoiser(nn.Module):
    def __init__(self, n_tokens, seq_len, d=64, heads=4, layers=2, ff=128):
        super().__init__()
        self.tok = nn.Embedding(n_tokens + 1, d)  # +1 for [MASK]
        self.pos = nn.Embedding(seq_len, d)
        self.time = nn.Sequential(nn.Linear(1, d), nn.SiLU(), nn.Linear(d, d))
        self.blocks = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d, heads, ff, dropout=0.0, batch_first=True, norm_first=True
            ),
            layers,
        )
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, n_tokens)

    def forward(self, x, t):
        h = (
            self.tok(x)
            + self.pos(torch.arange(x.shape[1]))
            + self.time(t[:, None])[:, None, :]
        )
        return self.head(self.norm(self.blocks(h)))

Train on the uniform six-position grammar with T=6T=6. Draw kk uniformly from the six steps per sequence and mask each position with probability k/Tk/T. Multiplying the masked cross-entropy by T/kT/k makes the stochastic loss unbiased for the sum over steps. The demonstration trains and evaluates on the same finite support to test the model mechanics.

PythonIn [16]
CollapseExpand
TRAIN_STEPS = 6


def diffusion_loss(model, x0):
    k = torch.randint(1, TRAIN_STEPS + 1, (x0.shape[0],))
    t = k / TRAIN_STEPS
    mask = torch.rand(x0.shape) < t[:, None]
    xt = torch.where(mask, torch.full_like(x0, MASK_ID), x0)
    logp = F.log_softmax(model(xt, t), dim=-1)
    true_logp = logp.gather(-1, x0[..., None]).squeeze(-1)
    return (-(true_logp * mask).sum(-1) / t).mean()

Both training runs use 801 optimizer updates and sample 128 corpus rows per update with replacement. The optimizer-update count is separate from the six denoising steps.

PythonIn [17]
CollapseExpand
model = Denoiser(K, SEQ_LEN)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
running = []

for step in range(801):
    batch = corpus[torch.randint(0, len(corpus), (128,))]
    loss = diffusion_loss(model, batch)
    opt.zero_grad()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    running.append(loss.item())

model.eval()
ConsoleOut [18]
CollapseExpand
training NELBO, first 100 steps: 4.876 nats/sequence
training NELBO, last 100 steps:  4.324 nats/sequence
per token (dividing by L=6): 0.721 nats/token

The displayed loss means describe noisy training batches at two points during optimization. Now inspect the conditional probabilities at individual masked positions.

PythonIn [19]
CollapseExpand
@torch.no_grad()
def inspect(tokens, mask_rate):
    ids = torch.tensor([[stoi[w] for w in tokens]])
    probs = F.softmax(model(ids, torch.tensor([mask_rate])), dim=-1)[0]
    out = []
    for i, w in enumerate(tokens):
        if w == "[MASK]":
            top = probs[i].topk(3)
            picks = ", ".join(
                f"{VOCAB[j]} {p:.2f}" for p, j in zip(top.values, top.indices)
            )
            out.append((i, picks))
    return out


prompt = ["the", "[MASK]", "[MASK]", "a", "[MASK]", "."]
for pos, picks in inspect(prompt, mask_rate=0.34):
    print(f"position {pos}: {picks}")
ConsoleOut [20]
CollapseExpand
prompt: [MASK] cats [MASK] [MASK] [MASK] .
position 0: a 0.56, the 0.44, chases 0.00
position 2: chase 1.00, chases 0.00, cat 0.00
position 3: a 0.55, the 0.45, dogs 0.00
position 4: dog 0.31, cat 0.30, cats 0.23

In the second input, the known subject at zero-based position 1 gives evidence for the plural verb at position 2. The determiner at position 0 is a separate prediction. In this grammar the data sampler picks the determiner independently of the noun.

Compare three ways to choose positions. The Bernoulli rule samples the modeled transition. Fixed-count random and confidence selection choose exactly ⌈n/k⌉\lceil n/k\rceil positions. Confidence here means the probability of the sampled token. The categorical sampler flattens the batch and sequence axes to give one row of probabilities per position.

PythonIn [21]
CollapseExpand
def reveal_positions(masked, confidence, k, order, generator):
    noise = torch.rand(masked.shape, generator=generator)
    if order == "bernoulli":
        return masked & (noise < 1 / k)
    count = torch.ceil(masked.sum(-1) / k).long()
    score = confidence if order == "confidence" else noise
    score = score.masked_fill(~masked, -torch.inf)
    rank = score.argsort(dim=-1, descending=True).argsort(dim=-1)
    return masked & (rank < count[:, None])


@torch.no_grad()
def sample(model, initial, steps, order, seed):
    generator = torch.Generator().manual_seed(seed)
    x = initial.clone()
    for k in range(steps, 0, -1):
        t = torch.full((len(x),), k / steps)
        probs = F.softmax(model(x, t), dim=-1)
        candidates = torch.multinomial(
            probs.reshape(-1, K), 1, generator=generator
        ).reshape_as(x)
        confidence = probs.gather(-1, candidates[..., None]).squeeze(-1)
        reveal = reveal_positions(x == MASK_ID, confidence, k, order, generator)
        x = torch.where(reveal, candidates, x)
    return x

For infilling, keep the subject and punctuation visible. Check that the sampler preserves both tokens and never returns a mask.

PythonIn [22]
CollapseExpand
known = torch.tensor([[stoi[w] for w in prompt2]]).repeat(8, 1)
infilled = sample(model, known, steps=6, order="bernoulli", seed=18)
assert torch.equal(infilled[known != MASK_ID], known[known != MASK_ID])
assert torch.all(infilled != MASK_ID)
ConsoleOut [23]
CollapseExpand
the cats chase the dogs .
a cats chase the cats .
the cats chase a cat .

For unconditional generation start with all masks. Score the positional pattern and subject–verb agreement for every sample.

PythonIn [24]
CollapseExpand
NOUN_IDS = {stoi[w] for w in NOUNS}
DET_IDS = {stoi[w] for w in DETS}
SG_IDS = {stoi["cat"], stoi["dog"]}


def validity_rate(ids):
    """Fraction of samples matching the grammar, including subject-verb agreement."""
    a = ids.numpy()
    pattern = (
        np.isin(a[:, 0], list(DET_IDS))
        & np.isin(a[:, 1], list(NOUN_IDS))
        & np.isin(a[:, 3], list(DET_IDS))
        & np.isin(a[:, 4], list(NOUN_IDS))
        & (a[:, 5] == stoi["."])
    )
    want = np.where(
        np.isin(a[:, 1], list(SG_IDS)), stoi["chases"], stoi["chase"]
    )
    return float((pattern & (a[:, 2] == want)).mean())


configs = [
    ("Bernoulli", "bernoulli"),
    ("Fixed count, random", "random"),
    ("Fixed count, confidence", "confidence"),
]
step_grid = [2, 3, 6, 12]
initial = torch.full((512, SEQ_LEN), MASK_ID, dtype=torch.long)

rows = []
for steps in step_grid:
    for label, order in configs:
        sampled = sample(model, initial, steps=steps, order=order, seed=steps)
        assert torch.all(sampled != MASK_ID)
        rows.append(
            {
                "steps": steps,
                "sampler": label,
                "valid%": 100 * validity_rate(sampled),
            }
        )
results = pd.DataFrame(rows)
ConsoleOut [25]
CollapseExpand
sampler  Bernoulli  Fixed count, confidence  Fixed count, random
steps                                                           
2             75.8                     84.4                 81.4
3             80.7                     98.6                 88.7
6             91.2                    100.0                 98.6
12            96.1                     99.8                 99.4
VisualizationOut [26]
CollapseExpand
Grouped bars show the percentage satisfying the template and agreement by step count and reveal policy.
Percentage of 512 unconditional samples per configuration that match both the synthetic template and subject–verb agreement. Bars compare three reveal policies at four denoising step budgets.

Rows with the same step count use the same denoiser and number of network evaluations. Differences across those rows reflect both the reveal policy and sampling variation. The 12-step run changes the set of times encountered at generation. The figure describes this grammar without measuring wall-clock time.

Likelihood: exact enumeration versus Monte Carlo

Check the bound on the same synthetic distribution in two ways. The exhaustive evaluation sums the expected discrete loss across every mask pattern at each step. The stochastic evaluation samples from that same sum. Both use T=6T=6 for the primary comparison. A causal model trained on the same corpus provides an exact NLL through its left-to-right factorization.

PythonIn [27]
CollapseExpand
SUBSETS = torch.tensor(
    list(itertools.product([False, True], repeat=SEQ_LEN))
)  # (S, L)
N_SUBSETS = SUBSETS.shape[0]


@torch.no_grad()
def nelbo_exact_model(model, x0, steps):
    """Exact discrete-time NELBO with a linear schedule, by enumerating mask patterns."""
    b, L = x0.shape
    total = torch.zeros(b)
    for k in range(1, steps + 1):
        t = k / steps
        q_pattern = torch.tensor(
            [t ** int(s.sum()) * (1 - t) ** (L - int(s.sum())) for s in SUBSETS]
        )
        xt = torch.where(
            SUBSETS.unsqueeze(1),
            torch.full((N_SUBSETS, b, L), MASK_ID),
            x0.unsqueeze(0),
        )
        tt = torch.full((N_SUBSETS * b,), t)
        logp = F.log_softmax(model(xt.reshape(N_SUBSETS * b, L), tt), dim=-1)
        target = (
            x0.unsqueeze(0).expand(N_SUBSETS, b, L).reshape(N_SUBSETS * b, L)
        )
        lp = (
            logp.gather(-1, target.unsqueeze(-1))
            .squeeze(-1)
            .reshape(N_SUBSETS, b, L)
        )
        masked_lp = (lp * SUBSETS.unsqueeze(1).float()).sum(-1)  # (S, B)
        total += (q_pattern.unsqueeze(1) * (-masked_lp)).sum(0) / k
    return total


@torch.no_grad()
def mc_estimates(model, x0, steps, draws=400, seed=0):
    generator = torch.Generator().manual_seed(seed)
    values = []
    for _ in range(draws):
        k = torch.randint(1, steps + 1, (len(x0),), generator=generator)
        t = k / steps
        mask = torch.rand(x0.shape, generator=generator) < t[:, None]
        xt = torch.where(mask, torch.full_like(x0, MASK_ID), x0)
        logp = F.log_softmax(model(xt, t), dim=-1)
        true_logp = logp.gather(-1, x0[..., None]).squeeze(-1)
        estimate = -(true_logp * mask).sum(-1) / t
        values.append(float(estimate.mean() / x0.shape[-1]))
    return np.array(values)

The primary Monte Carlo estimate uses 400 draws. Each averages over the full corpus with a new time and mask for each sequence. The variation across draws estimates uncertainty in the reported mean. The causal baseline shares the main transformer dimensions and uses BOS and a causal attention mask.

PythonIn [28]
CollapseExpand
class ARModel(nn.Module):
    """Causal transformer with the same main block dimensions as the denoiser."""

    def __init__(self, n_tokens, seq_len, d=64, heads=4, layers=2, ff=128):
        super().__init__()
        self.tok = nn.Embedding(n_tokens + 1, d)
        self.pos = nn.Embedding(seq_len, d)
        self.blocks = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d, heads, ff, dropout=0.0, batch_first=True, norm_first=True
            ),
            layers,
        )
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, n_tokens)

    def forward(self, x):
        L = x.shape[1]
        causal = torch.full((L, L), float("-inf")).triu(1)
        h = self.tok(x) + self.pos(torch.arange(L))
        return self.head(self.norm(self.blocks(h, mask=causal)))


BOS_ID = K
ar = ARModel(K, SEQ_LEN)
opt_ar = torch.optim.AdamW(ar.parameters(), lr=3e-3, weight_decay=0.01)

for step in range(801):
    batch = corpus[torch.randint(0, len(corpus), (128,))]
    inp = torch.cat(
        [torch.full((batch.shape[0], 1), BOS_ID), batch[:, :-1]], dim=1
    )
    loss = F.cross_entropy(ar(inp).reshape(-1, K), batch.reshape(-1))
    opt_ar.zero_grad()
    loss.backward()
    opt_ar.step()

ar.eval()
PythonIn [29]
CollapseExpand
with torch.no_grad():
    inp = torch.cat(
        [torch.full((len(corpus), 1), BOS_ID), corpus[:, :-1]], dim=1
    )
    ar_logp = (
        F.log_softmax(ar(inp), dim=-1).gather(-1, corpus[..., None]).squeeze(-1)
    )
ar_nll = float(-ar_logp.sum(-1).mean())

exact_rows = []
for steps in [2, 3, 6, 12, 24]:
    exact_rows.append(
        {
            "steps": steps,
            "NELBO/token": float(nelbo_exact_model(model, corpus, steps).mean())
            / SEQ_LEN,
        }
    )

summary = pd.DataFrame(exact_rows)
mc = mc_estimates(model, corpus, steps=TRAIN_STEPS)
mc_se = mc.std(ddof=1) / math.sqrt(len(mc))
ConsoleOut [30]
CollapseExpand
data entropy (best possible NLL):    4.159 nats/seq   0.693 nats/token
autoregressive exact NLL:            4.166 nats/seq   0.694 nats/token

 steps  NELBO/token
     2        0.763
     3        0.743
     6        0.724
    12        0.714
    24        0.709
Diffusion NELBO, Monte Carlo at T=6: 0.723 nats/token (SE 0.003)
Trainable parameters, denoiser: 72,969
Trainable parameters, AR:       68,681

The entropy floor is log⁡(64)/6≈0.693\log(64)/6\approx0.693 nats per token in expectation under the uniform grammar. For the causal baseline we compute exact cross-entropy on that distribution. For the denoiser we compute an upper bound for the reverse model at each step count. Compare the Monte Carlo estimate with the row at T=6T=6. Their difference is sampling error, with the Monte Carlo standard error as a scale.

Changing TT changes the modeled reverse chain. The table reports a different bound at each budget. Exact likelihood would require summing the reverse path probabilities, as we did for the two-token example.

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