AI/ML Diffusion LLMs MDLM & LLaDA Parallel Decoding PyTorch

Masked Diffusion Language Models (MDLM & LLaDA): Breaking the Autoregressive Token-by-Token Bottleneck


Autoregressive (AR) language models factorize a sequence strictly left-to-right: $P(x_{1:L}) = \prod_{i=1}^L P(x_i \mid x_{\lt i})$. While extraordinarily effective for pretraining, strict causal factorization forces decoding to emit one token per memory-bound forward pass (unless accelerated via Speculative Decoding) and causes the infamous reversal curse where a model trained on "A is B" fails to retrieve "B is A".

Masked Diffusion Language Models (MDLM) (Sahoo et al., 2024, arXiv:2406.07524) and LLaDA 8B (Nie et al., 2025, arXiv:2502.09992) bring continuous-time generative physics from Flow Matching into discrete token space. By defining an absorbing forward Markov chain that independently replaces tokens with [MASK] at probability $t \in [0, 1]$, the entire variational Evidence Lower Bound (ELBO) collapses into a clean, weighted bidirectional cross-entropy loss – unlocking parallel multi-token unmasking and native bidirectional infilling.


0. Continuous-Time Absorbing Diffusion & The Rao–Blackwellized ELBO

In discrete absorbing-state diffusion, let $q(x_t \mid x_0) = \prod_{i=1}^L \mathrm{Cat}\bigl(x_t^{(i)};\, \alpha_t e_{x_0^{(i)}} + (1 - \alpha_t) e_{\text{[MASK]}}\bigr)$ where $\alpha_t \in [0, 1]$ is a monotonically decreasing survival schedule ($\alpha_0 = 1$, $\alpha_1 = 0$). Taking the continuous-time limit ($T \to \infty$) and applying the SUBS parameterization (zeroing out the probability of predicting [MASK] and copying unmasked tokens verbatim) reduces the intractable discrete diffusion ELBO to a single expectation:

