GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0122: the start-up budget counts the pages parked on the per-CPU free lists (issue #148)
Robert Wojciechowskic388ee5189de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1da5443..c9c389e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -153,6 +153,22 @@ Every change to this recipe, newest first. Each release names the image it serveat ~400k while decode held ~45-55 tok/s. One running SHA-256 over the message shapes, copied at each step, makes itone pass: that session's restore 4.06 -> 0.014 s, the same restores (the same history in each key; ids are stilltried first). CPU check: `tools/kept_reasoning_check.py` (fails on the unpatched source).+- **The first start of a new image no longer gets a smaller pool** (patch `0122-cuda-budget-parked-pages`, by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)). TensorFold+ budgets each rank from `MemAvailable` at start; the first start of an+ image the worker lacked read 89.44 GiB "within" on rank 0 against 94.86 for a warm restart of the same image, and+ kept 2 prompt states, not 32. On kernel 6.7+ a bulk free leaves GiBs of free pages on the per-CPU lists (`pagesets`+ `count:` in `/proc/zoneinfo`), in neither `MemFree` nor `MemAvailable`: the image copy in `prepare.sh` (`docker save`+ / `docker load`) parks 5-9 GiB there, which comes back at ~0.05-0.1 GiB/s over 1-2 minutes, and the first start of a new+ image compiles `tensorfold_roce_v1` inside the rank container ~1 s before the budget is read, which parks 2.4 GiB+ more. `capacity.admit` now reads `/proc/meminfo` and, right after it, the lists once at start-up (every zone and CPU,+ less their `high_min:` resting level, so a warm start's idle 0.28 GiB, 0.11 GiB over it, does not move the budget; 0+ when `/proc/zoneinfo` is unreadable) and adds the excess to that one `MemAvailable` reading (capped at `MemTotal`) for+ both `available_bytes` and `page_room`, so pages that drain in between are undercounted, never counted twice. The+ start-up log says how many it counted, from 0.25 GiB. Only that start-up read counts them: the Qwen families' live memory gate+ keeps its figure, and the GLM family reads `MemAvailable` nowhere else. `start.sh`'s own "memory available" check+ (and its warning below ~110 GiB) counts the same excess. Cold first start of a new image, TP=2: 94.58 GiB "within"+ on rank 0 (rank 1 95.20) against 89.44 with nothing counted; a warm restart 94.86. CPU check on synthetic zoneinfo / meminfo files, admit() included: `tools/parked_pages_check.py`.- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (atdiff --git a/CREDITS.md b/CREDITS.mdindex d9f0623..c2847b8 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -211,6 +211,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- `0120-glm-fork-point-shared` (a kept state a second conversation goes on from is a shared prefix): the diagnosis and the first fix (the writer's next ids kept with a state, the state flagged when a resumed prompt goes on otherwise, the flag kept when the same ids are kept again) are by [RyanLeeUPC](https://github.com/RyanLeeUPC) in [issue #121](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/121); the rest by [BadAd84](https://github.com/BadAd84).- `0121-glm-kept-reasoning-linear` (kept reasoning restored in one pass over the conversation): by[cawilliamson](https://github.com/cawilliamson).+- `0122-cuda-budget-parked-pages` (the start-up budget counts the pages parked on the per-CPU free lists): by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X).- Every patch, except the parts credited above: by MiaAI-Lab, developed with[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify orquote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; seediff --git a/README.md b/README.mdindex 8110b44..0b2576d 100644--- a/README.md+++ b/README.md@@ -238,7 +238,7 @@ By default only data URLs are accepted; `VISION_URLS=1` also lets the server fetmodel, drafter, revision, image or worker).2. **Checks:** the arguments (TensorFold's own parser), the link, the previous server (stopped on `restart`, or whenonly one rank is up; a stopped container left from an earlier run is removed, its log saved first), the port, free memory (a warning- below ~110 GiB on either Spark).+ below ~110 GiB on either Spark, counting the pages still parked on the kernel's per-CPU free lists: see below).3. **Launch:** rank 1 on the worker over ssh, then rank 0 and the API here, with the settings from `scripts/config.sh`.4. **Loading:** rank 0's log as it comes, and every 15 s the elapsed time and how much of the startup estimate is oneach Spark's GPU; if a rank stops, both ranks' last log lines and why.@@ -298,6 +298,16 @@ moving caches instead, patch `0074`); `/health` shows `pool_tokens`, `pool_free_TensorFold's budget on each Spark is `MemAvailable` at start minus a host reserve (`MEMORY_RESERVE_GIB`, 14.5 GiB here;TensorFold's own default is a tenth of RAM). The server uses about 10 GiB beyond its own estimate at its peak, so thereserve also sets the lowest free memory.++TensorFold reads `MemAvailable` once, when it starts. The image copy in `prepare.sh` (`docker save` on the head,+`docker load` on the worker) frees tens of GiB of page cache at once, and the kernel parks 5-9 GiB of it on its per-CPU+free lists (the `count:` lines under `pagesets` in `/proc/zoneinfo`), in neither `MemFree` nor `MemAvailable`; it comes+back at ~0.05-0.1 GiB/s over the next 1-2 minutes, and the first start of a new image also parks 2.4 GiB compiling its kernels+a second before the budget is read. A first start used to land in that window: 89.44 GiB budgeted on rank 0 where a+warm restart got 94.86, which cut the kept prompt states from 32 to 2 and shrank the pool. Patch `0122` makes the+engine count the pages parked above the lists' resting level (read once, at start-up, and logged), so the first start+budgets 94.58 GiB (rank 1 95.20); `start.sh`'s ~110 GiB check counts them too.+The GB10 firmware also keeps about 2 GiB for a screen, which a headless Spark never uses and `MemAvailable` nevercounts. With `PARALLEL` above 1, `DISPLAY_KV_MIB=1792` (patch 0072) adds that much of it to the pool on every rank, ontop of `KV_POOL_GIB`: the first DSA layers' latent planes sit in a span of ordinary memory with the reservation mapped@@ -780,6 +790,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) || `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops || `tools/test_broken_health_exit.py --source-root DIR` | CPU-only broken-state checks against patched TensorFold: settings, first cause, request refusal, round/load/drop errors, health and metrics, subprocess exit (no Torch/GPU) |+| `tools/parked_pages_check.py` | patch 0122's checks, run in the image (`docker run ... --entrypoint python`, see the file) or against the patched source with `PYTHONPATH`: the start-up budget's count of the pages parked on the kernel's per-CPU free lists beyond their resting level, on synthetic zoneinfo / meminfo files (several CPUs, zones and nodes, a warm start, no `high_min`, no page lists, unreadable and garbled files) and the `available_bytes` / `page_room` figures that include them; no GPU, no model || `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait || `tools/test_sse_keepalive.py --source-root DIR` | patch 0111's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): every streaming route of the real handler, over a stub that stays silent for 3 s, gets `: keepalive` about once a second with `TENSORFOLD_SSE_KEEPALIVE_S=1` and none after its last event; without its comment lines each stream is byte-identical to the stream with `0`; non-streamed replies unchanged; no thread outlives its request; `--expect-stock` before 0111 shows the silence || `tools/kept_reasoning_check.py --source-root DIR` | patch 0121's checks on the CPU, against TensorFold's source with the patches applied: `restore` against the stock implementation (embedded) on 300 random agent conversations (LRU eviction, renumbered ids and re-serialised arguments included), and one pass over a ~2,100-message conversation; `--expect-stock` reproduces the quadratic restore on the unpatched source |diff --git a/patches/0122-cuda-budget-parked-pages.patch b/patches/0122-cuda-budget-parked-pages.patchnew file mode 100644index 0000000..4ffc7ea--- /dev/null+++ b/patches/0122-cuda-budget-parked-pages.patch@@ -0,0 +1,146 @@+# The startup budget counts the pages parked on the kernel's per-CPU free lists. TensorFold sizes the KV pool (and the+# kept prompt states) from MemAvailable when the ranks start (capacity.admit: available_bytes / page_room). On kernel+# 6.7+ (6.17 on the GB10) a bulk free leaves GiBs of free pages on the per-CPU lists ("pcp", the ``count:`` lines under+# each zone's ``pagesets`` in /proc/zoneinfo) instead of the buddy lists: they are free, and the kernel drains them when+# an allocation needs them, but neither MemFree nor MemAvailable counts them, and they drain back at only ~0.05-0.1+# GiB/s. Two sources measured on a Spark: an image copy (docker save | load) parks 5-9 GiB for 1-2 minutes, and the+# compile of the first start of a new image (tensorfold_roce_v1, built ~1 s before the budget is read) parks 2.4 GiB+# (MemAvailable -2.41 GiB at +1 s, still -0.53 GiB at +49 s). The first start of a new image then budgeted ~5 GiB too+# little: 89.44 GiB "within" on rank 0 against 94.58 with the pages counted (rank 1 95.20) and 94.86 on a warm restart+# of the same image, a smaller pool for as long as the server ran.+# start.sh's ~110 GiB free-memory warning counts the image copy's pages too (_avail_gb), but it runs before the rank+# container and cannot see the ones parked inside it.+# capacity.parked_bytes() sums those counts (x the page size; every zone and CPU) less their ``high_min:`` lines, the+# level they hold at rest (a Spark's idle lists hold 0.28 GiB, of which 0.11 GiB is over it; without high_min: the+# first 512 MiB), so a warm start's budget does not move: only the excess counts. 0 when /proc/zoneinfo is+# unreadable or has no page lists, never an error. admit() reads /proc/meminfo first and the lists right after, once,+# and passes that one reading (``counting``: MemAvailable plus the excess, capped at MemTotal) to available_bytes and+# page_room, so pages that drain in between are undercounted, never counted twice; it prints the start-up line "budget+# counts the N GiB free on the per-CPU page lists", from 0.25 GiB.+# Only that startup read counts them: the live memory gate of the qwen3_5 / qwen4_exp families (torch_live) calls+# available_bytes without a reading and keeps its figure; the GLM family reads MemAvailable only here. The 10 % reserve+# is unchanged. Same replies: sizing only. tools/parked_pages_check.py.+# By Robert Wojciechowski (GitHub @wojo, X @rwojo).++diff --git tensorfold/cuda/capacity.py tensorfold/cuda/capacity.py+--- tensorfold/cuda/capacity.py++++ tensorfold/cuda/capacity.py+@@ -138,15 +138,57 @@ def estimate_weights(model_dir: str | Path, transform: Callable, *, rank: int |+ return Weights(resident, staging, mapped)++++MEMINFO, ZONEINFO = "/proc/meminfo", "/proc/zoneinfo" # tools/parked_pages_check.py reads canned ones++PARKED_REST = GIB // 2 # what the lists hold at rest when /proc/zoneinfo has no high_min (kernels before 6.7)++++++def parked_bytes() -> int:++ """Bytes free on the kernel's per-CPU page lists beyond what they hold at rest: the ``count:`` lines under each++ zone's ``pagesets`` less their ``high_min:`` lines (PARKED_REST when there are none). A bulk free (an image copy, a++ compiler's exit) leaves GiBs there on kernel 6.7+; they are free, the kernel drains them when an allocation needs++ them, but neither MemFree nor MemAvailable counts them and they drain back at ~0.05-0.1 GiB/s. A warm start parks++ ~0.3 GiB, which the budget never counted: that is ~0, so it stays unchanged. 0 when the file is unreadable or has++ no page lists."""++++ count = rest = 0++ listed = False++ try:++ for row in Path(ZONEINFO).read_text().splitlines():++ word = row.split()++ if row.strip() == "pagesets":++ listed = True++ elif listed and row[:4] != " " and not row.startswith(" vm stats"):++ listed = False # the next zone's or the next field of this one++ elif listed and word[:1] == ["count:"]:++ count += int(word[1])++ elif listed and word[:1] == ["high_min:"]:++ rest += int(word[1])++ page = os.sysconf("SC_PAGE_SIZE")++ return max(0, count * page - (rest * page if rest else PARKED_REST)) if count else 0++ except (OSError, ValueError, IndexError):++ return 0+++++ def _meminfo() -> dict | None:+ try:+- rows = Path("/proc/meminfo").read_text().splitlines()++ rows = Path(MEMINFO).read_text().splitlines()+ memory = {key.rstrip(":"): int(value) * 1024 for key, value, *_ in (row.split() for row in rows)}+ except (OSError, ValueError):+ return None+ return memory if {"MemTotal", "MemAvailable"} <= memory.keys() else None++++_READ = object() # available_bytes / page_room read /proc/meminfo themselves unless given a reading++++++def counting(memory: dict | None, parked: int) -> dict | None:++ """A /proc/meminfo reading with ``parked`` (parked_bytes()) added to MemAvailable, at most MemTotal."""++++ if memory is None:++ return None++ return {**memory, "MemAvailable": min(memory["MemTotal"], memory["MemAvailable"] + parked)}+++++ def unified(torch) -> bool:+ """A GPU on the host's memory (GB10): its free figure is MemFree, which counts the page cache as used."""++@@ -171,10 +213,10 @@ def reserve_bytes(total: int, *, host: bool = False) -> int:+ return int(gib * GIB)+++-def available_bytes(torch) -> int:++def available_bytes(torch, memory: dict | None = _READ) -> int:+ free, total = map(int, torch.cuda.mem_get_info())+ available = max(0, free - reserve_bytes(total))+- memory = _meminfo()++ memory = _meminfo() if memory is _READ else memory+ if memory is None:+ return available+ host = max(0, memory["MemAvailable"] - reserve_bytes(memory["MemTotal"], host=True))+@@ -188,10 +230,10 @@ def total_bytes(torch) -> int:+ return int(torch.cuda.mem_get_info()[1])+++-def page_room(torch) -> int | None:++def page_room(torch, memory: dict | None = _READ) -> int | None:+ """What caches and mapped read-only tables share on a unified GPU (MemAvailable); None on a discrete GPU."""++- memory = _meminfo()++ memory = _meminfo() if memory is _READ else memory+ return memory["MemAvailable"] if memory is not None and unified(torch) else None+++@@ -279,6 +321,7 @@ def admit(model_dir: str | Path, requested: int | None, explicit: bool | None, t+ build.refuse_old_gpu(floor(model_dir)) # an old GPU is refused here, before any weight loads+ error = None+ plan = None++ parked = 0+ try:+ text = config(model_dir)+ geometry = geometry(text) if callable(geometry) else geometry+@@ -300,9 +343,14 @@ def admit(model_dir: str | Path, requested: int | None, explicit: bool | None, t+ main = geometry+ geometry = Geometry(lambda slots: main.bytes_at(slots) + draft_geometry.bytes_at(slots),+ main.reserve, main.minimum_slots)++ # MemAvailable first, the lists right after, one reading for both figures: pages that drain from the lists in++ # between are counted by neither (an undercount), never by both++ memory = _meminfo()++ parked = parked_bytes()++ memory = counting(memory, parked)+ plan = make_plan(int(text.get("max_position_embeddings") or 0), requested,+ requested is not None if explicit is None else explicit,+- available_bytes(torch), weights, geometry, room=page_room(torch))++ available_bytes(torch, memory), weights, geometry, room=page_room(torch, memory))+ except (OSError, ValueError, KeyError, TypeError, struct.error) as exc:+ error = f"{type(exc).__name__}: {exc}" # name the cause: its text alone has hidden a dtype's KeyError+ status = [1 if error else 0, *(plan.settings + [plan.fitting, plan.largest] if plan else [0, -1, 0, 0, 0])]+@@ -315,6 +363,9 @@ def admit(model_dir: str | Path, requested: int | None, explicit: bool | None, t+ print(f"[tensorfold] CUDA rank {rank} startup estimate {receipt['total_bytes_estimate'] / GIB:.2f} GiB "+ f"within {plan.budget / GIB:.2f} GiB; native {plan.native}, allocated prompt/reply window {window}, "+ f"cache slots {receipt['cache_slots']}", flush=True)++ if parked >= GIB // 4:++ print(f"[tensorfold] CUDA rank {rank} budget counts the {parked / GIB:.2f} GiB free on the per-CPU page lists "++ "beyond their resting level (neither MemFree nor MemAvailable does)", flush=True)+ note = tables_note(plan)+ if note:+ print(f"[tensorfold] {note}", flush=True)diff --git a/scripts/nodes.sh b/scripts/nodes.shindex b0b6466..ab14268 100644--- a/scripts/nodes.sh+++ b/scripts/nodes.sh@@ -56,6 +56,34 @@ worker_save_log() {worker "$1" "$(declare -f save_log); save_log \"\$HOME/.cache/tensorfold-glm53/logs\" $1 '$CONTAINER_NAME' '$LOG_KEEP'"}+# _avail_gb: whole GiB available here, what `free -g` shows in its "available" column plus the pages parked on the+# per-CPU free lists over their resting level, the figure TensorFold's budget starts from (patch 0122). The bulk free of+# the image copy in prepare.sh (`docker save` / `docker load`) parks 5-9 GiB there for 1-2 minutes: the "count:" lines+# under "pagesets" in /proc/zoneinfo, in neither MemFree nor MemAvailable. Runs on the workers too (the two helpers+# below are sent over ssh with it): no config.sh there.+# _parked_zone <page size>: "<parked KiB> <resting KiB>" from the per-CPU page lists, empty when there are none or a+# value is not a number. Only the count: and high_min: lines under a zone's "pagesets" count, as in the engine+# (capacity.parked_bytes in patch 0122). The resting level is the lists' high_min plus 256 MiB of slack (512 MiB when+# high_min is not listed): it undercounts a little, never overcounts.+_parked_zone() {+ awk -v pg="$1" '{ t = $0; gsub(/^[ \t]+|[ \t]+$/, "", t) }+ t == "pagesets" { l = 1; next }+ l && substr($0, 1, 4) != " " && $0 !~ /^ vm stats/ { l = 0 }+ l && $1 == "count:" { if ($2 !~ /^[0-9]+$/) bad = 1; c += $2; n++ }+ l && $1 == "high_min:" { if ($2 !~ /^[0-9]+$/) bad = 1; m += $2; k++ }+ END { if (n && !bad) print int(c * pg / 1024), (k ? int(m * pg / 1024) + 262144 : 524288) }' \+ /proc/zoneinfo 2>/dev/null || true+}+_mem_avail() { awk '/^MemAvailable:/ { print $2 }' /proc/meminfo 2>/dev/null || true; }+_avail_gb() {+ local pg a z h rest+ pg=$(getconf PAGESIZE 2>/dev/null || echo 4096)+ a=$(_mem_avail)+ [[ -n "$a" ]] || { free -g | awk '/^Mem:/ {print $7}'; return; }+ z=$(_parked_zone "$pg"); read -r h rest <<<"$z"+ echo $(( (a + (${h:-0} > ${rest:-0} ? h - rest : 0)) / 1048576 ))+}+need_worker() {local i=$1 v hv=$(wvar WORKER "$i"); h=$(worker_host "$i")diff --git a/start.sh b/start.shindex 2135a9c..6777ed2 100755--- a/start.sh+++ b/start.sh@@ -284,10 +284,12 @@ if ss -ltn "sport = :$PORT" 2>/dev/null | grep -q LISTEN; thenfi# TensorFold budgets each Spark's free memory minus MEMORY_RESERVE_GIB (14.5); the defaults want ~110 GiB free at start on each.# With less, rank 0 refuses the window and names one that fits, which the load below then starts again with.-here_gb=$(free -g | awk '/^Mem:/ {print $7}')+# Memory freed in bulk a moment ago (prepare.sh's image copy) can still sit on the kernel's per-CPU free lists, outside+# MemAvailable. It counts as available below, as in TensorFold's budget (patch 0122); see _avail_gb in scripts/nodes.sh.+here_gb=$(_avail_gb)low=0; (( here_gb >= 110 )) || low=1for i in $(worker_ids); do- there_gb[i]=$(worker "$i" "free -g | awk '/^Mem:/ {print \$7}'" 2>/dev/null || echo 0)+ there_gb[i]=$(worker "$i" "$(declare -f _parked_zone _mem_avail _avail_gb); _avail_gb" 2>/dev/null || echo 0)(( there_gb[i] >= 110 )) || low=1doneif (( ! low )); thendiff --git a/tools/parked_pages_check.py b/tools/parked_pages_check.pynew file mode 100755index 0000000..d82e58b--- /dev/null+++ b/tools/parked_pages_check.py@@ -0,0 +1,285 @@+#!/usr/bin/env python3+"""Checks for patch 0122 (the startup budget counts the pages parked on the kernel's per-CPU free lists beyond their+resting level), run inside the image that scripts/prepare.sh built (CPU only: no GPU, no model, about a second):++ docker run --rm --entrypoint python -v "$PWD/tools/parked_pages_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py++or on any machine against TensorFold's patched source (no torch needed):++ PYTHONPATH=/path/to/TensorFold/src python tools/parked_pages_check.py++Synthetic /proc/zoneinfo and /proc/meminfo files (capacity.ZONEINFO / MEMINFO point at them) and a stand-in for torch:+page lists on several CPUs, zones and nodes (only the ``count:`` lines under ``pagesets`` are summed, less their+``high_min:`` lines: the excess over the resting level), a warm start's lists (counts ~0), lists without high_min+(the first 512 MiB are resting), zones without lists, no lists at all, an unreadable or garbled file (0, never an+error), and the figures the startup budget reads (``available_bytes`` / ``page_room`` given the one counted reading, on a+unified and on a discrete GPU), which a live caller that passes none does not see. ``admit()`` itself, with a stub torch,+a tiny config.json, no weights and a constant geometry: its budget with and without parked pages, ``/proc/meminfo``+read before the lists (and pages draining between the reads never counted twice), and the 0.25 GiB log line. Exit code 1 when a check fails, and on an+image without the patch.+"""+import contextlib+import io+import json+import os+import re+import sys+import tempfile+from pathlib import Path+from types import SimpleNamespace as NS++from tensorfold.cuda import build, capacity++GIB, KIB = 1024**3, 1024+PAGE = os.sysconf("SC_PAGE_SIZE")+HIGH_MIN = 2146 # pages a CPU's list holds at rest, as the kernel prints it on a Spark+failures = []+++def check(name, ok, detail=""):+ print(("ok " if ok else "FAIL ") + name + (f" ({detail})" if detail and not ok else ""))+ if not ok:+ failures.append(name)+++def cpus(counts, high_min=HIGH_MIN, indent=4):+ """The page lists of one zone: a ``cpu:`` block a count, as the kernel prints them (no high_min line when None)."""+ pad = " " * indent+ rest = "" if high_min is None else f"{pad} high_min: {high_min}\n"+ return "".join(f"{pad}cpu: {n}\n{pad} count: {c}\n{pad} high: 5000\n{pad} batch: 63\n"+ f"{rest}{pad} high_max: 198283\n vm stats threshold: 110\n"+ for n, c in enumerate(counts))+++def zone(node, name, counts=None, managed=1000, high_min=HIGH_MIN):+ """One zone's block: stats lines, the page lists when ``counts`` is given, start_pfn."""+ text = f"Node {node}, zone {name:>8}\n pages free 10\n managed {managed}\n nr_free_cma 0\n"+ if counts is not None:+ text += " pagesets\n" + cpus(counts, high_min)+ return text + " start_pfn: 4096\n"+++def parked():+ return capacity.parked_bytes() if hasattr(capacity, "parked_bytes") else None # an image without the patch+++def run(zoneinfo, meminfo, torch=None, zone_path=None):+ """The figures the startup budget reads with those files in place of /proc's: ``info`` is the one reading admit()+ passes to ``avail`` (available_bytes) and ``room`` (page_room); ``live`` is available_bytes as the live gates call it,+ with no reading."""+ d = Path(tempdir.name)+ if zoneinfo is not None:+ (d / "zoneinfo").write_text(zoneinfo)+ (d / "meminfo").write_text(meminfo)+ capacity.ZONEINFO = zone_path or str(d / "zoneinfo")+ capacity.MEMINFO = str(d / "meminfo")+ p, plain = parked(), capacity._meminfo()+ live = capacity.available_bytes(torch) if torch else None+ if not hasattr(capacity, "counting"): # an image without the patch: no such argument+ return NS(parked=p, info=plain, plain=plain, avail=live, room=capacity.page_room(torch) if torch else None, live=live)+ info = capacity.counting(plain, p or 0)+ return NS(parked=p, info=info, plain=plain, live=live,+ avail=capacity.available_bytes(torch, info) if torch else None,+ room=capacity.page_room(torch, info) if torch else None)+++def fake(integrated, free=0, total=0):+ props = NS(is_integrated=integrated)+ return NS(cuda=NS(mem_get_info=lambda: (free, total), get_device_properties=lambda i: props))+++def meminfo(total_gib, avail_gib):+ return (f"MemTotal: {total_gib * GIB // KIB} kB\nMemFree: {GIB // KIB} kB\n"+ f"MemAvailable: {int(avail_gib * GIB) // KIB} kB\nBuffers: 1 kB\n")+++tempdir = tempfile.TemporaryDirectory()+os.environ.pop("TENSORFOLD_MEMORY_RESERVE_GIB", None)+check("capacity.parked_bytes exists (patch 0122 applied)", hasattr(capacity, "parked_bytes"))++MEM = meminfo(128, 100)+unified = fake(True, free=10 * GIB, total=128 * GIB)+discrete = fake(False, free=60 * GIB, total=80 * GIB)+reserve = capacity.reserve_bytes(128 * GIB, host=True) # a tenth of the host's memory (12.8 GiB)++# several CPUs on several zones of two nodes: every count less every high_min, nothing else+counts_a, counts_b, counts_c = [200000, 3143, 2332, 17], [100000, 100000, 100000], [400000]+text = (zone(0, "DMA", counts_a) + zone(0, "DMA32", None) + zone(0, "Normal", counts_b) + zone(1, "Normal", counts_c)+ + zone(1, "Movable", None))+n = len(counts_a + counts_b + counts_c)+excess = (sum(counts_a + counts_b + counts_c) - n * HIGH_MIN) * PAGE+r = run(text, MEM, unified)+check("sums every CPU, zone and node, less each list's resting level", r.parked == excess, f"{r.parked} != {excess}")+check("MemAvailable includes the excess", r.info["MemAvailable"] == 100 * GIB + excess)+check("MemTotal is the file's", r.info["MemTotal"] == 128 * GIB)+check("available_bytes (unified GPU) is MemAvailable + excess - the 10 % reserve",+ r.avail == 100 * GIB + excess - reserve, f"{r.avail}")+check("page_room (unified GPU) is MemAvailable + excess", r.room == 100 * GIB + excess)+check("a live caller (no reading passed) keeps MemAvailable", r.live == 100 * GIB - reserve and+ r.plain["MemAvailable"] == 100 * GIB)+r = run(text, MEM, discrete)+check("a discrete GPU is bounded by the smaller of both: here its own free memory",+ r.avail == 60 * GIB - capacity.reserve_bytes(80 * GIB), f"{r.avail}")+check("page_room is None on a discrete GPU", r.room is None)++# GiBs of them, like after an image copy: 6 GiB over the resting level is 6 GiB more budget+six = 6 * GIB // PAGE+r = run(zone(0, "Normal", [six // 4 + HIGH_MIN] * 4), meminfo(128, 90), unified)+check("6 GiB parked over the resting level raise the budget by 6 GiB",+ r.avail - (90 * GIB - reserve) == six // 4 * 4 * PAGE == 6 * GIB, f"{r.avail}")++# a warm start: the lists hold their resting level and a little more, or less+for label, counts in (("at their resting level", [HIGH_MIN] * 20), ("a little over it (0.11 GiB)", [HIGH_MIN + 1440] * 20),+ ("below it", [10, 0, 5, HIGH_MIN - 1] * 5), ("empty", [0] * 20)):+ r = run(zone(0, "Normal", counts), MEM, unified)+ small = r.parked is not None and r.parked < GIB // 4+ check(f"a warm start, lists {label}: under the log line's 0.25 GiB, MemAvailable within 0.25 GiB",+ small and r.info is not None and r.info["MemAvailable"] - 100 * GIB < GIB // 4, f"{r.parked}")+check("a warm start with the lists below their resting level counts nothing",+ run(zone(0, "Normal", [100] * 20), MEM).parked == 0)++# no high_min lines (kernels before 6.7): the first 512 MiB are resting+half = capacity.PARKED_REST if hasattr(capacity, "PARKED_REST") else None+r = run(zone(0, "Normal", [(GIB + GIB // 2) // PAGE // 2] * 2, high_min=None), MEM, unified)+check("no high_min: the first 512 MiB are resting", half == GIB // 2 and r.parked == GIB, f"{r.parked}")+check("no high_min, lists under 512 MiB: nothing", run(zone(0, "Normal", [1000] * 4, high_min=None), MEM).parked == 0)++# other lines named count, and the lines after the lists, are not page lists+noise = (zone(0, "Normal", [HIGH_MIN + 10]).replace(" start_pfn: 4096\n",+ " start_pfn: 4096\n count: 99999\n high_min: 7\n")+ + "Node 0, zone Other\n count: 77777\n pagesets\n cpu: 0\n high: 1\n")+r = run(" count: 5\n count: 6\n" + noise, MEM)+check("only the count: and high_min: lines under pagesets", r.parked == 10 * PAGE, f"{r.parked}")++# the kernel's other layouts of the lists+r = run("Node 0, zone Normal\n pagesets\n cpu: 0\n count: 2200\n high: 9\n"+ " high_min: 2000\n vm stats threshold: 8\n cpu: 1\n count: 2100\n"+ " high_min: 2000\n all_unreclaimable: 0\n", MEM)+check("a list that ends at the next field", r.parked == 300 * PAGE, f"{r.parked}")++# no page lists, an empty, an unreadable and a garbled file: nothing parked, the start goes on+no_lists = zone(0, "DMA", None) + zone(0, "Normal", None)+bad = zone(0, "Normal", [10 ** 6])+for label, text_, path in (("no page lists", no_lists, None), ("an empty file", "", None),+ ("a missing file", None, str(Path(tempdir.name) / "none")),+ ("a directory", None, tempdir.name),+ ("a count that is not a number", bad.replace("count: 1000000", "count: x"), None),+ ("a count with no value", bad.replace("count: 1000000", "count:"), None),+ ("a high_min that is not a number", bad.replace("high_min: 2146", "high_min: x"), None),+ ("binary", "\x00\xff\xfe" * 10, None)):+ r = run(text_, MEM, unified, zone_path=path)+ check(f"{label}: nothing parked, MemAvailable as read",+ r.parked == 0 and r.info["MemAvailable"] == 100 * GIB and r.avail == 100 * GIB - reserve, f"{r.parked}")+(Path(tempdir.name) / "zoneinfo").write_bytes(b"Node 0, zone Normal\n pagesets\n cpu: 0\n count: \xff\xfe\n")+capacity.ZONEINFO = str(Path(tempdir.name) / "zoneinfo")+check("undecodable bytes: nothing parked", parked() == 0)++# the sum cannot pass the host's memory+r = run(zone(0, "Normal", [200 * GIB // PAGE]), meminfo(128, 120), unified)+check("MemAvailable is capped at MemTotal", r.info["MemAvailable"] == 128 * GIB)+# a /proc/meminfo that lacks a field is still unusable, and unreadable ones too+check("meminfo without MemAvailable: None", run(text, "MemTotal: 1 kB\n").info is None)+check("meminfo that is not numbers: None", run(text, "MemTotal: x kB\nMemAvailable: 1 kB\n").info is None)++# admit() itself: the budget it plans from, the order of its two reads, and its log line. A stub torch, a tiny+# config.json, no weights and a constant geometry; ``calls`` records the reads, ``then`` swaps the files after the first+model = Path(tempdir.name) / "model"+model.mkdir()+(model / "config.json").write_text(json.dumps({"max_position_embeddings": 4096}))+real = {name: getattr(capacity, name) for name in ("floor", "estimate_weights", "make_plan", "_meminfo", "parked_bytes")}+real_refuse = build.refuse_old_gpu+build.refuse_old_gpu = lambda *args, **kwargs: None+capacity.floor = lambda directory: (0, 0)+capacity.estimate_weights = lambda *args, **kwargs: capacity.Weights(0, 0)+calls, plans, after = [], [], []+++def recording(name):+ def read(*args, **kwargs):+ calls.append(name)+ value = real[name](*args, **kwargs)+ if len(calls) == 1 and after:+ write(*after[0]) # pages drain right after the first read+ return value+ return read+++def write(zoneinfo, meminfo_text):+ d = Path(tempdir.name)+ (d / "zoneinfo").write_text(zoneinfo)+ (d / "meminfo").write_text(meminfo_text)+ capacity.ZONEINFO, capacity.MEMINFO = str(d / "zoneinfo"), str(d / "meminfo")+++def planning(*args, **kwargs):+ plans.append(real["make_plan"](*args, **kwargs))+ return plans[-1]+++capacity._meminfo, capacity.parked_bytes, capacity.make_plan = recording("_meminfo"), recording("parked_bytes"), planning+++def start(zoneinfo, meminfo_text, drained=None, torch=unified):+ """admit() on those files; ``drained`` is what the files become after its first read. Sets the budget, its output and+ the order in which it read."""+ calls.clear(), plans.clear(), after.clear()+ write(zoneinfo, meminfo_text)+ if drained:+ after.append(drained)+ out = io.StringIO()+ with contextlib.redirect_stdout(out):+ capacity.admit(model, None, None, torch, capacity.Geometry(lambda slots: 0, 0), None)+ return NS(budget=plans[0].budget, out=out.getvalue(), calls=list(calls),+ line=[row for row in out.getvalue().splitlines() if "budget counts" in row])+++six_gib = zone(0, "Normal", [HIGH_MIN + 6 * GIB // PAGE])+cold = start(six_gib, meminfo(128, 90))+bare = start(no_lists, meminfo(128, 90))+check("admit: no pages parked, the budget is MemAvailable less the reserve", bare.budget == 90 * GIB - reserve, f"{bare.budget}")+check("admit: 6 GiB parked over the resting level raise the budget by 6 GiB",+ cold.budget == 96 * GIB - reserve, f"{cold.budget}")+check("admit: it reads /proc/meminfo, then the page lists, once each", cold.calls == ["_meminfo", "parked_bytes"], f"{cold.calls}")+check("admit: the start-up line names the GiB counted",+ len(cold.line) == 1 and "counts the 6.00 GiB" in cold.line[0], f"{cold.line}")+check("admit: the line is absent when nothing is parked", bare.line == [])+# the lists drain between the two reads: MemAvailable read first can only undercount, never count the pages twice+drain = (no_lists, meminfo(128, 96))+raced = start(six_gib, meminfo(128, 90), drained=drain)+check("admit: pages draining between the reads are never counted twice",+ raced.budget <= 96 * GIB - reserve, f"{raced.budget} > {96 * GIB - reserve}")+check("admit: ... and that undercount is MemAvailable as first read", raced.budget == 90 * GIB - reserve, f"{raced.budget}")+# the line's threshold: 0.25 GiB+quarter = GIB // 4 // PAGE+for label, extra, shown in (("0.25 GiB over", quarter, True), ("just under 0.25 GiB", quarter - 1, False),+ ("a warm start's 0.11 GiB", 1440 * 20, False)):+ r = start(zone(0, "Normal", [HIGH_MIN + extra]), meminfo(128, 90))+ check(f"admit: {label}: the line is {'printed' if shown else 'absent'}", bool(r.line) == shown, f"{r.line}")+check("admit: the line names 0.25 GiB at the threshold",+ bool(start(zone(0, "Normal", [HIGH_MIN + quarter]), meminfo(128, 90)).line) and+ "counts the 0.25 GiB" in start(zone(0, "Normal", [HIGH_MIN + quarter]), meminfo(128, 90)).line[0])+nolines = start(no_lists, meminfo(128, 90))+check("admit: no page lists: budget as MemAvailable less the reserve, no line",+ nolines.budget == 90 * GIB - reserve and nolines.line == [])+capacity.__dict__.update({name: real[name] for name in real})+build.refuse_old_gpu = real_refuse++# this host's real file, when it has page lists in a layout this can read (any indentation): the answer is a figure+# between nothing and every parked page, and near an independent reading of the same file (the lists move between the+# two reads; a GiB is far more than they move, and far less than a wrong parse)+capacity.ZONEINFO, capacity.MEMINFO = "/proc/zoneinfo", "/proc/meminfo"+try:+ real = Path("/proc/zoneinfo").read_text()+except OSError:+ real = ""+counts = [int(v) for v in re.findall(r"^\s+count:\s+(\d+)\s*$", real, re.M)]+rests = [int(v) for v in re.findall(r"^\s+high_min:\s+(\d+)\s*$", real, re.M)]+if "pagesets" in real and counts and rests:+ want, got = max(0, sum(counts) - sum(rests)) * PAGE, parked()+ check("the real /proc/zoneinfo: between nothing and every parked page, near the count: less high_min: lines",+ got is not None and 0 <= got <= sum(counts) * PAGE and abs(got - want) < GIB, f"{got} vs {want}")+else:+ print("skip the real /proc/zoneinfo (no page lists with count: and high_min: lines here)")++print("FAILED: " + ", ".join(failures) if failures else "all checks passed")+sys.exit(1 if failures else 0)