Skip to content

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

Python

v1.5 (unreleased): up to 8 concurrent requests (patch 0069), TF_GLM_MULTI_WINDOW

MiaAI-Lab9a1a8825b7d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b227e41..8d7cb0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,18 @@ Every change to this recipe, newest first. Each release names the image it serve
## v1.5 (unreleased)
+### Added
+- **Up to 8 concurrent requests** (patch `0069-glm-eight-streams`): `PARALLEL` takes 1 to 8 (was 1 to 4; above 1 still
+ needs `DRAFTER=dflash2`); the default stays 4. The batched verify window's segment tables and the segmented kernels'
+ launch grids hold one segment a stream past four (four, as before, up to four streams), and the multi-stream DFlash2
+ drafter, scheduler and startup estimate take 5 to 8 streams. Each stream past the first takes ~210 MiB a Spark at
+ start (~150 MiB at `TP=3`); all of them share the one pool of per-token caches. Replies stay byte-identical to their
+ serial references. Measurements to come.
+- **`TF_GLM_MULTI_WINDOW`** (patch `0069`): the rows of every request's verify window together in a round, 16 to 64 in
+ steps of 8 (default 32, as before), checked to be the same on every rank and counted by the startup estimate (past
+ 48 rows: 64 adds ~250 MiB a Spark). For measuring wider windows with 6 to 8 requests at once; past 32 rows raise
+ `TF_ROCE_MAX_KB` (1024 for 64) to keep a round's all-gathers on RoCE.
+
### Changed
- The README no longer offers the earlier TR3-4bpw checkpoint, and `scripts/config.sh` no longer pins its revision:
the recipe serves `Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold`. (Any `MODEL_ID` still works, without a pin.)
diff --git a/README.md b/README.md
index 22de5ff..f149f14 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through an
OpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image and
video input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.6.0 on both Sparks (one rank on each)
-in NVIDIA's PyTorch container, plus 68 patches (65 of v1.4 and 3 for 3 Sparks, experimental): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,
+in NVIDIA's PyTorch container, plus 69 patches (65 of v1.4, 3 for 3 Sparks, experimental, and 1 for up to 8 requests at once): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,
faster prompt kernels, a one-shot RoCE all-gather between the Sparks, several requests over one shared cache pool,
vision, tool calling, `/tokenize` and `/metrics`.
@@ -363,7 +363,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `MASTER_PORT` | `29551` | the ranks' rendezvous port (keep it on the private link) |
| `TP` / `WORKER2` | `2` / empty | Sparks in all (`2`, or `3` through `./start-tp3.sh`), and the ssh target of rank 2 ([3 Sparks](#3-sparks-experimental)); `FABRIC_PEER2`, `WORKER_HF_CACHE2`, `WORKER_WEIGHTS2`, `NFS_SERVER2` as the worker's own |
| `MASTER_ADDR` / `SOCKET_IFNAME` | see [3 Sparks](#3-sparks-experimental) | the rendezvous address (`TP=2`: the head's address on the link) and, with `TP` above 2, NCCL's bootstrap netdev |
-| `PARALLEL` | `4` (`1` with `DRAFTER=mtp`) | requests decoded together, 1 to 4 (above 1 needs `DRAFTER=dflash2`) |
+| `PARALLEL` | `4` (`1` with `DRAFTER=mtp`) | requests decoded together, 1 to 8 (above 1 needs `DRAFTER=dflash2`; 5 to 8 with patch `0069`, measurements to come); each one past the first takes ~210 MiB a Spark at start (~150 MiB at `TP=3`) and shares the one cache pool |
| `CONTEXT` | `1048576` | prompt + reply window per request (with `KV=fp8`; other defaults in [KV pool and memory](#kv-pool-and-memory)); `0`: the largest that fits |
| `KV` | `fp8` | `fp8` or `bf16` (exact, shorter window) DSA latent cache and indexer keys |
| `WORKER_WEIGHTS` | `copy` | `copy`: the worker keeps its own copy of the weights; `nfs`: it reads the head's over NFS ([Worker weights over NFS](#worker-weights-over-nfs)); with `NFS_PATH`, `NFS_SERVER`, `NFS_VOLUME` |
@@ -385,6 +385,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_EXL3_LOADS` | `nc` | the decode expert kernel's trellis as 16-byte non-coherent loads a step ahead (`nc2` / `nc4`: 2 or 4 steps); `0`: TensorFold's 32-bit loads |
| `TF_ROCE_MAX_KB` | `512` | the largest all-gather (KiB) sent over RoCE with `COMM=roce` (TensorFold's default: 256); 512 covers the 17-32-row verify windows of concurrent requests |
| `TF_ROCE_WAIT_S` | `20` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it |
+| `TF_GLM_MULTI_WINDOW` | `32` | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them; past 48 the startup estimate grows (64: ~250 MiB a Spark), past 32 raise `TF_ROCE_MAX_KB` (1024 for 64) to keep a round's all-gathers on RoCE. Exact at any size |
| `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |
| `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start |
| `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 |
@@ -484,6 +485,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Sampling | `0034-cuda-nucleus-union` | a top_p draw from both ranks' candidates together, the same draw with fewer whole-shard reads (`TENSORFOLD_NUCLEUS_UNION=1`, off by default) | opt-in |
| Server | `0003-glm-vision`, `0050-glm-many-media`, `0056-glm-tool-result-media`, `0036-glm-tool-calls`, `0051-glm-tool-history-recovery`, `0053-glm-whole-tool-calls`, `0055-glm-open-tool-calls`, `0037-cuda-tokenize`, `0023-server-effort-max`, `0057-server-thinking-alias`, `0044-cuda-context-errors`, `0045-cuda-metrics`, `0058-server-client-gone-poll`, `0059-server-refused-bodies`, `0061-server-smooth-stream` | GLM's image and video processors and vision tower; up to 50 pictures and 4 clips a request in 96 MiB bodies, in user messages and tool results; GLM tool calls for agent clients; a past tool call whose arguments are not a JSON object left out of the prompt with its result and logged, instead of HTTP 400 (agents replay history, so a 400 ended the conversation); each call sent whole once written, a call the token limit cuts never sent, one the model ends without `</tool_call>` closed when it parses (else text), a missing `<arg_key>` put back; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; `chat_template_kwargs.thinking` read as `enable_thinking` (from Alexbob0's #25); the `param` field and GLM's own refusals on TensorFold v0.6.0's `context_length_exceeded` errors, and `/health`'s figures in its Prometheus `/metrics`; the client-gone check past 1,023 descriptors (TensorFold PR #218, jayleaton); a refused POST's body read before the reply (TensorFold v0.6.1's #181 fix); smooth streaming from a playout buffer (`STREAM_SMOOTH`) | the API features above |
| 3 Sparks (experimental) | `0066-glm-tp-n`, `0067-glm-tp3-split-pad`, `0068-glm-tpn-split-buffer-rows` | the engine on 2 or 3 ranks (`--tp`): heads, expert columns, vocabulary and DFlash2 KV groups split in whole units, the remainder to the lowest ranks; the row split (`SPLIT`) and its early connection to every peer; RoCE all-gathers over per-peer routes (b12x's proxy modified for more than two Sparks); prompt buffers and the memory estimate hold the split's pad row at three ranks | [3 Sparks](#3-sparks-experimental); two Sparks unchanged |
+| Eight requests at once | `0069-glm-eight-streams` | up to 8 concurrent requests (`PARALLEL` 1 to 8): the batched verify window's segment tables (and the segmented kernels' launch grids) sized for the streams, four as before up to four; the multi-stream DFlash2 drafter, scheduler and memory estimate for 5 to 8 streams; the shared verify window's rows set by `TF_GLM_MULTI_WINDOW` (32 by default, as before) and counted at start | up to 8 requests at once, measurements to come; `PARALLEL` 1 to 4 unchanged |
| Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |
Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token
diff --git a/patches/0069-glm-eight-streams.patch b/patches/0069-glm-eight-streams.patch
new file mode 100644
index 0000000..0c07e28
--- /dev/null
+++ b/patches/0069-glm-eight-streams.patch
@@ -0,0 +1,354 @@
+# 0069-glm-eight-streams: --parallel 1 to 8 for GLM-5.3-Flash (segment tables sized by the streams, four as
+# before up to four) and TF_GLM_MULTI_WINDOW, the shared verify window's rows (default 32), counted at start.
+# MiaAI-Lab, Apache-2.0.
+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
+index 8256956..ce38110 100644
+--- tensorfold/cuda/geometry.py
++++ tensorfold/cuda/geometry.py
+@@ -271,14 +271,17 @@ def even_share(world: int):
+
+ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,
+ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = None, onepass: bool = False,
+- exl3_prompt: bool = True, prompt_split_k: bool = True, kv: str = "bf16", share=None) -> Geometry:
++ exl3_prompt: bool = True, prompt_split_k: bool = True, kv: str = "bf16", share=None,
++ decode_rows: int | None = None) -> Geometry:
+ """GLM's engine: ``mtp`` whether it holds the MTP head's caches and decode buffers (None: when the checkpoint has
+ one; GLM's TF_GLM_MTP can leave it out); ``onepass``: prompt chunks' sparse latent attention keeps no partials
+ (TF_GLM_SPARSE_ONEPASS); an EXL3 checkpoint's ``exl3_prompt``: prompt chunks run the prompt expert kernels
+ (TF_GLM_EXL3_PROMPT: no split-K sums), ``prompt_split_k``: the prompt buffers keep split-K partials for BF16 / FP8
+ projections (``forward.Buffers.sk``); ``kv``: the DSA caches' format (TF_GLM_KV: the latent rows and the
+ indexer's pooled keys; the indexer's per-token keys and gates are bf16 rings); ``share(family, total)``: this
+- rank's share of a split dimension (GLM's ``tp.Layout``: heads, lin, dense, moe, vocab), default ``even_share``."""
++ rank's share of a split dimension (GLM's ``tp.Layout``: heads, lin, dense, moe, vocab), default ``even_share``;
++ ``decode_rows``: the decode windows' rows the buffers are sized for (default MLA_DECODE_ROWS; GLM's --parallel
++ asks for more when its own verify window and the batched one take more together)."""
+ share = even_share(world) if share is None else share
+ linear, attention = layer_counts(t)
+ lin = t.get("linear_attn_config") or {}
+@@ -289,7 +292,8 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+ kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))
+ vd, index = int(t["v_head_dim"]), int(t.get("index_head_dim", 128))
+ mtp = int(t.get("num_nextn_predict_layers", 0)) > 0 if mtp is None else bool(mtp)
+- rows, d, streams = MLA_DECODE_ROWS, int(t["hidden_size"]), int(t.get("hc_mult", 4))
++ rows = MLA_DECODE_ROWS if decode_rows is None else int(decode_rows)
++ d, streams = int(t["hidden_size"]), int(t.get("hc_mult", 4))
+ fixed = linear * (4 * lh * ld * ld * 4 + 3 * (conv - 1) * 3 * lh * ld * 2)
+ fixed += linear * rows * (3 * lh * ld + 2 * ld + lh) * 2
+ fixed += linear * rows * lh * (12 * ld + 4)
+diff --git tensorfold/families/glm5_next/cuda/dflash2_multi.py tensorfold/families/glm5_next/cuda/dflash2_multi.py
+index 10c53b5..702610d 100644
+--- tensorfold/families/glm5_next/cuda/dflash2_multi.py
++++ tensorfold/families/glm5_next/cuda/dflash2_multi.py
+@@ -9,7 +9,7 @@ updates stack every stream's kept rows; each row carries its own position and ri
+
+ API (both ranks call it identically, the same streams in the same order):
+
+- md = MultiDrafter(drafter, streams=4) # drafter: a dflash2.Drafter (its weights are shared)
++ md = MultiDrafter(drafter, streams=8) # drafter: a dflash2.Drafter (its weights are shared)
+ ctx = md.contexts[i] # stream i's DraftContext (duck-types a Drafter's context for
+ # decode.prefill / take_snapshot / restore: add_taps, reset,
+ # context_end, pos_dev, kc, vc, ring, window)
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index a6332ba..64549a8 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -304,10 +304,37 @@ def round_costs(costs: dict) -> tuple[float, ...]:
+ return tuple(v + costs["block"] + 0.0 + costs["taps_row"] * 1 for v in costs["verify"])
+
+
+-PARALLEL_MOST = 4 # --parallel: concurrent requests at most (the segmented kernels' streams)
++PARALLEL_MOST = 8 # --parallel: concurrent requests at most (segments.MAX_SEGS: a window's streams)
+ MULTI_WINDOW = 32 # --parallel: rows of every stream's verify windows together (multi.MAX_WINDOW)
+
+
++def multi_window(value: str | None = None) -> int:
++ """TF_GLM_MULTI_WINDOW: --parallel's shared verify window, the rows of every stream's windows together in a round
++ (the longest tails trimmed past it): 32 (default) or 16 to 64 in steps of 8 (``geometry.MLA_DECODE_ROWS``: the
++ widest decode window the kernels serve). The batched window's buffers, token selection scratch and CUDA graphs (one
++ a row count) are sized for it, and the startup estimate counts them. Past 32 rows a round's all-gathers exceed
++ TF_ROCE_MAX_KB=512 (16 KiB a row) and go through NCCL unless it is raised (1024 for 64 rows)."""
++
++ from tensorfold.cuda.geometry import MLA_DECODE_ROWS
++
++ value = (os.environ.get("TF_GLM_MULTI_WINDOW", "") if value is None else value).strip()
++ if value == "":
++ return MULTI_WINDOW
++ if not value.isdecimal() or not 16 <= int(value) <= MLA_DECODE_ROWS or int(value) % 8:
++ raise ValueError(f"TF_GLM_MULTI_WINDOW: 16 to {MLA_DECODE_ROWS} rows in steps of 8, not {value!r}")
++ return int(value)
++
++
++def multi_decode_rows(parallel: int, window: int, rows: int = MAX_ROWS) -> int:
++ """Decode-window rows the startup estimate sizes buffers for: MLA_DECODE_ROWS, or under --parallel the engine's own
++ window (``rows``: TF_GLM_MAX_ROWS, a lone stream's) and the batched one (``window``) together when they take more
++ (TF_GLM_MULTI_WINDOW past 48 at the default 16 rows; 16 + 32 = 48 fit the 64 rows as ever)."""
++
++ from tensorfold.cuda.geometry import MLA_DECODE_ROWS
++
++ return max(MLA_DECODE_ROWS, int(rows) + int(window)) if parallel > 1 else MLA_DECODE_ROWS
++
++
+ def slot_bytes(t: dict, world: int = 2, rows: int = MAX_ROWS, rank: int = 0) -> int:
+ """What one more stream slot (``forward.Slots``) takes on rank ``rank`` of ``world``, from the text config:
+ every KDA layer's recurrent states (two parities), conv window, a decode window's projections and replay
+@@ -343,8 +370,19 @@ def multi_draft_bytes(t: dict, streams: int, world: int = 2, *, ring: bool, capa
+ window = int(t.get("sliding_window", 0))
+ ring_rows = draft_ring_rows(window - 1, block) if ring and window > 0 else 0
+ cap = ring_rows if 0 < ring_rows < capacity + block else capacity + block
+- trash = -(-max(64, streams * tap_rows) // block) * block
+- return 2 * layers * heads * hd * (streams * cap + trash) * 2
++
++ def update_rows(n: int) -> int: # a context update's rows (MultiDrafter.t_max): the trash
++ return -(-max(64, n * tap_rows) // block) * block
++
++ trash = update_rows(streams)
++ # past four streams (whose blocks and updates the drafter's own 64-row estimate covers): the batched block pass's
++ # activations (dflash2_geometry's 16 fp32 values a row and width) and the context update's tap rows grow too
++ four = min(streams, 4)
++ hidden, inter = int(t.get("hidden_size", 0)), int(t.get("intermediate_size", 0))
++ taps = len((t.get("dflash_config") or {}).get("target_layer_ids") or ()) or 5
++ passes = (16 * (max(64, streams * block) - max(64, four * block)) * (hidden + inter) * 4
++ + (trash - update_rows(four)) * taps * hidden * 2)
++ return 2 * layers * heads * hd * (streams * cap + trash) * 2 + passes
+
+
+ def draft_fraction(draft_dir, rank: int, world: int):
+@@ -462,6 +500,8 @@ class GlmEngine:
+ if not 1 <= parallel <= PARALLEL_MOST:
+ raise ValueError(f"--parallel: 1 to {PARALLEL_MOST} requests at once for GLM-5.3-Flash, not {parallel}")
+ self.parallel = parallel
++ # TF_GLM_MULTI_WINDOW: the rows of a round's shared verify window (--parallel), read on every rank (compared below)
++ self.multi_window = multi_window()
+ self.policy = "0" if serial_only else policy
+ self.serial_only = serial_only
+ self.comm = comm if comm is not None else NCCL(rank, world, master, port)
+@@ -561,12 +601,14 @@ class GlmEngine:
+ g = mla_geometry(text, world, MAX_ROWS, share=share, minimum_slots=DENSE_CAPACITY, latent=LATENT,
+ prefill_rows=prompt_buffer_rows,
+ mtp=self.mtp_on, onepass=SPARSE_ONEPASS, exl3_prompt=prompt_kernels(),
+- prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4", kv=kv)
++ prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4", kv=kv,
++ decode_rows=multi_decode_rows(parallel, self.multi_window))
+ # --parallel: every stream slot past the first (KDA states, conv windows, window scratch); the batched
+- # verify window's buffers fit the decode rows the estimate sizes (MLA_DECODE_ROWS), its token selection's
+- # fp32 scores (MAX_WINDOW rows x a pool of 4 tokens) grow with the pool
++ # verify window's buffers (TF_GLM_MULTI_WINDOW rows) beside the engine's own fit the decode rows the
++ # estimate sizes (``multi_decode_rows``), its token selection's fp32 scores (window rows x a pool of 4
++ # tokens) grow with the pool
+ extra = workspace + (parallel - 1) * (slot_bytes(text, world, rank=rank) + mla_ring_bytes(text, prefill_rows))
+- per = 4 * MULTI_WINDOW // 4 if parallel > 1 else 0
++ per = 4 * self.multi_window // 4 if parallel > 1 else 0
+ if not extra and not per:
+ return g
+ return Geometry(lambda slots: g.bytes_at(slots) + extra + per * slots, g.reserve, g.minimum_slots)
+@@ -607,7 +649,7 @@ class GlmEngine:
+
+ from .sliced_fill import budget_ms
+
+- verify_code = [verify_code] + MultiSettings.from_env().code() + _f64_ints(budget_ms())
++ verify_code = [verify_code] + MultiSettings.from_env().code() + _f64_ints(budget_ms()) + [self.multi_window]
+ else:
+ verify_code = [verify_code]
+ # every rank must run the same calls: refuse to start when they were given different settings
+@@ -628,7 +670,7 @@ class GlmEngine:
+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_KVB, TF_GLM_COPY_*, "
+ "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, "
++ "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): "
+ 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 "
+@@ -770,7 +812,8 @@ class GlmEngine:
+ self.scheduler = GlmScheduler(self.multi, max_streams=parallel)
+ self.concurrent = True
+ print(f"[tensorfold] --parallel {parallel}: up to {parallel} requests decode together, their caches "
+- f"in one pool of {pool_rows} tokens (each up to {self.limit}); DFlash2 drafts, prompt chunks of "
++ f"in one pool of {pool_rows} tokens (each up to {self.limit}), their verify windows "
++ f"{self.multi.window} rows together (TF_GLM_MULTI_WINDOW); DFlash2 drafts, prompt chunks of "
+ f"{self.multi.fill_rows} rows while others decode (TF_GLM_FILL_ROWS, TF_GLM_FILL_SHARE "
+ f"{self.multi.share:g}){'; waiting prompts share prompt chunks (TF_GLM_MULTI_PREFILL)' if self.multi.group else ''}; "
+ f"{self.multi.tune.describe()}"
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index bfc06e2..24d3e6f 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -14,11 +14,12 @@ TF_GLM_MULTI_PREFILL=1 a prompt chunk holds the next rows of several filling str
+ stream's rows get the bits of a chunk of their own; the shortest remaining prompts first, within the same row
+ budget). A round: each
+ decoding stream (admission order) proposes drafts under its own DFlash2 policy (copy drafts first), the combined
+-window is capped at ``MAX_WINDOW`` rows (the longest tails trimmed), one verify over every stream's rows
+-(``forward_streams``: ``verify.BatchedVerify``, one forward over every stream's rows through the segmented KDA and
+-DSA kernels, or ``verify.SerialVerify``, the reference running each window as its own forward; TF_GLM_MULTI_VERIFY),
+-one packed all-gather for the samplers, each stream accepts and commits its own. Between prompt slices, a
+-round takes one token per stream without drafts to keep its latency and the newcomer's inserted work small;
++window is capped at TF_GLM_MULTI_WINDOW rows (``MAX_WINDOW`` by default; the longest tails trimmed), one verify
++over every stream's rows (``forward_streams``: ``verify.BatchedVerify``, one forward over every stream's rows through
++the segmented KDA and DSA kernels, or ``verify.SerialVerify``, the reference running each window as its own
++forward; TF_GLM_MULTI_VERIFY), one packed all-gather for the samplers, each stream accepts and commits its own.
++Between prompt slices, a round takes one token per stream without drafts to keep its latency and the newcomer's
++inserted work small;
+ TF_GLM_FILL_SHARE applies to unsliced fills, slices alternate with these short rounds. Contiguous layer ranges
+ are balanced within the budget without adding rounds; GPU layer cost, finalization and dispatch overhead are
+ learned separately so extra slices cannot inflate every layer cost.
+@@ -134,7 +135,7 @@ def unseal(msg: Sequence[int], seq: int, rank: int = 1) -> list[int]:
+
+ LONE_LEFT = 16 # a lone stream moves home only with at least this many tokens still to go
+ DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons
+-MAX_WINDOW = 32 # rows of every stream's windows together in one round
++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)
+
+
+@@ -384,11 +385,15 @@ class NoRoom(RuntimeError):
+ class MultiDecoder:
+ """The ``GlmScheduler``'s decoder, on rank 0 (deciding) and rank 1 (``follow``, applying)."""
+
++ window = MAX_WINDOW # rows of a round's windows together (TF_GLM_MULTI_WINDOW; set by __init__)
++
+ def __init__(self, engine, streams: int, *, verify=None, drafts=None, draft_graphs: bool | None = None,
+- tune: MultiSettings | None = None, row_ms: Sequence[float] | None = None) -> None:
++ tune: MultiSettings | None = None, row_ms: Sequence[float] | None = None,
++ window: int | None = None) -> None:
+ """``drafts``: the multi-stream drafter (``dflash2_multi.MultiDrafter``; default one over the engine's
+ drafter, its graphs captured unless TF_GLM_MULTI_DRAFT_GRAPHS=0); ``verify``: the verify seam (default
+- ``SerialVerify``)."""
++ ``SerialVerify``); ``window``: the rows of a round's windows together (default the engine's
++ TF_GLM_MULTI_WINDOW, ``engine.multi_window``, else MAX_WINDOW)."""
+ from .engine import DFLASH_POLICY, encode_policy
+
+ self.g = engine
+@@ -398,6 +403,9 @@ class MultiDecoder:
+ self.count = streams
+ if e.slots.count < streams:
+ raise ValueError(f"the engine holds {e.slots.count} stream slots, not {streams}")
++ self.window = int(window if window is not None else getattr(engine, "multi_window", MAX_WINDOW))
++ if self.window < streams:
++ raise ValueError(f"a verify window of {self.window} rows cannot hold {streams} streams' pending tokens")
+ self.rows_max = e.rows # a stream's window (decode.MAX_ROWS)
+ self.pool = Pool(e.caches.rows)
+ self.arena = e.caches.arena
+@@ -431,7 +439,7 @@ class MultiDecoder:
+ if verify is None:
+ if verify_kind() == "batched":
+ taps = engine.drafter.tap_layers if engine.drafter is not None else ()
+- verify = BatchedVerify(e, taps=taps, rows=MAX_WINDOW)
++ verify = BatchedVerify(e, taps=taps, rows=self.window)
+ # TF_GLM_MULTI_GRAPHS=0: eager windows (the same bits); by default a graph a window size
+ if os.environ.get("TF_GLM_MULTI_GRAPHS", "1") != "0" and torch.cuda.is_available():
+ verify.capture()
+@@ -556,7 +564,7 @@ class MultiDecoder:
+ comm.all_gather(vals[:n], allv)
+
+ def _time_rows(self, reps: int = 5) -> list[float]:
+- """TF_GLM_MULTI_DEPTH=joint: the batched window's ms for 1 .. MAX_WINDOW rows (its graphs, fastest of
++ """TF_GLM_MULTI_DEPTH=joint: the batched window's ms for 1 .. its rows (its graphs, fastest of
+ ``reps``), the larger of both ranks' (so both allocate alike)."""
+
+ v = self.verify
+@@ -1469,7 +1477,7 @@ class MultiDecoder:
+ got = self.drafts.propose([a for _, a in asks])
+ for (k, _), d in zip(asks, got):
+ drafts[k] = list(d)
+- drafts = trim(drafts, MAX_WINDOW)
++ drafts = trim(drafts, self.window)
+ if prof is not None:
+ prof.mark("propose")
+ segments = []
+@@ -1564,7 +1572,7 @@ class MultiDecoder:
+ reach.append(reach_of(confs))
+ asked = {k for k, _ in live}
+ fixed = sum(1 + (0 if k in asked else len(d)) for k, d in enumerate(drafts))
+- take = allocate(reach, fixed, self._row_cost, self.tune.overhead_ms, MAX_WINDOW)
++ take = allocate(reach, fixed, self._row_cost, self.tune.overhead_ms, self.window)
+ for (k, _), n in zip(live, take):
+ drafts[k] = drafts[k][:n]
+
+diff --git tensorfold/families/glm5_next/cuda/segments.py tensorfold/families/glm5_next/cuda/segments.py
+index ae8b0d9..b8361aa 100644
+--- tensorfold/families/glm5_next/cuda/segments.py
++++ tensorfold/families/glm5_next/cuda/segments.py
+@@ -15,10 +15,23 @@ import torch
+
+ from .sparse import POOL, SPARSE_FROM, TOKENS, split_scratch
+
+-MAX_SEGS = 4 # streams a window holds
++MAX_SEGS = 8 # streams a window holds at most (--parallel up to engine.PARALLEL_MOST)
++SEGS_DEFAULT = 4 # a window's tables hold at least this many segments: --parallel 2 to 4 keep the four they had
+ EXTENT = 2048 # a stream's extent starts at a multiple of this many tokens (its pooled keys at base / 4)
+
+
++def seg_count(streams: int) -> int:
++ """Segments a batched window's tables (and the launch grids its CUDA graphs capture) hold for ``streams`` stream
++ slots: SEGS_DEFAULT up to four streams (the tables and grids of v1.4), one a stream past that, at most MAX_SEGS.
++ Every segmented kernel loops over the table's segments and skips one of 0 rows, so a larger table only adds
++ programs that exit at once: each segment's bits are those of its stream's window alone at any size."""
++
++ streams = int(streams)
++ if not 1 <= streams <= MAX_SEGS:
++ raise ValueError(f"a batched verify window holds 1 to {MAX_SEGS} streams, not {streams}")
++ return max(SEGS_DEFAULT, streams)
++
++
+ class SegRows:
+ """Device tables of a window of up to ``rows`` rows in up to ``max_segs`` segments, one int32 tensor:
+
+@@ -34,9 +47,11 @@ class SegRows:
+
+ NO_RING = 2 ** 31 - 1 # the kernels' ring size without rings (positions stay below it: base + pos)
+
+- def __init__(self, rows: int, device, max_segs: int = MAX_SEGS, ring: int | None = None) -> None:
++ def __init__(self, rows: int, device, max_segs: int = SEGS_DEFAULT, ring: int | None = None) -> None:
+ if ring is not None and ring < 4:
+ raise ValueError(f"an index ring of {ring} rows")
++ if not 1 <= max_segs <= MAX_SEGS:
++ raise ValueError(f"tables of {max_segs} segments: 1 to {MAX_SEGS}")
+ self.rows, self.max_segs = rows, max_segs
+ self.ring = ring
+ self.ring_rows = ring if ring is not None else self.NO_RING
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 64dbc7c..07dcba8 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -74,14 +74,16 @@ def timing_tokens(vocab: int, n: int) -> list[int]:
+
+
+ class BatchedVerify:
+- """One forward over every segment's rows (``rows`` at most, ``segments.MAX_SEGS`` streams), on buffers of its
+- own; see the module docstring. ``taps``: the drafter's tap layers (DFlash2's inputs), or ()."""
++ """One forward over every segment's rows (``rows`` at most: TF_GLM_MULTI_WINDOW), on buffers of its own; see the
++ module docstring. ``taps``: the drafter's tap layers (DFlash2's inputs), or (); ``segs``: the streams a window
++ holds (its segment tables and the kernels' segment grids; default ``segments.seg_count`` of the engine's stream
++ slots: 4 up to four streams, one a stream up to ``segments.MAX_SEGS``)."""
+
+- def __init__(self, e, *, taps: Sequence[int] = (), rows: int = 32) -> None:
++ def __init__(self, e, *, taps: Sequence[int] = (), rows: int = 32, segs: int | None = None) -> None:
+ from . import kda as kda_mod
+ from . import latent
+ from .forward import Buffers
+- from .segments import MAX_SEGS, SegRows, SelectScratch
++ from .segments import SegRows, SelectScratch, seg_count
+
+ if not latent.ENABLED:
+ raise ValueError("batched verify windows need the latent cache (TF_GLM_LATENT=1)")
+@@ -93,7 +95,8 @@ class BatchedVerify:
+ if taps:
+ self.b.set_taps(tuple(taps), c.hidden)
+ self.taps = bool(taps)
+- self.seg_rows = SegRows(rows, dev, max_segs=MAX_SEGS, ring=e.caches.ring if e.caches.rings else None)
++ self.segs = seg_count(e.slots.count) if segs is None else int(segs)
++ self.seg_rows = SegRows(rows, dev, max_segs=self.segs, ring=e.caches.ring if e.caches.rings else None)
+ self.sel = SelectScratch(rows, e.caches.rows, dev) if e.caches.index is not None else None
+ kda_layers = [l for l in w.layers if l.kind == "kda"]
+ n = len(kda_layers)
+@@ -105,8 +108,8 @@ class BatchedVerify:
+ self.dsa_index = {l.index: i for i, l in enumerate(l for l in w.layers if l.kind == "dsa")}
+ self.proj = torch.zeros((n, rows, width), dtype=torch.bfloat16, device=dev)
+ self.scratch = kda_mod.KDAScratchSet(n, rows, LL, dev) if n else None
+- self.kseg = torch.zeros((MAX_SEGS, kda_mod.SEG_COLS), dtype=torch.int32, device=dev)
+- self.kseg_host = torch.zeros((MAX_SEGS, kda_mod.SEG_COLS), dtype=torch.int32,
++ self.kseg = torch.zeros((self.segs, kda_mod.SEG_COLS), dtype=torch.int32, device=dev)
++ self.kseg_host = torch.zeros((self.segs, kda_mod.SEG_COLS), dtype=torch.int32,
+ pin_memory=torch.cuda.is_available())
+ self.staged = torch.cuda.Event() if torch.cuda.is_available() else None
+ self.segments: list[Segment] = []
diff --git a/scripts/config.sh b/scripts/config.sh
index 0b486a3..f1fc031 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -93,8 +93,10 @@ export TF_GLM_MTP="${TF_GLM_MTP:-auto}"
VISION="${VISION:-1}"
VISION_URLS="${VISION_URLS:-0}"
# Concurrent requests (patches 0026-0030, 0035, 0040, 0041: one shared pool of per-token caches, one batched verify window
-# a round): 1 to 4, with DRAFTER=dflash2 only (mtp: 1). 4 (default), prose in all (sparkDash): 60.4 / 79.2 / 89.5 /
-# 108.8 tok/s at 1 / 2 / 3 / 4 at once; structured 114.7 / 147.6 / 196.3 / 227.9.
+# a round): 1 to 8 (patch 0069: 5 to 8, measurements to come), with DRAFTER=dflash2 only (mtp: 1). 4 (default), prose
+# in all (sparkDash): 60.4 / 79.2 / 89.5 / 108.8 tok/s at 1 / 2 / 3 / 4 at once; structured 114.7 / 147.6 / 196.3 /
+# 227.9. Each stream past the first takes ~210 MiB a Spark at start (its KDA states, index rings and DFlash2 ring;
+# ~150 MiB with TP=3); every stream shares the one pool of per-token caches, so more streams do not grow it.
if [[ "$DRAFTER" == dflash2 ]]; then _par=4; else _par=1; fi
PARALLEL="${PARALLEL:-$_par}"
# The DSA latent cache and the indexer's pooled keys (patch 0038): fp8 (default) holds them as e4m3 rows with a
@@ -172,6 +174,12 @@ export TF_GLM_WIDE_GRAPHS="$_w" TF_GLM_COPY_REPLY_MATCH="$_w"
# kept prompts there, so interactive sessions miss the prompt cache and re-read whole histories (issues #12, #13).
# Off by default until that move keeps them. Exact either way.
export TF_GLM_MULTI_LONE="${TF_GLM_MULTI_LONE:-0}"
+# --parallel: rows of every request's verify window together in a round (patch 0069; TensorFold's TF_GLM_MULTI_WINDOW):
+# 32 (default, as before) or 16 to 64 in steps of 8. With more requests at once each one's drafts get fewer of these
+# rows (8 streams at 32: ~3 drafts each); a wider window verifies more of them a round at a higher round cost. Past 48
+# rows the startup estimate grows (64: ~250 MiB a Spark), and past 32 a round's all-gathers exceed TF_ROCE_MAX_KB=512
+# (16 KiB a row) and go through NCCL unless it is raised (1024 for 64). Measurements to come. Exact at any size.
+export TF_GLM_MULTI_WINDOW="${TF_GLM_MULTI_WINDOW:-32}"
# Kept prompt states (TensorFold's TF_GLM_CACHE_ENTRIES, 8 by default): the oldest is dropped past this count, however
# much of the pool is free. A drafted agent request keeps 1 to 3 (its own plus shared-prefix states), so 8 let three
# or four alternating conversations push each other out (issue #17). Each entry reserves its fixed state (~45 MiB) at
diff --git a/start.sh b/start.sh
index 909e1ab..e0f5c18 100755
--- a/start.sh
+++ b/start.sh
@@ -33,7 +33,8 @@
# FOREGROUND=1 (stay attached to rank 0's log, exit with its code); WAIT_TIMEOUT (seconds, default 1800);
# DRY_RUN=1 (print the docker commands, change nothing);
# STOP_TIMEOUT (stop.sh); LOG_DIR, LOG_KEEP (saved server logs)
-# decode TF_GLM_L2PF (1), TF_GLM_EXL3_LOADS (nc), TF_ROCE_MAX_KB (512), TF_GLM_MULTI_LONE (0)
+# decode TF_GLM_L2PF (1), TF_GLM_EXL3_LOADS (nc), TF_ROCE_MAX_KB (512), TF_GLM_MULTI_LONE (0),
+# TF_GLM_MULTI_WINDOW (32)
# ranks every TENSORFOLD_*, TF_GLM_* and TF_ROCE_* variable goes to every rank (TP>2: TF_ROCE_HCA per node, found),
# e.g.
# TENSORFOLD_GLM_IMAGE_TOKENS, TENSORFOLD_MEMORY_RESERVE_GIB, TF_GLM_KEEP_REASONING=0
@@ -60,7 +61,7 @@ SERVE_ARGS=(--context "$CONTEXT" --parallel "$PARALLEL" --max-tokens "$MAX_TOKEN
check_workers
[[ "$KV" =~ ^(bf16|fp8)$ ]] || die "KV is bf16 or fp8, not $KV"
[[ "$CONTEXT" =~ ^[0-9]+$ && "$CONTEXT" -le 1048576 ]] || die "CONTEXT is a token count up to 1048576 (0: the largest that fits), not $CONTEXT"
-[[ "$PARALLEL" =~ ^[1-4]$ ]] || die "PARALLEL is 1 to 4, not $PARALLEL"
+[[ "$PARALLEL" =~ ^[1-8]$ ]] || die "PARALLEL is 1 to 8, not $PARALLEL"
[[ "$MAX_TOKENS" =~ ^[1-9][0-9]*$ ]] || die "MAX_TOKENS is a token count, not $MAX_TOKENS"
[[ "$DRAFTER" == dflash2 || "$PARALLEL" == 1 ]] || die "PARALLEL=$PARALLEL needs DRAFTER=dflash2 (mtp serves one request at a time: PARALLEL=1)"
for v in SPLIT SHARED_PREFIX KDA_CHUNKED COPY_CODE MULTI_PREFILL STREAM_SMOOTH; do [[ "${!v}" =~ ^[01]$ ]] || die "$v is 0 or 1, not ${!v}"; done
@@ -72,6 +73,7 @@ DRY=0; [[ "${DRY_RUN:-0}" == 1 ]] && DRY=1
[[ "$DRAFT_POLICY" == f* ]] || die "DRAFT_POLICY is a DFlash2 policy (fc5:0.3, fnc7:0.3, fcost7:noisy ...), not $DRAFT_POLICY"
# decode settings the ranks read at load (scripts/config.sh): checked here so a typo fails before anything is stopped
[[ "$TF_GLM_MULTI_LONE" =~ ^[01]$ ]] || die "TF_GLM_MULTI_LONE is 0 or 1, not $TF_GLM_MULTI_LONE"
+[[ "$TF_GLM_MULTI_WINDOW" =~ ^(16|24|32|40|48|56|64)$ ]] || die "TF_GLM_MULTI_WINDOW is 16 to 64 rows in steps of 8, not $TF_GLM_MULTI_WINDOW"
[[ "$TF_GLM_CLEAR_THINKING" =~ ^[01]$ ]] || die "TF_GLM_CLEAR_THINKING is 0 or 1, not $TF_GLM_CLEAR_THINKING"
[[ "$TF_GLM_L2PF" =~ ^(0|off|1|bulk|lines|touch)$ ]] || die "TF_GLM_L2PF is 0, 1 (bulk), lines or touch, not $TF_GLM_L2PF"
[[ "$TF_GLM_EXL3_LOADS" =~ ^(0|ldg|1|nc|nc1|nc2|nc4)$ ]] || die "TF_GLM_EXL3_LOADS is 0, nc, nc2 or nc4, not $TF_GLM_EXL3_LOADS"