MDLM / LLaDA Continuous-Time Masked Diffusion Objective (Sahoo et al., 2024; Nie et al., 2025)
$$-\log p_\theta(x_0) \;\le\; \mathcal{L}_{\text{MDLM}}(\theta) = \mathbb{E}_{t \sim \mathcal{U}(0, 1),\, x_t \sim q(x_t \mid x_0)} \left[ \frac{-\alpha'_t}{1 - \alpha_t} \sum_{i : x_t^{(i)} = \text{[MASK]}} -\log p_\theta\bigl(x_0^{(i)} \mid x_t\bigr) \right]$$ $$\text{Linear Schedule } \alpha_t = 1 - t \;\Longrightarrow\; \mathcal{L}_{\text{LLaDA}}(\theta) = -\mathbb{E}_{t \sim \mathcal{U}(0, 1),\, x_t \sim q_t}\!\left[ \frac{1}{t} \sum_{i=1}^{L} \mathbb{I}\bigl[x_t^{(i)} = \text{[MASK]}\bigr] \log p_\theta\bigl(x_0^{(i)} \mid x_t\bigr) \right]$$

Notice that BERT's static 15% masked language modeling (MLM) is merely a single frozen slice ($t = 0.15$) of this objective! Sampling $t \sim \mathcal{U}(0, 1)$ across the full $[0, 1]$ continuum with the $1/t$ likelihood weight turns a bidirectional encoder into a principled generative language model.

Step t = 1.0 (Full Mask) [M] [M] [M] [M] [M] [M] Non-causal Bidirectional Transformer predicts all L positions simultaneously Step t = 0.5 (Low-Conf Remask) The [M] fox [M] over [M] Commit highest-confidence tokens; remask uncertain positions to avoid collisions Step t = 0.0 (Clean Output) The quick fox jumps over dog 32–64 parallel steps emit 512+ tokens with zero reversal-curse failure
Figure 1: Reverse masked diffusion decoding in MDLM / LLaDA. Instead of sequential left-to-right token generation, the bidirectional Transformer progressively unmasks high-confidence anchor tokens in parallel.
Two Crucial Implementation Details in MDLM & LLaDA: (1) Drop Explicit Timestep Conditioning: Unlike continuous image DiTs, Sahoo et al. (2024) and LLaDA (2025) showed that omitting timestep $t$ embeddings achieves identical or better perplexity because the fraction of [MASK] tokens visible in self-attention already reveals $t$! (2) Low-Confidence Remasking Prevents Multi-Token Collisions: Because each parallel step samples positions conditionally independently given $x_t$, randomly unmasking two adjacent tokens simultaneously can emit incompatible bigrams (e.g., "a apple"). Keeping only the top-confidence unmasked tokens and re-masking the lowest-confidence predictions recovers coherent grammar.

1. Runnable PyTorch Reference: MDLM Continuous-Time Loss & Low-Confidence Remasking Sampler

The self-contained PyTorch script below implements the exact LLaDA / MDLM $1/t$-weighted masked diffusion training loss with SUBS zero-mask-logit clamping and the confidence-guided reverse unmasking loop:

💻 Python: MDLM / LLaDA Training Objective & Low-Confidence Parallel Unmasking SamplerPyTorch
import torch
import torch.nn.functional as F

def mdlm_continuous_loss(model, x0: torch.Tensor, mask_token_id: int, eps: float = 1e-3) -> torch.Tensor:
    """Continuous-time absorbing masked diffusion ELBO (Sahoo et al., arXiv:2406.07524; Nie et al., arXiv:2502.09992)."""
    # x0: [B, L] clean token IDs
    B, L = x0.shape
    t = torch.rand(B, 1, device=x0.device) * (1.0 - eps) + eps  # t ~ U(eps, 1)
    is_masked = torch.rand(B, L, device=x0.device) < t        # Independent masking at rate t
    xt = torch.where(is_masked, torch.full_like(x0, mask_token_id), x0)

    logits = model(xt)                                        # [B, L, V] bidirectional non-causal Transformer
    logits[:, :, mask_token_id] = -1e9                        # SUBS parameterization: never predict [MASK]

    token_ce = F.cross_entropy(logits.reshape(-1, logits.size(-1)), x0.reshape(-1), reduction="none").view(B, L)
    # Exact 1/t continuous-time ELBO weighting strictly over masked positions
    weighted_loss = (token_ce * is_masked.float() / t).sum() / (B * L)
    return weighted_loss

@torch.no_grad()
def sample_low_confidence_remasking(model, seq_len: int, mask_token_id: int, steps: int = 16, device: str = "cpu") -> torch.Tensor:
    """Iterative parallel unmasking keeping highest-confidence tokens at each reverse diffusion step."""
    x = torch.full((1, seq_len), mask_token_id, dtype=torch.long, device=device)
    for s in range(steps, 0, -1):
        logits = model(x)
        logits[:, :, mask_token_id] = -1e9
        probs = F.softmax(logits, dim=-1)
        conf, pred_ids = probs.max(dim=-1)                    # [1, L] top token & confidence
        # Only consider currently masked positions; lock already-unmasked tokens with inf confidence
        still_masked = (x == mask_token_id)
        x_cand = torch.where(still_masked, pred_ids, x)
        conf_eff = torch.where(still_masked, conf, torch.full_like(conf, float("inf")))
        # Remask the lowest-confidence fraction (s - 1) / steps for the next refinement pass
        n_remask = int(seq_len * (s - 1) / steps)
        if n_remask > 0:
            low_idx = torch.topk(conf_eff, k=n_remask, largest=False, dim=-1).indices
            x_cand.scatter_(1, low_idx, mask_token_id)
        x = x_cand
    return x

if __name__ == "__main__":
    t_vals = torch.tensor([0.1, 0.5, 0.9])
    print(f"[PASS] MDLM Continuous ELBO Weights (1/t at t=0.1, 0.5, 0.9): {[round(w, 2) for w in (1.0 / t_vals).tolist()]}")
# Output:
# [PASS] MDLM Continuous ELBO Weights (1/t at t=0.1, 0.5, 0.9): [10.0, 2.0, 1.11]

2. Autoregressive vs. Masked Diffusion LLMs: Head-to-Head

Dimension Autoregressive Transformer (Llama-3) Masked Diffusion LLM (MDLM / LLaDA, arXiv:2502.09992)
Attention Mask Causal lower-triangular ($O(1)$ incremental KV-cache) Full bidirectional (no KV-cache without block-diffusion)
Tokens Emitted per Forward Pass Strictly 1 token (unless using Speculative Decoding) Arbitrary $K$ tokens in parallel (tunable quality/speed trade-off)
Reversal Curse & Fill-in-the-Middle Requires FIM training; fails reversal retrieval Native bidirectional infilling; solves reversal tasks out-of-the-box