GitHub: github.com/atveit/diffusion-picogpt  ·  8×H100 Benchmark Sibling: github.com/atveit/diffusion-nanogpt (Part 2)

diffusion-picogpt overview: bidirectional text unmasking, Lean 4 non-leakage proofs over the BD3-LM block mask, and a single 267 MB INT8 binary file powering 11 languages

In 2007, O'Reilly published Beautiful Code — showing how a short, clear program explains an idea better than a thirty-page spec. Later, Jay Mody did exactly that for GPT-2 with picoGPT: an entire autoregressive Transformer in ~40 lines of pure NumPy.

Now discrete text diffusion is having its moment — from research foundations like MDLM and Block Diffusion to ultra-fast systems like Mercury, Gemini Diffusion, DiffuCoder, and DFlash (see the Appendix for links).

atveit/diffusion-picogpt brings that same Beautiful Code simplicity to discrete text diffusion, with Lean 4 as a modern twist:

  • Pure NumPy reference (diffusion_picogpt.py): zero-PyTorch Masked & Block Diffusion forward pass with a 3-line BD3-LM attention mask.
  • Flagship Lean 4 port (ports/lean4/): native executable inference plus 8 machine-checked non-leakage proofs (zero sorry).
  • 11 languages, 1 binary file: 9 more zero-dependency single-file ports (C99, Rust, Swift 6, Go, TypeScript, C#, Kotlin, Mojo, CUDA) all reading one 267 MB DPIC weight file.

The core forward pass in pure NumPy (and a 3-line block mask)

If you have never worked with diffusion language models before, the easiest mental picture is a mechanical typewriter vs. a crossword puzzle:

  • Classic GPT (Typewriter): writes strictly one word at a time, left to right. It can never skip ahead to write the punchline or fill in a missing middle phrase.
  • Text Diffusion (Crossword Puzzle): starts with blank tiles ([MASK]), looks at clues on both sides at once, locks in the easiest high-confidence words first, and uses those newly revealed words as clues to fill in the trickier blanks over a few parallel rounds.
  • Block Diffusion (B = 16): sits neatly in between — like writing a novel one 16-word block at a time. Completed earlier blocks are locked in ink (so they can be KV-cached), while inside the active block the model still solves multiple blanks in parallel.
How Text Diffusion Inference Works: Classic GPT types one word at a time left-to-right like a typewriter, while Diffusion fills the easiest clues first in parallel like solving a crossword puzzle

To evaluate or train all blocks in parallel in one forward pass, you concatenate [x_noisy, x_clean] into a 2L sequence sharing positions [0..L-1, 0..L-1], and apply a four-quadrant attention mask:

  1. Noisy → Noisy: bidirectional strictly within the same block (bq == bk).
  2. Noisy → Clean: strictly earlier blocks only (bk < bq) — never the current or future block.
  3. Clean → Noisy: completely blocked (zeros).
  4. Clean → Clean: block-causal (bk <= bq).

In diffusion_picogpt.py, that entire BD3-LM mask is three lines of NumPy:

def build_block_mask(seq_len, block_size):
    """Exact (2L, 2L) vectorized BD3-LM mask for concatenated [x_noisy, x_clean]."""
    b = np.arange(seq_len) // block_size
    bq, bk = b[:, None], b[None, :]
    return np.block([[bq == bk, bk < bq], [np.zeros((seq_len, seq_len), dtype=bool), bk <= bq]])

The rest of the forward pass (diffusion_gpt_forward) fits on a single screen and runs both MDLM (x_clean=None) and Block Diffusion (x_clean provided) with zero PyTorch — including the modernized modded-nanogpt backbone pieces (RMSNorm, QK-Norm, half-truncated RoPE, symmetric U-Net residual skips, value embeddings, ReLU² MLP, and logit softcap):

def attention(x, w_qkv, w_proj, n_head, head_dim, positions, scale, attn_mask=None, ve=None, ve_lamb=None):
    """Fused QKV attention with optional value embeddings, QK-Norm, and half-truncated RoPE."""
    T = x.shape[0]
    q, k, v = np.moveaxis((x @ w_qkv.T).reshape(T, 3, n_head, head_dim), 1, 0)
    if ve is not None and ve_lamb is not None:
        v = (1.0 - ve_lamb) * v + ve_lamb * ve.reshape(T, n_head, head_dim)
    q = apply_rope(rms_norm(q), positions).transpose(1, 0, 2)
    k = apply_rope(rms_norm(k), positions).transpose(1, 0, 2)
    scores = (q @ k.swapaxes(-1, -2)) * scale
    if attn_mask is not None:
        scores = np.where(attn_mask, scores, -np.inf)
    return ((softmax(scores) @ v.transpose(1, 0, 2)).transpose(1, 0, 2).reshape(T, n_head * head_dim)) @ w_proj.T
def diffusion_gpt_forward(token_ids, params, cfg, x_clean=None, block_size=None, t=None):
    """Forward pass for MDLM (x_clean=None) or vectorized BD3-LM Block Diffusion."""
    token_ids = np.asarray(token_ids, dtype=np.int64)
    L = len(token_ids)
    if x_clean is not None:
        ids = np.concatenate([token_ids, np.asarray(x_clean, dtype=np.int64)])
        positions, attn_mask = np.concatenate([np.arange(L), np.arange(L)]), build_block_mask(L, block_size)
    else:
        ids, positions, attn_mask = token_ids, np.arange(L), None

    x = rms_norm(params["embed.weight"][ids], params["norm_in.gains"])
    ...
    for i in range(n_layers):
        if n_skips and i >= dec_start:
            x = x + params["skip_weights"][i - dec_start] * skips.pop()
        ve_idx = i if i < n_ve else (n_layers - 1 - i if i >= n_layers - n_ve else None)
        p = f"blocks.{i}"
        x = x + attention(
            rms_norm(x, params[f"{p}.norm1.gains"]), params[f"{p}.attn.qkv.weight"], params[f"{p}.attn.proj.weight"],
            n_head, head_dim, positions, scale, attn_mask,
            ve=ves[ve_idx] if ve_idx is not None else None, ve_lamb=params.get(f"{p}.attn.ve_lamb"),
        )
        x = x + mlp(rms_norm(x, params[f"{p}.norm2.gains"]), params[f"{p}.mlp.fc.weight"], params[f"{p}.mlp.proj.weight"])
        if n_skips and i < n_skips:
            skips.append(x)

    x = rms_norm(x, params["norm_out.gains"])
    logits = (x[:L] if x_clean is not None else x) @ params["lm_head.weight"].T
    cap = float(cfg.get("logit_softcap", 15.0))
    return cap * logits / np.sqrt(logits * logits + cap * cap) if cap > 0 else logits

Live bidirectional infilling on CPU in ~4 seconds

The repo ships real trained weights via Git LFS: weights/block_b16_int8.bin (267 MB, per-row int8 quantized from our 278M-parameter Track 1 Block Diffusion baseline trained in 264 seconds on 8×H100 SXM5, reaching 4.062 FineWeb validation NELBO).

Clone the repo, pull the LFS weights, and run bidirectional fill-in-the-middle infilling right on a laptop CPU (no PyTorch, no GPU):

git lfs pull
pip install numpy tiktoken

python3 diffusion_picogpt.py \
  --weights weights/block_b16_int8.bin \
  --mode infill \
  --prefix "The new album is interesting, but" \
  --suffix "for anyone looking to listen." \
  --mask-len 12 --steps 6 --temperature 0.7 --seed 42

Here is the real output on an Apple Silicon CPU (~4 seconds total):

[step 01/06] The new album is interesting, but it[MASK][MASK][MASK][MASK][MASK][MASK][MASK][MASK][MASK][MASK]for anyone looking to listen.
[step 03/06] The new album is interesting, but it’s not to[MASK][MASK][MASK][MASK][MASK][MASK]for anyone looking to listen.
[step 05/06] The new album is interesting, but it’s not to be[MASK] a[MASK] album—for anyone looking to listen.
[step 06/06] The new album is interesting, but it’s not to be like a new album—for anyone looking to listen.

A 4.4-minute starter checkpoint at 4.062 NELBO is obviously not frontier prose — it is a quick calibration baseline. Even so, you can watch the bidirectional unmasking happen in real time: it does not decode strictly left-to-right. By step 5, it has already placed "album—" right before "for anyone looking to listen.", bridging both ends of the gap simultaneously before filling the remaining interior tokens on step 6.

The modern twist: Lean 4 (executable inference + 8 machine-checked proofs)

If Beautiful Code were written in 2026, it would have a chapter in Lean 4.

In Block Diffusion, the attention mask is security-critical. Think of a 12-story exam hall where every layer of the Transformer is another floor: checking that no student peeks directly at the locked answer sheet on Floor 1 is easy. The sneaky bug is passing a note through a friend — the answer leaks to a helper token on Floor 1, and that helper whispers it to a guess on Floor 2! One off-by-one mistake (≤ instead of <, or forgetting to isolate clean tokens from noisy tokens) silently breaks the model. Unit tests check a few shapes; a formal proof rules out every whisper chain at every sequence length L, every block size B, and every Transformer depth d at once.

Why Formal Proof Matters: The No-Passing-Notes Rule — comparing a sneaky 2-hop leak across Transformer layers against a Lean 4 isolation shield proved for arbitrary depth

ports/lean4/DiffusionPicoGPT.lean does two things in one zero-dependency file (Lean 4.36.0 stdlib only, no Mathlib):

  1. It defines the exact boolean predicate bd3Allows and proves 8 machine-checked theorems over it — with zero sorry, zero custom axioms, and purely constructive proofs (not even Classical.choice).
  2. It compiles to a native binary (lake build) that loads the exact same DPIC .bin file, runs the full DiffusionGPT forward pass over FloatArray, and directly calls that exact proved bd3Allows predicate inside its attention loop.

Here is the formal heart of DiffusionPicoGPT.lean:

def bd3Allows (L B q k : Nat) : Bool :=
  if q < L then
    if k < L then decide (k / B = q / B)
    else decide ((k - L) / B < q / B)
  else
    if k < L then false
    else decide ((k - L) / B ≤ (q - L) / B)

/-- No noisy token can attend to its own or any future clean block. -/
theorem bd3_no_future_clean_leakage (L B q k : Nat)
    (hq : q < L) (hk : k ≥ L) (h : (k - L) / B ≥ q / B) :
    bd3Allows L B q k = false := by
  simp [bd3Allows, hq, Nat.not_lt.mpr hk]; omega

/-- `bd3Allows` is transitive, forming a preorder across token positions. -/
theorem bd3_transitive (L B q m k : Nat)
    (hqm : bd3Allows L B q m = true) (hmk : bd3Allows L B m k = true) :
    bd3Allows L B q k = true := by
  by_cases hq : q < L <;> by_cases hm : m < L <;> by_cases hk : k < L <;>
    simp [bd3Allows, hq, hm, hk] at hqm hmk ⊢ <;> omega

/-- Information flow reachability across `d` stacked Transformer layers. -/
inductive Bd3Reaches (L B : Nat) : Nat → Nat → Nat → Prop where
  | zero (q : Nat) : Bd3Reaches L B 0 q q
  | step {d q m k : Nat} :
      bd3Allows L B q m = true → Bd3Reaches L B d m k → Bd3Reaches L B (d + 1) q k

/-- Arbitrary-depth multi-layer isolation: any key `k` influencing query `q` across `d` layers
    is already permitted in a single layer, ruling out indirect multi-hop leakage. -/
theorem bd3_multilayer_isolation (L B d q k : Nat)
    (hr : Bd3Reaches L B d q k) :
    bd3Allows L B q k = true := by
  induction hr with
  | zero q => exact bd3_always_reflexive L B q
  | step hqm _ ih => exact bd3_transitive L B _ _ _ hqm ih

The key theorem here is bd3_multilayer_isolation. Single-layer mask checks are easy to eyeball; what trips people up in deep Transformers is multi-hop leakage (position q attends to m in layer 2, and m attended to forbidden position k in layer 1). Because bd3Allows is reflexive and transitive, a four-line induction rules out multi-hop leakage at any depth d — whether 12 layers or 1,000.

(Honest scope check, in the spirit of my formal-methods audit post: these 8 theorems certify the discrete attention graph bd3Allows over Nat. They do not formalize IEEE-754 floating-point rounding inside FloatArray or statistical model quality — numerical parity is verified separately against PyTorch down to ~3e-7.)

One binary format (DPIC), 11 languages, 11/11 verified (including live 278M-param runs)

To make cross-language ports clean without dragging JSON, safetensors, or pickle parsers into every language, we defined a tiny 4-byte-aligned little-endian binary format (DPIC v1, exported via tools/export_weights.py): "DPIC" magic, a JSON config header, and a flat list of fp32 or per-row symmetric int8 tensors. Every port under ports/ is a single self-contained file with zero external dependencies that reads the exact same .bin file.

We verified all 11 out of 11 languages against PyTorch DiffusionGPT (via tools/test_parity.py, matching 8/8 argmax in both fp32 and int8), and timed every port live on the full 278M-parameter weights/block_b16_int8.bin checkpoint on an Apple M2 Max (12-core CPU, 32 GB RAM) — plus NVIDIA H100 SXM5 for CUDA:

Language Path fp32 Parity (MDLM / Block) Live 278M-Param Timing (block_b16_int8.bin) Verified Runtime
Python (NumPy) diffusion_picogpt.py 1.79e-06 / 1.67e-06 0.064 s 1-pass compute (0.47 s load) · 0.22 s 4-step (0.87 s 8-step total) Python 3.12 + NumPy / Accelerate BLAS
CUDA C++ ports/cuda/ 3.58e-07 / 3.58e-07 4.04 s total (load + CUDA init + 2 blocks = 32 tokens) nvcc CUDA 13.0 on NVIDIA H100 SXM5
C99 ports/c/ 3.62e-07 / 3.56e-07 2.95 s 1-step · 11.60 s 4-step (2.05e-5 max diff / 1.06M logits) Apple Clang 17 (-O3 -march=native, 1T)
Rust ports/rust/ 3.58e-07 / 3.58e-07 2.98 s 1-step · 11.60 s 4-step (2.48e-5 max diff) rustc 1.86.0 -O (0 warnings, 1T)
Swift 6 ports/swift/ 3.62e-07 / 3.56e-07 3.39 s 1-step · 13.07 s 4-step (2.48e-5 max diff) Swift 6.2.1 (-O, 0 warnings, 1T)
C# (.NET 9) ports/csharp/ 3.58e-07 / 3.58e-07 ~3.4 s/step · 27.43 s 8-step .NET 9.0.107 Release (1T)
Kotlin (JVM) ports/kotlin/ 3.58e-07 / 3.58e-07 3.95 s 1-step · 13.36 s 4-step kotlinc 2.5.0 / OpenJDK 27 (1T)
Go ports/go/ 3.62e-07 / 3.56e-07 4.42 s 1-step · 17.71 s 4-step (2.38e-5 max diff) go build (zero deps, 1T)
TypeScript ports/typescript/ 3.58e-07 / 2.38e-07 ~4.4 s/step · 35.15 s 8-step Node v25.9.0 native TS (1T)
Mojo ports/mojo/ 3.58e-07 / 4.77e-07 ~4.5 s/step · 35.66 s 8-step Mojo 0.25.7 (mojo build, 1T)
Lean 4 (+ 8 proofs) ports/lean4/ 3.29e-07 / 2.19e-07 32.07 s 1-pass on all 278M params (4.42e-6 max diff vs Python!) Lean 4.36.0 (lake build, 0 sorry, 1T)

Two details from running the full 278M-parameter model across all 11 runtimes stood out:

  1. Bit-level cross-language agreement on real English. On the 21-token prompt "The new album is interesting, but[MASK]×8 for anyone looking to listen.", Python, TypeScript, C#, and Mojo all independently generated the exact same 8-step greedy English sentence: "The new album is interesting, but it’s not a good idea for anyone looking to listen." Meanwhile C99, Rust, Swift 6, and Go matched Python 21/21 on 4-step greedy (max_abs_diff ≈ 2e-5 across all 1.06 million output logits), and even Lean 4's pure FloatArray binary ran all 278M parameters in 32.07 s within 4.42e-6 of Python.
  2. Why NumPy is ~45× faster than the compiled ports here. NumPy's 0.064 s pass dispatches every matmul to multi-threaded Apple Accelerate BLAS SGEMM, whereas all ten single-file ports intentionally use readable, zero-dependency, single-threaded nested loops (matching the Beautiful Code goal rather than shipping a hand-tuned BLAS in every language).

Part 2 is live: training it from scratch on 8×H100

Inference is only half the story. Where did that 267 MB block_b16_int8.bin checkpoint come from, and how do you build an honest, ungameable speedrun benchmark for discrete text diffusion that doesn't collapse back into autoregressive GPT?

Read Part 2: Diffusion-NanoGPT — An Open 8×H100 Speedrun Benchmark for Discrete Text Diffusion and check out the open-source repo at atveit/diffusion-nanogpt — featuring a locked stratified NELBO harness, automated anti-leakage canary checks, four public tracks, and our 20M-token data-constrained showdown where autoregressive GPT collapses to perplexity 1,452 while masked diffusion holds steady through 44 epochs.

Appendix: Popular Text Diffusion Models & Further Reading

If you want to explore the broader discrete text diffusion ecosystem — from the papers behind this repo to frontier models and speculative drafters — here is a quick map:

Model / Paper Authors / Org Year Why It Matters Link
MDLM Sahoo et al. (Cornell) 2024 Clean, simple Masked Diffusion LM formulation with continuous-time 1/t NELBO (the Track 2 objective here). arXiv:2406.07524
Block Diffusion (BD3-LMs) Arriola et al. (Cornell) 2025 Interpolates AR and diffusion across blocks (B ≥ 16), unlocking KV-caching and arbitrary-length generation. arXiv:2503.09573
LLaDA (8B) Nie et al. (ML-GSAI) 2025 First 8B-scale masked diffusion LLM trained from scratch competitive with strong autoregressive baselines. arXiv:2502.09992
Dream 7B Ye et al. (HKU NLP) 2025 Open-weight 7B diffusion LLM initialized from AR weights, strong at planning and arbitrary infilling. arXiv:2508.15487
DiffuCoder (7B) Gong et al. (Apple & HKU) 2025 Masked diffusion code model trained with coupled-GRPO, showing how diffusion unlocks parallel code generation. arXiv:2506.20639
Mercury Inception Labs 2025 Commercial diffusion LLMs (Mercury Coder / Mercury 2–3) running >1,000 tok/s on H100s. arXiv:2506.17298 · Site
Gemini Diffusion Google DeepMind 2025 Experimental parallel text diffusion model generating at ~1,470+ tok/s for coding and math. DeepMind
DFlash Chen, Liang & Liu (UCSD) 2026 Uses a lightweight block-diffusion drafter for flash speculative decoding, accelerating standard AR LLMs. arXiv:2602.06036
LLaDA 2.0 / 2.1 (100B MoE) InclusionAI (Ant Group) 2025–2026 Scales discrete diffusion to 100B MoE (2.0) and speeds up parallel text diffusion via token editing (2.1). arXiv:2512.15745 · arXiv:2602.08676
CDLM (Consistent Diffusion LMs) Mahmood et al. (Purdue & Microsoft) 2026 Multi-Path Discrete Consistency (MPDC) for single-stage, teacher-free few-step discrete text diffusion. arXiv:2605.00161
Fast-dLLM++ Kasa, Dai, Negi & Li (Amazon & ANU) 2026 Fréchet Profile Decoding for faster diffusion LLM inference (building on NVlabs' Fast-dLLM v2 block KV caching). arXiv:2606.02955
Unified Discrete Diffusion Yuan et al. (McGill, Mila, Cambridge & UofT) 2026 Comprehensive 2026 synthesis uniting transition-matrix, absorbing/masked, and ratio-based discrete diffusion from tokenization to generation. arXiv:2607.13431
Sigma (Continuous dLMs) NVIDIA, Georgia Tech & Cornell 2026 3B/8B continuous-latent diffusion LLMs using steerable ODE/SDE trajectories and embedding-space CFG for coding & reasoning. arXiv:2610.02665
GameNGen (related) Valevski et al. (Google Research) 2024 Real-time interactive diffusion world model simulating DOOM at 20+ FPS (showing diffusion beyond static images). arXiv:2408.14837

And for the educational inspiration behind this repo's style: Jay Mody's picoGPT and O'Reilly's Beautiful Code.

ℹ️ How this project was made

I built atveit/diffusion-picogpt using Google Antigravity with parallel Gemini agents for the pure-NumPy reference, Lean 4 formal proofs and executable inference, DPIC v1 exporter, and cross-language ports (tested locally on Apple Silicon and on a rented RunPod NVIDIA H100 SXM5 for the CUDA port).

All code, proofs, weights, and parity tests are MIT-licensed. The design choices, claims, and any mistakes are mine.

Best Regard,
Amund