GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0098: kindling spark-os - the server starts (the drafter and vision tower load out of the mmap)
BadAd84ec7f9ea8497a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54a3f69..34cd131 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,16 @@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++- **kindling spark-os: the server starts** (patch `0098-glm-mmap-uploads`, by [BadAd84](https://github.com/BadAd84)):+ on kindling's 64 KiB-page kernel a pageable copy to the GPU straight from a safetensors mmap hangs in the driver+ (`cuMemcpyHtoDAsync`) once the process holds GPU memory, and the DFlash2 drafter and the GLM vision tower load+ after the main weights. v1.10 on three Sparks with kindling spark-os 0.9.5 stopped after the drafter timings (no+ vision line for 15 minutes, every rank spinning); with the patch it serves in 145 s. Both loaders now copy each+ tensor out of the mmap first (`.clone()`): the same bytes, one host copy a tensor at start; the main weights use+ direct reads and never had the problem. CPU check: `tools/mmap_upload_check.py` (fails on the unpatched loaders).+## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second railImage: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on twodiff --git a/CREDITS.md b/CREDITS.mdindex 521996e..187fb08 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -139,6 +139,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing ofdispram ships here: the ranks import the host's client (`python/dispram.py`, GPL-3.0 with a bundling exception)mounted read-only at run time and talk to `dispramd` (AGPL-3.0) over its socket.+- `0098-glm-mmap-uploads` (the drafter's and the vision tower's tensors copied out of the safetensors mmap before+ they go to the GPU: kindling spark-os's 64 KiB-page kernel): by [BadAd84](https://github.com/BadAd84).- `0090-glm-expert-launch-order` (`TF_GLM_EXL3_DEC_ORDER`: the launch order of the expert decode kernel's blocks): byLukasz Raczylo ([lukaszraczylo](https://github.com/lukaszraczylo)), in[PR #95](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/95).diff --git a/README.md b/README.mdindex 2bace9c..8458155 100644--- a/README.md+++ b/README.md@@ -295,6 +295,10 @@ DRM path has no dumb buffers (`CREATE_DUMB` fails ENOSYS), and kindling's `dispr`DISPLAY_KV_BACKEND=dispram` (patch 0087) maps the same span through it (`dispram.map_glued`: ordinary device memorywith the reservation's slice right above it, one virtual range). `start.sh` checks the daemon's socket and client andmounts both into every rank. 2032 MiB, measured on three Sparks at `PARALLEL=4`: +317,440 pool tokens.+kindling's kernel also uses 64 KiB pages, where a pageable copy to the GPU straight from a safetensors mmap hangs+in the driver once the process holds GPU memory; the DFlash2 drafter and the vision tower load after the main+weights, so patch 0098 copies each of their tensors out of the mmap first (without it the server never finishes+starting there). Nothing to set.On the Spark's unified memory, running out tends to freeze the machine rather than fail an allocation. A setting thatdoes not fit is refused before any weights load, with the largest window that fits; `start.sh` then restarts oncewith that window and says so (free memory on both Sparks for the full one). Other settings' windows:@@ -624,6 +628,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Weights | `0002-glm-dense-fp8`, `0005-glm-dense-q4` | the checkpoint's BF16 dense weights in FP8, or 4-bit with MSE-searched ranges (`DENSE`) | q4 over fp8: prose 38.9 -> 44.4 tok/s, code 44.2 -> 48.7, prefill ~1,090 -> ~1,260 tok/s || KV cache | `0038-glm-kv-fp8` | the DSA latent cache and the indexer's pooled keys as FP8 rows (`KV=fp8`) | the 1M window with 4 requests fits || KV pool | `0072-glm-display-kv` | the first DSA latent planes in a span ending in the GPU's display reservation, which `MemAvailable` does not count; the pool's row copies of those planes by a kernel (a memcpy may not cross the span's two registrations) (`DISPLAY_KV_MIB`, by ezoushen) | 1792 MiB: ~277k more tokens at `PARALLEL=8`; the same bits, decode and prefill |+| Loads, kindling | `0098-glm-mmap-uploads` | the DFlash2 drafter's and the vision tower's loaders copy each tensor out of the safetensors mmap before it goes to the GPU: on kindling spark-os's 64 KiB-page kernel a pageable copy straight from a file mmap hangs in the driver once the process holds GPU memory (by [BadAd84](https://github.com/BadAd84)) | kindling: the server starts (it stopped after the drafter timings); elsewhere the same bytes, one host copy a tensor at start || KV pool, kindling | `0087-glm-display-kv-dispram` | `0072`'s span with its reservation half from kindling spark-os's `dispramd` instead of a DRM dumb buffer, which kindling's `nvidia_drm` (no modeset) cannot make; the rest of `0072` runs unchanged (`DISPLAY_KV_BACKEND=dispram`) (by [BadAd84](https://github.com/BadAd84)) | 2032 MiB: +317,440 tokens at `PARALLEL=4` on three Sparks; the display check 53/53 || Prompt | `0001-glm-exl3-prompt-experts`, `0004-glm-prompt-kernels`, `0009-glm-prefill-kernels`, `0020-glm-prompt-experts-order`, `0024-glm-prompt-select-rows`, `0028-glm-lean-prompt-scratch` | EXL3 expert kernels that keep a prompt chunk's rows in L2, launched in a better order; each row's input rotated once; dense attention only where the sparse pass needs it; token selection in blocks of 512 rows; smaller prompt scratch | faster prefill, less memory at 1M || Prompt, indexer | `0086-glm-prompt-scores-loop` | a prompt chunk's indexer scoring (`0009`'s `_scores`) takes one row and 32 pool blocks a program (`SCORE_LOOP`), the row's queries loaded once, instead of 4 rows and one block (`TF_GLM_SCORE_RB`, retired), which reloaded every row's queries for each 64-pool block (by [BadAd84](https://github.com/BadAd84)) | the scoring 36% faster at long context (the part of a cold prefill that grows with it); cold prefill at 226k 138.3 -> 126.6 s; the same bits |diff --git a/patches/0098-glm-mmap-uploads.patch b/patches/0098-glm-mmap-uploads.patchnew file mode 100644index 0000000..926b5b8--- /dev/null+++ b/patches/0098-glm-mmap-uploads.patch@@ -0,0 +1,31 @@+# kindling spark-os: the DFlash2 drafter's and the GLM vision tower's loaders copy each tensor out of the safetensors+# mmap before it goes to the GPU. On kindling's 64 KiB-page kernel a pageable copy to the GPU straight from a file mmap+# hangs in the driver (cuMemcpyHtoDAsync) once the process holds GPU memory, and both loaders run after the main+# weights: the server never finished starting (the vision tower's first upload, after the drafter timings, on three+# Sparks; the drafter's first upload in an earlier recipe). A clone is an ordinary host buffer: the same bytes, one+# copy per tensor at start. The main weights use direct reads and are unaffected. tools/mmap_upload_check.py.++diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py+--- tensorfold/families/glm5_next/cuda/dflash2.py++++ tensorfold/families/glm5_next/cuda/dflash2.py+@@ -274,7 +274,7 @@ class Drafter:++ with safe_open(str(path / "model.safetensors"), framework="pt", device="cpu") as f:+ def get(name: str) -> torch.Tensor:+- return f.get_tensor(name)++ return f.get_tensor(name).clone()++ self.fc = quantize4(gpu(get("fc.weight")))+ self.hidden_norm = gpu(get("hidden_norm.weight"))+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py+--- tensorfold/vision/glm.py++++ tensorfold/vision/glm.py+@@ -347,7 +347,7 @@ class GlmVisionTower:+ with safe_open(str(model_dir / file), framework="pt", device="cpu") as f:+ for n in names:+ if index[n] == file:+- t[n[len("model.visual."):]] = f.get_tensor(n).to(device=device, dtype=torch.bfloat16)++ t[n[len("model.visual."):]] = f.get_tensor(n).clone().to(device=device, dtype=torch.bfloat16)+ self.weight_bytes = sum(x.numel() * x.element_size() for x in t.values())+ self.t = t+ self.device = devicediff --git a/tools/mmap_upload_check.py b/tools/mmap_upload_check.pynew file mode 100644index 0000000..765a4f2--- /dev/null+++ b/tools/mmap_upload_check.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""Check for patch 0098 (glm-mmap-uploads): the DFlash2 drafter's and the GLM vision tower's loaders copy each tensor+out of the safetensors mmap before it goes to the GPU. Run inside the image scripts/prepare.sh built (no GPU needed):++ docker run --rm --entrypoint python -v "$PWD/tools/mmap_upload_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py++Each loader runs here on the CPU over a small checkpoint this script writes, with ``Tensor.to`` watched: no tensor a+loader hands to a device copy may lie in the safetensors file's mapping (its address inside a mapping of that file in+/proc/self/maps, read at the moment of the copy). Why it matters: on kindling spark-os's 64 KiB-page kernel a pageable+copy to the GPU straight from a file mmap hangs in the driver (cuMemcpyHtoDAsync) once the process holds GPU memory,+and both loaders run after the main weights; the same copy from an ordinary host buffer is instant. The loaders as+TensorFold ships them fail this check. Exit code 1 when a check fails.+"""+import json+import os+import sys+import tempfile+from pathlib import Path+from types import SimpleNamespace++import torch+from safetensors.torch import save_file++failures = []+++def check(name, cond, detail=""):+ print(f"{'ok ' if cond else 'FAIL'} {name}{': ' + detail if detail else ''}")+ if not cond:+ failures.append(name)+++def file_ranges(path):+ """[start, end) of every mapping of ``path`` in this process right now."""++ real = os.path.realpath(path)+ out = []+ with open("/proc/self/maps") as maps:+ for line in maps:+ parts = line.split(maxsplit=5)+ if len(parts) == 6 and parts[5].strip() == real:+ lo, hi = parts[0].split("-")+ out.append((int(lo, 16), int(hi, 16)))+ return out+++class Watch:+ """While active, every ``Tensor.to`` call records whether its source tensor's bytes lie in a mapping of ``path``."""++ def __init__(self, path):+ self.path = path+ self.calls = 0+ self.from_mmap = 0++ def __enter__(self):+ self.orig = torch.Tensor.to+ watch = self++ def to(t, *args, **kwargs):+ lo = t.data_ptr()+ hi = lo + t.numel() * t.element_size()+ watch.calls += 1+ if any(a < hi and lo < b for a, b in file_ranges(watch.path)):+ watch.from_mmap += 1+ return watch.orig(t, *args, **kwargs)++ torch.Tensor.to = to+ return self++ def __exit__(self, *exc):+ torch.Tensor.to = self.orig+ return False+++def bf16(*shape):+ return torch.randn(*shape).to(torch.bfloat16)+++def vision_tower(root):+ from tensorfold.vision.glm import GlmVisionTower++ d = Path(root) / "vision"+ d.mkdir()+ vision = {"hidden_size": 64, "num_heads": 4, "depth": 1, "rms_norm_eps": 1e-6, "patch_size": 14,+ "temporal_patch_size": 2, "spatial_merge_size": 2, "out_hidden_size": 64}+ (d / "config.json").write_text(json.dumps({"vision_config": vision}))+ names = {"model.visual.a.weight": bf16(256, 64), "model.visual.b.weight": bf16(64),+ "model.visual.c.weight": torch.randn(64, 64)} # float32: the load converts it to bf16+ save_file(names, str(d / "model-00001-of-00001.safetensors"))+ index = {"weight_map": {n: "model-00001-of-00001.safetensors" for n in names}}+ (d / "model.safetensors.index.json").write_text(json.dumps(index))+ with Watch(d / "model-00001-of-00001.safetensors") as w:+ tower = GlmVisionTower(d, "cpu")+ check("vision tower: the loader copies its tensors to the device", w.calls >= len(names), f"{w.calls} copies")+ check("vision tower: no device copy reads the safetensors mmap", w.from_mmap == 0,+ f"{w.from_mmap} of {w.calls} copies from the mapped file")+ check("vision tower: the weights arrive as written",+ all(torch.equal(tower.t[n[len("model.visual."):]], t.to(torch.bfloat16)) for n, t in names.items()))+++class Stop(Exception):+ pass+++def drafter(root):+ from tensorfold.families.glm5_next.cuda import dflash2++ d = Path(root) / "dflash2"+ d.mkdir()+ cfg = {"hidden_size": 64, "head_dim": 16, "num_attention_heads": 4, "num_key_value_heads": 2,+ "intermediate_size": 128, "rms_norm_eps": 1e-6, "rope_parameters": {"rope_theta": 10000.0},+ "num_hidden_layers": 1, "sliding_window": 17, "is_causal": True,+ "dflash_config": {"mask_token_id": 0, "conv_group_size": 1, "conv_kernel_size": 2, "block_size": 8,+ "selector_top_k": 4, "target_layer_ids": [1]}}+ (d / "config.json").write_text(json.dumps(cfg))+ fc = bf16(64, 128)+ save_file({"fc.weight": fc, "hidden_norm.weight": bf16(64)}, str(d / "model.safetensors"))+ seen = []++ def quantize4(t): # the first upload's result; nothing past it is needed here+ seen.append(t)+ raise Stop++ orig = dflash2._quantize4+ dflash2._quantize4 = quantize4+ try:+ with Watch(d / "model.safetensors") as w:+ try:+ dflash2.Drafter(d, SimpleNamespace(device="cpu", rank=0, world=1))+ except Stop:+ pass+ finally:+ dflash2._quantize4 = orig+ check("drafter: the loader reached its first upload", len(seen) == 1 and w.calls >= 1, f"{w.calls} copies")+ check("drafter: no device copy reads the safetensors mmap", w.from_mmap == 0,+ f"{w.from_mmap} of {w.calls} copies from the mapped file")+ check("drafter: the weight arrives as written", len(seen) == 1 and torch.equal(seen[0], fc))+++def main():+ with tempfile.TemporaryDirectory() as root:+ vision_tower(root)+ drafter(root)+ print(f"{len(failures)} failed" if failures else "all passed")+ sys.exit(1 if failures else 0)+++if __name__ == "__main__":+ main()