GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
NUCLEUS_UNION=1 by default: default sampling no longer decodes at a third of greedy's speed (issue #91)
MiaAI-Lab3011f22e2ba9
diff --git a/README.md b/README.mdindex d9151fc..7c156a0 100644--- a/README.md+++ b/README.md@@ -527,6 +527,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_GLM_KEEP_PER_CHAT` | `0` (no limit) | at most this many of one conversation's own turn-boundary kept states (patch `0089`, PR #65); shared-prefix and mid-prefill states do not count, the older turns are dropped without a spill. The author runs `2`; `kept_mix` in `/health` shows each conversation's count || `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 |+| `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 || `STREAM_SMOOTH` / `STREAM_SMOOTH_MS` | `1` / `400` | streamed replies go out one token an event at a steady pace from a playout buffer of this many ms, so drafted bursts (~3 tokens every ~50-100 ms) and short pauses do not show; text appears that much later, the reply ends when it did, tool calls keep their place; `0`: one event a round |@@ -636,7 +637,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Drafts | `0007-glm-copy-drafts`, `0032-glm-code-copy-drafts`, `0018-glm-noise-policies`, `0021-glm-dflash-policy-env`, `0025-glm-dflash2-ring` | copy (prompt-lookup) drafts ahead of DFlash2's (`COPY`, `COPY_CODE`); DFlash2 stop rules aware of the sampling noise (`DRAFT_POLICY`); kept prompt states' DFlash2 window with shared prefixes (the ring itself and `TF_GLM_MTP` are TensorFold v0.6.0's; the recipe sets `TF_GLM_MTP=auto`, so the MTP head is not loaded when DFlash2 drafts) | `COPY`: quote / edit replies 80.3 -> 84.4 tok/s; `COPY_CODE`: code 55.4 -> 56.2, edit 120 -> 125; `DRAFT_POLICY` over `fc5:0.3`: prose 47.2 -> 50.6 tok/s, code 51.7 -> 55.5; memory for the window || Drafts, tooling | `0011-glm-draft-sim` | records of DFlash2's drafts for an offline simulator of stop rules (`TF_GLM_DRAFT_DUMP`, off) | how the stop rules were tuned || Concurrent requests | `0026-glm-multi-kda`, `0027-glm-multi-dflash2`, `0029-glm-multi-dsa`, `0030-glm-multi-stream-engine`, `0035-glm-multi-rounds`, `0040-glm-parallel-deadlocks`, `0041-glm-parallel-ring-base`, `0048-glm-timing-tokens`, `0049-glm-multi-prefill`, `0065-glm-rank-checks` | several streams over one shared pool of per-token caches, one batched verify window a round, both ranks kept in step; prompts that arrive together filled in one forward (`MULTI_PREFILL`: 4 prose requests at once 103.4 -> 108.8 tok/s, first token 590 -> 340 ms); a request alone on the one-stream graphs (`TF_GLM_MULTI_LONE=1`, off by default since v1.3.1: +0.6-0.9%); the startup timings of verify windows on distinct tokens | 4 requests at once ([Performance](#performance)) |-| 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 |+| 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`, on in the recipe; `NUCLEUS_UNION=0` turns it off) | default sampling (temperature 1, top_p 0.95) decodes at greedy's pace, not a third of it || 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 as before; 64 by default past 4 requests) and counted at start | 8 at once: +27% prose, +32% code over 4 on two Sparks (+36% / +28% on three); `PARALLEL` 1 to 4 unchanged ([Performance](#performance)) |diff --git a/scripts/config.sh b/scripts/config.shindex 05557ae..83d9f3a 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -225,6 +225,14 @@ export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"# no load balancer in front of it should set a small value (ours: 0, in scripts/local.sh).MAX_QUEUED="${MAX_QUEUED:-}"export TF_GLM_MAX_QUEUED="$MAX_QUEUED"+# Sampled decode with the checkpoint's defaults (temperature 1, top_p 0.95, top_k 0) draws from the top_p nucleus+# (patch 0034). Stock TensorFold tests each rank's candidates alone, which fails on any two ranks whenever both hold+# part of the nucleus, so every such step gathered and sorted the whole vocabulary on the CPU: ~15 tok/s against+# greedy's ~58 on two Sparks (issue #91). NUCLEUS_UNION=1 (the default) tests the ranks' candidates together: the+# same nucleus and the same draw (the merged walk stops above every partial rank's last candidate, so no unsent token+# can be in it; tools/test_nucleus_union.py compares both paths), 42-61 tok/s. A step whose nucleus is still wider+# makes one extra 16,384-candidate gather before the whole shards. 0: stock behaviour. Every rank gets the same value.+export TENSORFOLD_NUCLEUS_UNION="${NUCLEUS_UNION:-${TENSORFOLD_NUCLEUS_UNION:-1}}"# Waiting prompts filled together in one forward (patch 0049): shared work (expert weights, glue, projections) runs once# for every waiting prompt, attention per prompt on its own state, so each gets the bits it gets alone. sparkDash, prose at# 4 at once: 103.4 -> 108.8 tok/s, time to first token 590 -> 340 ms; structured at 3 / 4 at once: 175.2 -> 196.3 anddiff --git a/tools/test_nucleus_union.py b/tools/test_nucleus_union.pynew file mode 100644index 0000000..0d2504e--- /dev/null+++ b/tools/test_nucleus_union.py@@ -0,0 +1,95 @@+"""CPU-only check that TENSORFOLD_NUCLEUS_UNION=1 draws exactly what the default path draws (issue #91).++ python3 -B tools/test_nucleus_union.py --source-root /path/to/patched/src+Needs numpy only (torch is stubbed: the draw itself is numpy). Emulates ``nucleus_rows`` over R ranks' vocabulary+shards the way ``_shares`` builds them, runs the real ``_draw`` with the flag off and on, and compares the token and+its share of the mass over many random rows, ranks 2 to 4, top_p, min_p and tie-heavy distributions.+"""+from __future__ import annotations++import argparse+import os+import sys+import types++import numpy as np+++def load(root):+ sys.path.insert(0, root)+ sys.modules.setdefault("torch", types.ModuleType("torch"))+ from tensorfold.cuda import sampling+ from tensorfold.engine.exact_sampling import Sampling+ return sampling, Sampling+++def shares(sampling, scaled, mass, count, ranks):+ """``_shares`` on numpy: per rank the top ``count`` (value, id, mass) per row, padded, plus shard sums and widths."""++ rows, vocab = scaled.shape+ cuts = np.linspace(0, vocab, ranks + 1).astype(int)+ vs, ids, ms, sums, wid = [], [], [], [], []+ for k in range(ranks):+ lo, hi = cuts[k], cuts[k + 1]+ v, i, m = np.full((rows, count), -np.inf), np.full((rows, count), -1, np.int64), np.zeros((rows, count), np.int64)+ for r in range(rows):+ order = np.lexsort((np.arange(lo, hi), -scaled[r, lo:hi]))[:count] # topk (ties: lowest id first)+ n = len(order)+ v[r, :n], i[r, :n], m[r, :n] = scaled[r, lo:hi][order], order + lo, mass[r, lo:hi][order]+ vs.append(v), ids.append(i), ms.append(m)+ sums.append(mass[:, lo:hi].sum(axis=1)), wid.append(np.full(rows, hi - lo))+ return np.stack(vs), np.stack(ids), np.stack(ms), np.stack(sums), np.stack(wid)+++def nucleus(sampling, scaled, positions, smp, ranks, union):+ os.environ["TENSORFOLD_NUCLEUS_UNION"] = "1" if union else "0"+ top = scaled.max(axis=1)+ mass = np.floor(np.exp(scaled - top[:, None]) * sampling.MASS).astype(np.int64)+ got = shares(sampling, scaled, mass, sampling.NUCLEUS, ranks)+ drawn = sampling._draw(got, positions, smp)+ trips = 1+ if drawn is None and sampling.union_cover() and int(got[4].max()) > sampling.WIDER:+ drawn, trips = sampling._draw(shares(sampling, scaled, mass, sampling.WIDER, ranks), positions, smp), 2+ if drawn is None:+ drawn, trips = sampling._draw(shares(sampling, scaled, mass, int(got[4].max()), ranks), positions, smp), trips + 1+ return drawn, trips+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--source-root", required=True)+ ap.add_argument("--vocab", type=int, default=20000)+ ap.add_argument("--cases", type=int, default=60)+ args = ap.parse_args()+ sampling, Sampling = load(args.source_root)+ rng = np.random.default_rng(7)+ trips_off = trips_on = n = 0+ for case in range(args.cases):+ ranks = int(rng.integers(2, 5))+ kind = case % 5+ logits = rng.normal(size=(3, args.vocab)) * (1.0, 4.0, 0.3, 0.0, 1.0)[kind]+ if kind == 3:+ logits = np.round(logits + rng.normal(size=logits.shape) * 0.0, 0)+ logits[:, rng.integers(0, args.vocab, 8)] = 2.0 # a few tied peaks+ if kind == 0:+ logits[:, :40] += 12.0 # concentrated+ if kind == 4: # ~4000 broad candidates over the ranks+ for r in range(3):+ logits[r, rng.choice(args.vocab, 4000, replace=False)] += 7.0+ temp = float((1.0, 0.7, 1.3)[case % 3])+ top_p = float((0.95, 0.9, 0.6, 0.99)[case % 4])+ min_p = float((0.0, 0.0, 0.05)[case % 3])+ smp = Sampling(int(rng.integers(1, 10**6)), temp, 0, top_p, min_p)+ scaled = logits / temp+ positions = [int(x) for x in rng.integers(0, 10**5, 3)]+ a, ta = nucleus(sampling, scaled, positions, smp, ranks, False)+ b, tb = nucleus(sampling, scaled, positions, smp, ranks, True)+ assert a == b, f"case {case} differs: {a} vs {b}"+ n += len(a)+ trips_off += ta+ trips_on += tb+ print(f"{n} draws identical over {args.cases} cases; gathers off {trips_off}, on {trips_on}")+++if __name__ == "__main__":+ main()