Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python

Patch 0100: the next DFlash2 block pass starts at a decode round's end

BadAd848e6165d0903d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..f71aa08 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,20 @@
Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls
`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.
+## Unreleased
+
+- **The next draft pass starts at a round's end** (patch `0100-glm-draft-prelaunch`, by
+ [BadAd84](https://github.com/BadAd84)): a decode round asked for its DFlash2 drafts only after rank 0 had emitted
+ the last round's tokens, planned the next round and sent its message, so the GPU sat idle meanwhile (an nsys
+ trace on three Sparks: 0.47 ms a round between the taps update and the message gather, 0.74 ms at 4 streams). Now
+ every rank launches the next round's block pass at the end of the round, from state every rank holds (never
+ rank 0's own stop decisions), and the next round waits for it when its streams, pending tokens and contexts
+ match (a context's every change bumps its generation), else runs its own pass. The same inputs give the same
+ candidates: every digest equal, drafted and serial alike. Three Sparks, `PARALLEL=4`: one stream's prose
+ 66.8-67.0 -> 67.9-68.2 tok/s (38.0 -> 37.3 ms a round), code 88.8-91.1 -> 89.2-92.3 (overlapping), four at 596k
+ 133.7-133.9 -> 134.7-134.9; `0092`'s check and retry is kept. `TF_GLM_DRAFT_PRELAUNCH=0` turns it off. GPU check:
+ `tools/draft_prelaunch_check.py`.
+
## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second rail
Image: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on two
diff --git a/CREDITS.md b/CREDITS.md
index 521996e..e5ef94c 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -134,6 +134,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
[BadAd84](https://github.com/BadAd84).
- `0086-glm-prompt-scores-loop` (the prompt scoring, one row and many pool blocks a program): by
[BadAd84](https://github.com/BadAd84).
+- `0100-glm-draft-prelaunch` (the next round's DFlash2 block pass launched at a decode round's end,
+ `TF_GLM_DRAFT_PRELAUNCH`): by [BadAd84](https://github.com/BadAd84).
- `0087-glm-display-kv-dispram` (`DISPLAY_KV_BACKEND=dispram`: `0072`'s display reservation on kindling spark-os): by
[BadAd84](https://github.com/BadAd84). It maps the span through `dispram`, the display-carveout lender of
[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing of
diff --git a/README.md b/README.md
index 2bace9c..580ad56 100644
--- a/README.md
+++ b/README.md
@@ -529,6 +529,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_MULTI_WATCHDOG_S` / `TF_GLM_MULTI_WATCHDOG_EXIT` | `300` / `0` | a rank stuck this many seconds in one step prints every thread's stack to its log (`/health`'s `iteration_s` shows how long the current step has run); `EXIT=1`: the server then exits (code 1) instead of waiting, so a supervisor can restart it. Both ranks also check that they received the same message each step, and stop with an error naming it if not |
| `TF_GLM_CLEAR_THINKING` | `0` | `1`: drop earlier turns' reasoning from the prompt, as the checkpoint's template does (agents then prefill the previous turn's tool loop again); a request's `chat_template_kwargs.clear_thinking` wins |
| `TF_GLM_EFFORT_TAIL` | `0` | `1` (patch `0096`, issue #93, reported by [jdecker76](https://github.com/jdecker76)): render the reasoning-effort line just before `<\|assistant\|><think>` instead of at token 3, so switching effort or thinking on/off keeps the conversation's kept prompt (the reporter measured 0% cached becoming 98%); the model was trained with the line first, so check that Low and High still change the answers before you rely on it (`tools/toolcheck.py`, `tools/end_of_turn.py`). The previous turn's last tokens prefill again |
+| `TF_GLM_DRAFT_PRELAUNCH` | `1` | a decode round's end launches the next round's DFlash2 block pass (patch `0100`); the same drafts and replies either way; `0`: each round runs its own pass when it asks for drafts. Every rank must have the same value (checked at startup) |
| `NUCLEUS_UNION` | `1` | `TENSORFOLD_NUCLEUS_UNION` (patch `0034`): a sampled step with top_p below 1 and top_k off tests the ranks' candidates together for the nucleus, instead of each rank alone (which sent almost every step to a whole-vocabulary CPU sort: ~15 tok/s against greedy's ~58); the same draws, byte for byte (`tools/test_nucleus_union.py`); `0`: stock (issue #91) |
| `TF_GLM_MAX_QUEUED` | unset | admission at saturation (patch `0082`): past the lanes plus this many queued foreground requests, a request is refused with 429 + `Retry-After: 5` instead of queueing; unset queues as every scheduler always has, `0` refuses anything past the lanes (by johnwhited, #48) |
| `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |
@@ -655,6 +656,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Delivery abort | `0083-tfcap-delivery-abort` | a stream whose delivery callback raises (broken pipe, reset, timeout) ends at once and frees its lane, instead of the exception escaping and the lane leaking until generation ends (by johnwhited, #48) | a client that dies mid-reply no longer holds a lane |
| Anthropic Messages | `0084-anthropic-messages` | Anthropic's `/v1/messages` (also `/messages`, with `/count_tokens` suffixes), translated to the same chat completion the OpenAI route serves — text and image blocks, `tool_use` / `tool_result`, thinking, `stop_sequences`, `output_config` effort/JSON schema — with Anthropic SSE streaming and bodies capped at 32 MiB (upstream v0.6.3, by [evilpsycho42](https://github.com/evilpsycho42) and [ashhart](https://github.com/ashhart), request bodies by [Jordi Posthumus](https://github.com/JordiPosthumus); backported by [Eduardo Florencio](https://github.com/eduffd)) | Claude Code and the Anthropic SDKs work against the server directly, without a translating proxy |
| Checked draft candidates | `0092-glm-draft-candidates-checked` | the drafter checks each block pass's candidate ids against the vocabulary; on an id outside it (issue #80: a float's bits read as an id) it logs the value, copies the rows again once the device is idle, and fails only if they are still bad | a rare drafter `IndexError` is retried (and its cause logged) instead of killing a rank |
+| Draft pass ahead | `0100-glm-draft-prelaunch` | a decode round's end launches the next round's DFlash2 block pass, so it runs while rank 0 finishes the round and sends the next message; the next round uses it only when its streams, pending tokens and contexts are the ones it was launched for, else it runs its own; `0092`'s check and retry kept; `TF_GLM_DRAFT_PRELAUNCH=0` turns it off (by [BadAd84](https://github.com/BadAd84)) | the same drafts and replies; three Sparks, one stream: prose 66.8-67.0 -> 67.9-68.2 tok/s (38.0 -> 37.3 ms a round) |
| Spill tier | `0088-glm-spill-tier` | kept prompt states written to local disk on every Spark when they leave the pool (early, in the background, past `SPILL_HIGHWATER`) and read back beside decoding streams, also after a clean restart (`SPILL_GIB`, off by default; authored by Robert Wojciechowski, [wojo](https://github.com/wojo), #78) | [Spill tier](#spill-tier-optional) |
| Kept-state count | `0097-glm-kept-entries-share` | `TF_GLM_CACHE_SHARE_PCT` (the kept-state count as a share of the pool's memory; a ceiling at three quarters of it, so the reservation stays inside the estimate) and the kept states' key arrays built once, not at every admission (issue #84, @jdecker76) |
| Kept-state limits | `0089-glm-kept-state` | `TF_GLM_KEPT_BYTES_GIB` (a byte budget for the kept states, with the freed blocks handed back to the driver) and `TF_GLM_KEEP_PER_CHAT` (a per-conversation quota of turn-boundary states), both off by default; `/health` `kept_bytes`, `kept_mix` (authored by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), #65) | with both at 0, nothing changes |
diff --git a/patches/0100-glm-draft-prelaunch.patch b/patches/0100-glm-draft-prelaunch.patch
new file mode 100644
index 0000000..535d7d0
--- /dev/null
+++ b/patches/0100-glm-draft-prelaunch.patch
@@ -0,0 +1,258 @@
+# The next DFlash2 block pass starts at a decode round's end: MultiDecoder._prelaunch -> MultiDrafter.prelaunch
+# launches the block pass of the streams that will ask for drafts next round, so it runs while rank 0 finishes the
+# round (emit, the next plan, the message all-gather) instead of after it. The next round's candidates() only waits
+# for it when its streams and pending tokens match and none of their contexts changed since (DraftContext.context_end
+# bumps that context's generation; another slot's prompt chunk or admission leaves it valid); else it runs its own
+# pass. The same inputs give the same candidates: the same drafts and replies. The decision reads only state every
+# rank holds (the round's streams, tokens and depths from the gathered samples, context ends), never Stream.done,
+# which rank 0's emit sets alone, so every rank launches the same collectives. Patch 0092's check-and-retry loop is
+# kept: the first copy of the candidates goes out with the pass, the retry copies again. TF_GLM_DRAFT_PRELAUNCH=0
+# turns it off (checked equal on every rank at startup). tools/draft_prelaunch_check.py.
+
+diff --git tensorfold/families/glm5_next/cuda/dflash2_multi.py tensorfold/families/glm5_next/cuda/dflash2_multi.py
+--- tensorfold/families/glm5_next/cuda/dflash2_multi.py
++++ tensorfold/families/glm5_next/cuda/dflash2_multi.py
+@@ -100,8 +100,21 @@ class DraftContext:
+ self.kc = [c[:, slot * cap:(slot + 1) * cap] for c in owner.kc]
+ self.vc = [c[:, slot * cap:(slot + 1) * cap] for c in owner.vc]
+ self.pos_dev = owner.pos[slot:slot + 1] # the device mirror of context_end (restore fills it)
++ self.gen = 0 # bumped by every change of this context (``context_end``)
+ self.context_end = 0
+
++ @property
++ def context_end(self) -> int:
++ return self._end
++
++ @context_end.setter
++ def context_end(self, value: int) -> None:
++ # every change of this stream's context (taps, a restore, a reslot into this slot, a reset, a capture)
++ # goes through here and outdates a block pass of this slot launched ahead (``MultiDrafter.prelaunch``):
++ # a pass reads only its own slots' rings, so another slot's change (a prompt chunk, an admission) does not
++ self._end = value
++ self.gen += 1
++
+ def reset(self) -> None:
+ self.context_end = 0
+ self.pos_dev.zero_()
+@@ -137,6 +150,7 @@ class MultiDrafter:
+
+ def __init__(self, drafter: Drafter, streams: int = 4, *, tap_rows: int | None = None) -> None:
+ d = self.d = drafter
++ self._pre = None # the ``_key`` of the block pass launched ahead (``prelaunch``)
+ if streams < 1:
+ raise ValueError("a multi-stream drafter needs at least one stream")
+ self.streams = streams
+@@ -372,17 +386,26 @@ class MultiDrafter:
+ self._launch_taps(pieces)
+
+ # -- drafts -------------------------------------------------------------------------------------------------
+- @torch.no_grad()
+- def candidates(self, reqs: Sequence[tuple[DraftContext, int, int]]) -> list[tuple[np.ndarray, ...]]:
+- """(stream, pending, depth) -> each stream's ``Drafter.candidates(pending, depth)``: one batched pass."""
+-
+- S, St = len(reqs), self.streams
++ def _check_block(self, ctxs: Sequence[DraftContext]) -> None:
++ S, St = len(ctxs), self.streams
+ if not 1 <= S <= St:
+ raise ValueError(f"a block pass takes 1..{St} streams, got {S}")
+- if len({c.slot for c, _, _ in reqs}) != S or any(c.owner is not self for c, _, _ in reqs):
++ if len({c.slot for c in ctxs}) != S or any(c.owner is not self for c in ctxs):
+ raise ValueError("a block pass takes each of this drafter's streams at most once")
++
++ @staticmethod
++ def _key(reqs: Sequence[tuple]) -> tuple:
++ """A block pass's inputs: its streams in order, their pending tokens and their contexts' generations
++ (a context's end, and the ring rows below it, change only with its generation)."""
++ return tuple((r[0].slot, int(r[1]), r[0].gen) for r in reqs)
++
++ def _launch_block(self, reqs: Sequence[tuple[DraftContext, int]]) -> tuple:
++ """One batched block pass for (stream, pending) and its candidates' copy to ``cand_host`` (``cand_ready``
++ records its end); returns the pass's ``_key``."""
++
++ S, St = len(reqs), self.streams
+ h = self.b_host
+- for s, (c, pending, _) in enumerate(reqs):
++ for s, (c, pending) in enumerate(reqs):
+ h[s], h[St + s], h[2 * St + s] = int(pending), c.slot, c.context_end
+ self.b_meta.copy_(h, non_blocking=True)
+ g = self.block_graphs.get(S)
+@@ -390,16 +413,54 @@ class MultiDrafter:
+ g.replay()
+ else:
+ self._block_compute(S)
++ if self.cand_ready is not None:
++ self.cand_host.copy_(self.cand, non_blocking=True)
++ self.cand_ready.record()
++ else:
++ self.cand_host.copy_(self.cand)
++ return self._key(reqs)
++
++ @torch.no_grad()
++ def prelaunch(self, reqs: Sequence[tuple[DraftContext, int]]) -> None:
++ """Launch now the block pass a later ``candidates`` call will ask for (the next round's, from the
++ end of this one, so it runs while the host finishes the round and rank 0's message goes out). Every rank
++ calls it at the same point with the same streams (its all-gather pairs up). ``candidates`` with the same
++ streams and pending tokens, none of their contexts changed in between (``DraftContext.gen``), only waits for
++ it; any other call runs its own pass. The pass's inputs are the ones ``candidates`` would give it, so its
++ candidates and the drafts chosen from them are the same."""
++
++ if not reqs:
++ return
++ self._check_block([c for c, _ in reqs])
++ if self._pre is not None and self.cand_ready is not None:
++ self.cand_ready.synchronize() # an unused pass ahead still reads b_host
++ self._pre = self._launch_block(reqs)
++
++ @torch.no_grad()
++ def candidates(self, reqs: Sequence[tuple[DraftContext, int, int]]) -> list[tuple[np.ndarray, ...]]:
++ """(stream, pending, depth) -> each stream's ``Drafter.candidates(pending, depth)``: one batched pass (or
++ the one ``prelaunch`` started for exactly these inputs)."""
++
++ S, St = len(reqs), self.streams
++ self._check_block([c for c, _, _ in reqs])
++ key = self._key(reqs)
++ pre, self._pre = self._pre, None
++ if pre != key:
++ if pre is not None and self.cand_ready is not None:
++ self.cand_ready.synchronize() # the unused pass ahead still reads b_host
++ self._launch_block([(c, p) for c, p, _ in reqs])
+ d = self.d
+ m, k = self.block - 1, d.top_k
+ vocab = d.succ.shape[0]
+ for attempt in (0, 1):
+- if self.cand_ready is not None:
+- self.cand_host.copy_(self.cand, non_blocking=True)
+- self.cand_ready.record()
++ if attempt: # (patch 0092) the rows again, copied once the device is idle
++ if self.cand_ready is not None:
++ self.cand_host.copy_(self.cand, non_blocking=True)
++ self.cand_ready.record()
++ else:
++ self.cand_host.copy_(self.cand)
++ if self.cand_ready is not None: # the first copy went out with the pass (``_launch_block``)
+ self.cand_ready.synchronize()
+- else:
+- self.cand_host.copy_(self.cand)
+ g_all = self.cand_host[:d.gathered * S * m * 2 * k].view(d.gathered, S * m, 2 * k)
+ p_all = self.cand_host[self.cand_n:].view(St * m, -1)
+ try:
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -701,6 +701,9 @@ class GlmEngine:
+ wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
+ spare = max(0, min(wanted, plan["budget_bytes"] - plan["total_bytes_estimate"]))
+ self.agreed = mine[:1] + mine[2:] # the spill tier's folders are keyed on these (not the window's slots)
++ from .multi import PRELAUNCH # TF_GLM_DRAFT_PRELAUNCH: every rank alike
++
++ mine = mine + [int(PRELAUNCH)] # checked alike, not in the spill tier's key (``agreed``)
+ rows = self._gather_ints(mine + [spare >> 20])
+ odd = [r for r, row in enumerate(rows) if row[:-1] != rows[0][:-1]]
+ if odd:
+@@ -709,7 +712,8 @@ class GlmEngine:
+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "
+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "
+ "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE / _PROFILE / _WINDOW, "
+- "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV, TF_GLM_ASSISTANT_ENDS): "
++ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV, TF_GLM_ASSISTANT_ENDS, "
++ "TF_GLM_DRAFT_PRELAUNCH): "
+ f"rank 0 {rows[0][:-1]}, " + ", ".join(f"rank {r} {rows[r][:-1]}" for r in odd) +
+ "; pull the draft model on every machine (or pass --drafter none to all) and give "
+ "every rank the same flags")
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -141,6 +141,10 @@ LONE_LEFT = 16 # a lone stream moves home only with a
+ DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons
+ MAX_WINDOW = 32 # rows of every stream's windows together in one round (TF_GLM_MULTI_WINDOW)
+ SHARED_SLOTS = 2 # shared-prefix points an ADMIT carries (engine.SHARED_MOST)
++# TF_GLM_DRAFT_PRELAUNCH (default 1; 0 off, the same drafts and replies either way): a round's end launches
++# the next round's DFlash2 block pass (``MultiDecoder._prelaunch``). Every rank reads it (start.sh forwards TF_GLM_*);
++# ranks that disagree would launch different collectives, so it is read once here and must be set alike everywhere
++PRELAUNCH = __import__("os").environ.get("TF_GLM_DRAFT_PRELAUNCH", "1").strip() != "0"
+
+
+ # -- settings ------------------------------------------------------------------------------------------------------
+@@ -458,6 +462,7 @@ class Lane:
+ copy_rounds: int = 0
+ copy_drafted: int = 0
+ copy_accepted: int = 0
++ next_copy: Any = None # ((copies length, room), proposal, proposed) the round's end worked out
+
+
+ class NoRoom(RuntimeError):
+@@ -2052,7 +2057,6 @@ class MultiDecoder:
+ stream at home, verified through the one-stream graphs when its window fits them. ``short``: between fill
+ slices, commit one token per stream without proposing drafts (the same keyed sample, lower round cost)."""
+
+- from .decode import copy_room
+ from .dflash2_multi import DraftRequest
+
+ if depths is not None and [l.depth for l in lanes] != depths:
+@@ -2063,7 +2067,7 @@ class MultiDecoder:
+ copied: list[bool] = []
+ asks = []
+ for l in lanes:
+- c = l.copies.propose(copy_room(l.copies, l.s.count, l.s.out)) if l.copies is not None and not short else []
++ c = self._copy_proposal(l) if l.copies is not None and not short else []
+ copied.append(bool(c))
+ drafts.append(list(c))
+ if not short and not c and l.dflash and l.depth > 0:
+@@ -2150,11 +2154,57 @@ class MultiDecoder:
+ elif l.policy is not None:
+ l.depth = min(l.policy.next(*((0, 0) if was_copy else (ndrafts, keep - 1))),
+ max(0, s.count - len(s.out)))
++ if not short and PRELAUNCH and self.drafts is not None:
++ self._prelaunch(lanes)
+ if prof is not None:
+ prof.mark("emit")
+ prof.end(len(lanes), sum(len(g.tokens) for g in segments), sum(keeps),
+ sum(len(g.tokens) - 1 for g in segments))
+
++ def _copy_proposal(self, l: Lane) -> list[int]:
++ """``l.copies.propose`` with this round's room. The previous round's end may have worked it out
++ already (``_prelaunch``); with the copies unchanged since (the same length and room) its proposal and
++ ``proposed`` are this call's."""
++
++ from .decode import copy_room
++
++ room = copy_room(l.copies, l.s.count, l.s.out)
++ hit = l.next_copy
++ if hit is not None and hit[0] == (l.copies.length, room):
++ l.copies.proposed = hit[2]
++ return list(hit[1])
++ return l.copies.propose(room)
++
++ def _prelaunch(self, lanes: list[Lane]) -> None:
++ """Both ranks, at the end of a round that was not short: the DFlash2 block pass of the streams that
++ will ask for drafts next round if nothing changes (``MultiDrafter.prelaunch``), so it runs while rank 0
++ finishes the round and sends the next message instead of after. Only state every rank holds decides it -
++ not ``Stream.done``, which rank 0's emit sets alone (a stop string, a cancelled client) - so every rank
++ launches the same pass and its all-gather pairs up. A next round that differs (a stream left, joined or
++ paused, a short round, copied drafts) runs its own pass; the drafts are the same either way."""
++
++ from .decode import copy_room
++
++ reqs = []
++ for l in lanes:
++ s = l.s
++ if not l.dflash or l.depth <= 0 or not s.out or len(s.out) >= s.count or s.out[-1] in self._ends(l):
++ continue
++ ctx = self._ctx(l)
++ if min(l.depth, self.drafts.block - 1) < 1 or ctx.context_end <= 0:
++ continue
++ if l.copies is not None:
++ room = copy_room(l.copies, s.count, s.out)
++ before = l.copies.proposed
++ c = l.copies.propose(room)
++ l.next_copy = ((l.copies.length, room), list(c), l.copies.proposed)
++ l.copies.proposed = before # settled by extend as before (a short round proposes nothing)
++ if c:
++ continue
++ reqs.append((ctx, s.out[-1]))
++ if reqs:
++ self.drafts.prelaunch(reqs)
++
+ def _joint(self, lanes: list[Lane], drafts: list[list[int]], asks: list) -> None:
+ """TF_GLM_MULTI_DEPTH=joint: every asking stream's chain walked to its depth in one block pass, then the
+ round's rows allocated across them by expected tokens per ms (``multi_tune.allocate``). The picks are each
diff --git a/tools/draft_prelaunch_check.py b/tools/draft_prelaunch_check.py
new file mode 100644
index 0000000..423a041
--- /dev/null
+++ b/tools/draft_prelaunch_check.py
@@ -0,0 +1,347 @@
+#!/usr/bin/env python3
+"""tools/draft_prelaunch_check.py: patch 0100 (a round's end launches the next round's DFlash2 block pass), in the
+image with the patch applied, one GPU, one rank (about 30 s on a DGX Spark):
+
+ docker run --rm --gpus all --network none --ipc host -v "$PWD/tools/draft_prelaunch_check.py:/c.py:ro" \
+ --entrypoint python3 tensorfold-glm53:v0.6.0 /c.py
+
+A real dflash2.Drafter over a small random checkpoint (written to a temp dir: hidden 1024, 8 query / 2 KV heads of
+128, MLP 2048, 2 layers, block 8, the production ring), shared by a dflash2_multi.MultiDrafter of 4 streams whose
+contexts get random taps (300 / 517 / 1,024 / 2,500 rows: the last wraps the 2,176-row ring), CUDA graphs captured
+as the engine does. Then:
+ 1. reuse: prelaunch(streams) then candidates(same streams, pending tokens, contexts) returns the arrays a fresh
+ candidates call returns, bit for bit, and launches ONE block pass (``_launch_block`` counted), for 1, 2 and 3
+ streams - with the host copy zeroed and the pass held behind ~30 ms of GPU work, so a candidates that did not
+ wait for the pass ahead reads the zeros;
+ 2. a different next call (another pending token, another stream set, another order) launches its own pass and
+ returns the fresh arrays;
+ 3. a context changed in between - taps committed, or a restore that puts other rows under the SAME context end
+ (multi.put_draft_window) - outdates the pass: candidates launches again and returns the candidates of the new
+ context (which differ from the stale ones); a change of ANOTHER slot's context (taps, a restore) does not: the
+ pass is reused (one launch) and its candidates are a fresh pass's, bit for bit;
+ 4. MultiDecoder._prelaunch decides from state every rank holds: Stream.done set by rank 0's emit alone does not
+ change it; streams at their count, after an end token, with depth 0, without DFlash2 or with copied drafts are
+ left out; the copies' ``proposed`` is left as it was and ``_copy_proposal`` reuses the worked-out proposal only
+ while the copies' length and room are unchanged (else it proposes again); with a real copy_drafts.CopyDrafts the
+ reused proposal and ``proposed`` are what a fresh ``propose`` gives;
+ 5. (with patch 0092's check-and-retry) a torn first copy (ids outside the vocabulary) is copied again from the
+ device and gives a fresh pass's candidates without a second block pass, for an own pass and a pass ahead;
+ 6. TF_GLM_DRAFT_PRELAUNCH is on by default and is one of the settings the engine checks equal on every rank.
+On the image without the patch it fails (the drafter has no ``prelaunch``). Prints a FAIL line per failure (an
+uncaught exception prints one too), exits 1 on any, else ALL PASS."""
+import json
+import os
+import sys
+import tempfile
+import traceback
+from types import SimpleNamespace
+
+sys.excepthook = lambda t, v, tb: (traceback.print_exception(t, v, tb), # a raise is a FAIL line
+ print(f"FAIL raised {t.__name__}: {v}", flush=True))
+
+import numpy as np
+import torch
+from safetensors.torch import save_file
+
+from tensorfold.families.glm5_next.cuda import copy_drafts, dflash2, dflash2_multi, multi
+
+fails = []
+
+
+def fail(msg):
+ fails.append(msg)
+ print("FAIL", msg, flush=True)
+
+
+def check(cond, msg):
+ if not cond:
+ fail(msg)
+
+
+dev = torch.device("cuda")
+torch.manual_seed(87)
+D, H, KV, HD, I, LAYERS, V, RANK = 1024, 8, 2, 128, 2048, 2, 4096, 256
+
+
+def ckpt(path):
+ cfg = {"hidden_size": D, "head_dim": HD, "num_attention_heads": H, "num_key_value_heads": KV,
+ "rms_norm_eps": 1e-5, "rope_parameters": {"rope_theta": 10000.0, "rope_type": "default"},
+ "intermediate_size": I, "num_hidden_layers": LAYERS, "sliding_window": 2048, "is_causal": False,
+ "dflash_config": {"block_size": 8, "conv_group_size": 16, "conv_kernel_size": 2, "mask_token_id": V - 1,
+ "selector_rank": RANK, "selector_top_k": 16, "target_layer_ids": [1, 2, 3, 4, 5]}}
+ open(os.path.join(path, "config.json"), "w").write(json.dumps(cfg))
+
+ def r(*shape, s=0.05):
+ return (torch.randn(*shape) * s).to(torch.bfloat16)
+ t = {"fc.weight": r(D, 5 * D, s=0.02), "hidden_norm.weight": 1 + r(D), "norm.weight": 1 + r(D),
+ "candidate_selector.hidden_projection.weight": r(RANK, D),
+ "candidate_selector.predecessor_codebook": r(V, RANK, s=0.3),
+ "candidate_selector.successor_codebook": r(V, RANK, s=0.3)}
+ for i in range(LAYERS):
+ p = f"layers.{i}."
+ t.update({p + "self_attn.q_proj.weight": r(H * HD, D), p + "self_attn.k_proj.weight": r(KV * HD, D),
+ p + "self_attn.v_proj.weight": r(KV * HD, D), p + "self_attn.o_proj.weight": r(D, H * HD),
+ p + "mlp.gate_proj.weight": r(I, D), p + "mlp.up_proj.weight": r(I, D),
+ p + "mlp.down_proj.weight": r(D, I), p + "attention_conv.base_kernel": r(2, 2, D, s=0.5),
+ p + "mlp_conv.base_kernel": r(2, 2, D, s=0.5),
+ p + "attention_conv.kernel_projection.weight": r(D // 4, D),
+ p + "mlp_conv.kernel_projection.weight": r(D // 4, D),
+ p + "input_layernorm.weight": 1 + r(D), p + "post_attention_layernorm.weight": 1 + r(D),
+ p + "self_attn.q_norm.weight": 1 + r(HD), p + "self_attn.k_norm.weight": 1 + r(HD)})
+ save_file(t, os.path.join(path, "model.safetensors"))
+
+
+tmp = tempfile.mkdtemp(prefix="t87-")
+ckpt(tmp)
+head = dflash2._quantize4((torch.randn(V, D) * 0.05).to(torch.bfloat16).to(dev))
+w = SimpleNamespace(device=dev, rank=0, world=1, comm=None, embed=(torch.randn(V, D) * 0.1).to(torch.bfloat16).to(dev),
+ head=head, draft_head=None, vocab_offset=0)
+d = dflash2.Drafter(tmp, w, capacity=8192, tap_rows=16, ring=True)
+check(d.ring == 2176, f"ring {d.ring}, expected the production 2,176 rows")
+md = dflash2_multi.MultiDrafter(d, streams=4)
+md.capture()
+launches = []
+orig_launch = md._launch_block
+
+
+def counted(reqs):
+ launches.append([c.slot for c, _ in reqs])
+ return orig_launch(reqs)
+
+
+md._launch_block = counted
+ctx = md.contexts
+for c, n in zip(ctx, (300, 517, 1024, 2500)):
+ for start in range(0, n, 64):
+ c.add_taps((torch.randn(min(64, n - start), 5 * D) * 0.5).to(torch.bfloat16).to(dev))
+check([c.context_end for c in ctx] == [300, 517, 1024, 2500], f"context ends {[c.context_end for c in ctx]}")
+
+
+def same(a, b):
+ return all(np.array_equal(x, y) for p, q in zip(a, b) for x, y in zip(p, q)) and len(a) == len(b)
+
+
+def fresh(reqs):
+ md._pre = None
+ return md.candidates(reqs)
+
+
+# 1. reuse
+for reqs in ([(ctx[0], 17, 7)], [(ctx[1], 99, 7), (ctx[3], 5, 4)], [(ctx[0], 3, 7), (ctx[2], 4, 2), (ctx[3], 8, 7)]):
+ ref = fresh(reqs)
+ launches.clear()
+ # the host copy poisoned (zeros: token 0, value 0) and the pass held behind ~30 ms of GPU work: candidates must
+ # wait for the pass ahead (cand_ready) before it reads, else it reads the poison (a fresh pass's identical leftovers
+ # in the buffer would hide a missing wait)
+ md.cand_host.zero_()
+ torch.cuda._sleep(60_000_000)
+ md.prelaunch([(c, p) for c, p, _ in reqs])
+ got = md.candidates(reqs)
+ check(same(got, ref), f"reuse {[c.slot for c, _, _ in reqs]}: candidates differ from a fresh pass's")
+ check(len(launches) == 1, f"reuse {[c.slot for c, _, _ in reqs]}: {len(launches)} block passes, expected 1")
+ check(md._pre is None, "candidates left a pass ahead behind")
+print("1. reuse checked", flush=True)
+
+# 2. a different next call runs its own pass
+base = [(ctx[1], 99, 7), (ctx[3], 5, 4)]
+for name, pre, reqs in (("pending", [(ctx[1], 98), (ctx[3], 5)], base),
+ ("streams", [(ctx[1], 99)], base),
+ ("order", [(ctx[3], 5), (ctx[1], 99)], base)):
+ ref = fresh(reqs)
+ launches.clear()
+ md.prelaunch(pre)
+ got = md.candidates(reqs)
+ check(same(got, ref), f"mismatch ({name}): candidates differ from a fresh pass's")
+ check(len(launches) == 2, f"mismatch ({name}): {len(launches)} block passes, expected 2")
+print("2. mismatches checked", flush=True)
+
+# 3. a changed context outdates the pass
+reqs = [(ctx[2], 41, 7)]
+stale = fresh(reqs)
+launches.clear()
+md.prelaunch([(ctx[2], 41)])
+ctx[2].add_taps((torch.randn(3, 5 * D) * 0.5).to(torch.bfloat16).to(dev))
+got = md.candidates([(ctx[2], 41, 7)])
+check(len(launches) == 2, f"taps after the pass: {len(launches)} block passes, expected 2")
+check(same(got, fresh([(ctx[2], 41, 7)])), "taps after the pass: candidates are not the new context's")
+# a restore under the same context end (other rows): only gen tells
+end = ctx[1].context_end
+rows = multi.draft_window(ctx[1], end)
+ref_old = fresh([(ctx[1], 7, 7)])
+other = [(torch.randn_like(r.float()) * 0.5).to(r.dtype) for r in rows]
+launches.clear()
+md.prelaunch([(ctx[1], 7)])
+multi.put_draft_window(ctx[1], end, other)
+check(ctx[1].context_end == end, "put_draft_window moved the context end")
+got = md.candidates([(ctx[1], 7, 7)])
+check(len(launches) == 2, f"restore under the same end: {len(launches)} block passes, expected 2")
+new = fresh([(ctx[1], 7, 7)])
+check(same(got, new), "restore under the same end: candidates are not the restored context's")
+check(not same(new, ref_old), "the restored rows gave the old candidates (the case cannot tell a stale pass)")
+# a change of another slot's context leaves the pass ahead valid
+reqs = [(ctx[1], 7, 7), (ctx[3], 5, 4)]
+launches.clear()
+md.prelaunch([(c, p) for c, p, _ in reqs])
+ctx[0].add_taps((torch.randn(5, 5 * D) * 0.5).to(torch.bfloat16).to(dev))
+end2 = ctx[2].context_end
+multi.put_draft_window(ctx[2], end2, [(torch.randn_like(r.float()) * 0.5).to(r.dtype)
+ for r in multi.draft_window(ctx[2], end2)])
+got = md.candidates(reqs)
+check(len(launches) == 1, f"other slots changed: {len(launches)} block passes, expected 1 (the pass ahead)")
+check(same(got, fresh(reqs)), "other slots changed: the pass ahead's candidates are not a fresh pass's")
+print("3. outdated passes checked", flush=True)
+
+# 4. MultiDecoder._prelaunch / _copy_proposal decide from replicated state
+EOS = (7,)
+
+
+class Copies:
+ def __init__(self, hit):
+ self.hit, self.length, self.proposed, self.calls = hit, 100, 0, 0
+
+ def propose(self, room):
+ self.calls += 1
+ self.proposed = len(self.hit)
+ return list(self.hit[:max(0, room)])
+
+
+def lane(slot, out, count=50, dflash=True, depth=5, copies=None, done=False, stop_eos=True):
+ s = SimpleNamespace(out=list(out), count=count, stop_eos=stop_eos, done=done)
+ return SimpleNamespace(s=s, slot=slot, dflash=dflash, depth=depth, copies=copies, next_copy=None)
+
+
+fake = SimpleNamespace(drafts=SimpleNamespace(block=8, prelaunch=None, contexts=ctx), eos=EOS)
+fake._ctx = lambda l: ctx[l.slot]
+fake._ends = lambda l: EOS if l.s.stop_eos else ()
+seen = []
+fake.drafts.prelaunch = lambda reqs: seen.append([(c.slot, p) for c, p in reqs])
+
+
+def decide(lanes):
+ seen.clear()
+ multi.MultiDecoder._prelaunch(fake, lanes)
+ return seen[0] if seen else []
+
+
+cp_hit = Copies([11, 12])
+cp_miss = Copies([])
+lanes = [lane(0, [1, 2, 3]), lane(1, [4, 5], done=True), lane(2, [6] * 50), lane(3, [8, 7]),
+ ]
+got = decide(lanes)
+check(got == [(0, 3), (1, 5)], f"_prelaunch picked {got}: expected slots 0 and 1 (2 at its count, 3 after an end "
+ f"token; 1's Stream.done is rank 0's alone)")
+lanes = [lane(0, [1, 2, 3], depth=0), lane(1, [4], dflash=False), lane(2, [6, 9], copies=cp_hit),
+ lane(3, [8, 9], copies=cp_miss)]
+before = (cp_hit.proposed, cp_miss.proposed)
+got = decide(lanes)
+check(got == [(3, 9)], f"_prelaunch picked {got}: expected slot 3 alone (0 depth 0, 1 no DFlash2, 2 copied)")
+check((cp_hit.proposed, cp_miss.proposed) == before, "_prelaunch left the copies' proposed changed")
+check(lanes[2].next_copy is not None and lanes[2].next_copy[1] == [11, 12], "no worked-out copy proposal kept")
+lanes[3].s.done = True
+check(decide(lanes) == [(3, 9)], "Stream.done changed _prelaunch's choice")
+check(decide([lane(3, [8, 7], stop_eos=False)]) == [(3, 7)], "an end token without stop_eos left the stream out")
+# _copy_proposal: reuse while length and room are unchanged, else propose again
+calls = cp_hit.calls
+l2 = lanes[2]
+c = multi.MultiDecoder._copy_proposal(fake, l2)
+check(c == [11, 12] and cp_hit.calls == calls and cp_hit.proposed == 2,
+ f"_copy_proposal did not reuse the worked-out proposal ({c}, calls {cp_hit.calls - calls})")
+decide(lanes)
+cp_hit.length += 3 # extend ran in between
+c = multi.MultiDecoder._copy_proposal(fake, l2)
+check(cp_hit.calls == calls + 2, "_copy_proposal reused a proposal for changed copies")
+decide(lanes)
+l2.s.count -= 1 # another room
+multi.MultiDecoder._copy_proposal(fake, l2)
+check(cp_hit.calls == calls + 4, "_copy_proposal reused a proposal for another room")
+# with a real CopyDrafts in lockstep with an untouched twin (the path without the patch): every round's proposal and
+# ``proposed`` are the twin's, through copied rounds that keep all, keep fewer (``missed``: miss_most) and find none
+import copy as _copy
+
+from tensorfold.families.glm5_next.cuda.decode import copy_room
+
+text = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 3
+real = copy_drafts.CopyDrafts(text, 2, 6, prompt=len(text), miss_most=2)
+twin = _copy.deepcopy(real)
+rl = lane(0, [text[-1]], count=60, copies=real, stop_eos=False) # the text holds the fake end token 7
+seen_kinds, real_calls, real_propose = set(), [0], real.propose
+
+
+def counting_propose(room):
+ real_calls[0] += 1
+ return real_propose(room)
+
+
+real.propose = counting_propose
+for step, keep in enumerate((7, 1, 3, 1, 2, 4, 1)):
+ missed = twin.missed
+ decide([rl])
+ got_c = multi.MultiDecoder._copy_proposal(fake, rl)
+ want = twin.propose(copy_room(twin, rl.s.count, rl.s.out))
+ seen_kinds.add(("missed" if missed else "full") if want else "none")
+ check(got_c == want and real.proposed == twin.proposed,
+ f"real copies round {step}: {got_c} / proposed {real.proposed}, the path without the patch {want} / {twin.proposed}")
+ new = (want + [99])[:keep] if want else [text[step % len(text)]]
+ for c_ in (real, twin):
+ c_.extend(new)
+ rl.s.out += new
+check(real_calls[0] == 7, f"the real copies proposed {real_calls[0]} times in 7 rounds: the round's end's proposal "
+ "was not reused (expected one proposal a round)")
+check(seen_kinds >= {"missed", "full"}, f"the real-copies rounds did not cover a missed and a full proposal: {seen_kinds}")
+print("4. decisions checked", flush=True)
+
+# 5. patch 0092's check-and-retry with the first copy issued beside the pass: a host buffer that
+# reads ids outside the vocabulary after the first copy (a torn copy, simulated) is copied again from the device and
+# gives a fresh pass's candidates, with no second block pass; also for a pass launched ahead
+real_merge = dflash2_multi.merge_candidates
+torn = [0]
+
+
+def tearing_merge(*a, **kw):
+ if torn[0] == 0:
+ torn[0] = 1
+ md.cand_host.fill_(255) # every id 0x437f0000 (255.0's bits): outside the vocabulary
+ return real_merge(*a, **kw)
+
+
+for name, ahead in (("own pass", False), ("pass ahead", True)):
+ reqs = [(ctx[1], 7, 7), (ctx[3], 5, 4)]
+ ref = fresh(reqs)
+ torn[0] = 0
+ launches.clear()
+ if ahead:
+ md.prelaunch([(c, p) for c, p, _ in reqs])
+ else:
+ md._pre = None
+ dflash2_multi.merge_candidates = tearing_merge
+ try:
+ got = md.candidates(reqs)
+ except dflash2.BadCandidates as exc:
+ got = None
+ fail(f"retry ({name}): the second attempt read the torn rows again: {exc}")
+ finally:
+ dflash2_multi.merge_candidates = real_merge
+ check(torn[0] == 1, f"retry ({name}): the first attempt never merged")
+ check(got is not None and same(got, ref), f"retry ({name}): candidates after the retry are not a fresh pass's")
+ check(len(launches) == 1, f"retry ({name}): {len(launches)} block passes, expected 1 (a retry only copies)")
+print("5. retry checked", flush=True)
+
+# 6. the setting: on by default, and checked equal on every rank at startup (ranks that disagree would launch
+# different collectives)
+import ast
+import inspect
+
+from tensorfold.families.glm5_next.cuda import engine
+
+check(multi.PRELAUNCH, "TF_GLM_DRAFT_PRELAUNCH is off in this environment (the check reads the shipped default)")
+src = ast.parse(inspect.getsource(engine))
+gathered = [n for n in ast.walk(src) if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "mine"
+ for t in n.targets) and "PRELAUNCH" in ast.unparse(n.value)]
+check(len(gathered) == 1, f"the engine's rank check does not include TF_GLM_DRAFT_PRELAUNCH ({len(gathered)} sites)")
+check("TF_GLM_DRAFT_PRELAUNCH" in inspect.getsource(engine), "the rank check's message does not name the setting")
+print("6. setting checked", flush=True)
+
+if fails:
+ print(f"{len(fails)} FAILURES")
+ sys.exit(1)
+print("ALL PASS")