Skip to content

Commit 222fe5f

Browse files
Chedrian07ashhart
authored andcommitted
fix: account for host n-grams in Flash Next memory preflight
The MLX preflight charged the entire checkpoint before the loader could memory-map its n-gram tables, refusing Flash Next on a 128 GiB Mac even in host mode. Let families estimate startup weight bytes. Flash Next uses the loader's shared host-selection rule and subtracts only mapped weight, scale and bias ranges from safetensors headers. Keep the 70% budget and reject oversized resident weights or forced GPU tables. Tests cover automatic and explicit host mode, forced GPU mode, reduced budgets, mixed checkpoint files and both MLX device-info APIs.
1 parent 279d8f7 commit 222fe5f

5 files changed

Lines changed: 178 additions & 17 deletions

File tree

‎src/tensorfold/cli.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,11 +429,16 @@ def cmd_serve(args: argparse.Namespace) -> int:
429429
print(f"[tensorfold] memory budget {memory_limit / gib:.1f} GiB{note}: MLX's buffers up to "
430430
f"{(memory_limit - PROCESS_BYTES) / gib:.1f} GiB, {PROCESS_BYTES / gib:.0f} GiB for the rest of the process",
431431
flush=True)
432-
weights = sum(path.stat().st_size for path in Path(model_dir).glob("*.safetensors"))
432+
checkpoint = sum(path.stat().st_size for path in Path(model_dir).glob("*.safetensors"))
433+
estimate = getattr(family.package, "weight_bytes", None)
434+
weights = checkpoint if estimate is None else estimate(model_dir)
433435
if args.ple_on_ssd:
434-
weights -= family.package.ple_bytes(model_dir) # read from disk at each lookup, never loaded
436+
weights = checkpoint - family.package.ple_bytes(model_dir) # read from disk at each lookup, never loaded
435437
if args.ssd_experts is not None:
436438
weights += int(args.ssd_experts * gib) - family.package.expert_bytes(model_dir) # the pool, not the stacks
439+
if weights < checkpoint:
440+
print(f"[tensorfold] weights: {weights / gib:.1f} GiB resident, "
441+
f"{(checkpoint - weights) / gib:.1f} GiB file-backed", flush=True)
437442
if weights >= memory_limit - PROCESS_BYTES:
438443
stream = ("stream its routed experts from SSD with --ssd-experts GIB (slower), "
439444
if args.ssd_experts is None and hasattr(family.package, "expert_bytes") else "")

‎src/tensorfold/families/qwen4_exp/__init__.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,27 @@ def expert_bytes(model_dir: Path) -> int:
6868
and ".mlp.switch_mlp." in name)
6969

7070

71+
def weight_bytes(model_dir: Path) -> int:
72+
"""MLX startup weight estimate: keep the file-size bound, less the n-gram tensors the loader will memory-map."""
73+
74+
import re
75+
76+
from tensorfold.families.qwen4_exp.host_table import ngrams_on_host, read_header
77+
78+
paths = list(Path(model_dir).glob("*.safetensors"))
79+
size = sum(p.stat().st_size for p in paths)
80+
if ngrams_on_host(model_dir):
81+
for path in paths:
82+
if not path.name.startswith("model"):
83+
continue
84+
for name, entry in read_header(path).items():
85+
if re.fullmatch(r"language_model\.model\.layers\.\d+\.ple\.ple_embedding\.ngram_embedding\."
86+
r"shard_\d+\.(weight|scales|biases)", name):
87+
begin, end = entry["data_offsets"]
88+
size -= end - begin
89+
return size
90+
91+
7192
def load(model_dir: Path, *, mtp_drafts: int | None = None, ple_on_ssd: bool = False,
7293
ssd_experts: float | None = None, **_: Any) -> tuple[Any, Any]:
7394
from tensorfold.families.qwen4_exp.runtime import load as load_runtime

‎src/tensorfold/families/qwen4_exp/host_table.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,23 @@
1515
_PARTS = ("weight", "scales", "biases")
1616

1717

18+
def ngrams_on_host(model_dir: Path, ssd: bool = False) -> bool:
19+
"""Host n-gram tables when read from SSD, else past the GPU working-set threshold (TF_NGRAM_HOST=0/1 overrides)."""
20+
21+
flag = os.environ.get("TF_NGRAM_HOST", "")
22+
if ssd:
23+
if flag == "0":
24+
raise ValueError("--ple-on-ssd reads the n-gram tables on the host: unset TF_NGRAM_HOST=0")
25+
return True
26+
if flag in ("0", "1"):
27+
return flag == "1"
28+
import mlx.core as mx
29+
30+
size = sum(p.stat().st_size for p in Path(model_dir).glob("model*.safetensors"))
31+
info = mx.device_info() if hasattr(mx, "device_info") else mx.metal.device_info()
32+
return size > 0.75 * int(info["max_recommended_working_set_size"])
33+
34+
1835
class HostTable:
1936
"""Keep n-gram shards memory-mapped on the host; gather copies only requested rows, never whole tables to the GPU."""
2037

‎src/tensorfold/families/qwen4_exp/model.py‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from mlx_lm.models.gated_delta import gated_delta_update
1717
from mlx_lm.models.switch_layers import SwitchGLU
1818

19+
from tensorfold.families.qwen4_exp.host_table import ngrams_on_host
1920
from tensorfold.families.qwen4_exp.model_layers import (
2021
Config,
2122
_derived,
@@ -328,21 +329,6 @@ def norms_stored_around_one(weights: dict[str, mx.array]) -> bool:
328329
return around_one
329330

330331

331-
def ngrams_on_host(model_dir: Path, ssd: bool = False) -> bool:
332-
"""Host n-gram tables when read from SSD, else past the GPU working-set threshold (TF_NGRAM_HOST=0/1 overrides)."""
333-
334-
flag = os.environ.get("TF_NGRAM_HOST", "")
335-
if ssd:
336-
if flag == "0":
337-
raise ValueError("--ple-on-ssd reads the n-gram tables on the host: unset TF_NGRAM_HOST=0")
338-
return True
339-
if flag in ("0", "1"):
340-
return flag == "1"
341-
size = sum(p.stat().st_size for p in Path(model_dir).glob("model*.safetensors"))
342-
info = mx.device_info() if hasattr(mx, "device_info") else mx.metal.device_info()
343-
return size > 0.75 * int(info["max_recommended_working_set_size"])
344-
345-
346332
def prefetch_ngrams(model: Qwen4Exp) -> None:
347333
"""Prefetch host n-gram pages after the first forwards to avoid displacing weights during loading."""
348334

‎tests/test_flash_next_memory.py‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
"""Flash Next startup counts file-backed n-grams separately, without loading checkpoint tensors or MLX."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
import struct
7+
import sys
8+
from types import ModuleType, SimpleNamespace
9+
10+
import pytest
11+
12+
from tensorfold import cli
13+
from tensorfold.families import qwen4_exp
14+
from tensorfold.families.qwen4_exp import host_table
15+
from tensorfold.server import memory_budget
16+
17+
GIB = 1024**3
18+
NGRAM = "language_model.model.layers.1.ple.ple_embedding.ngram_embedding"
19+
20+
21+
def _file(path, tensors):
22+
header = {"__metadata__": {"format": "mlx"}}
23+
offset = 0
24+
for name, size in tensors.items():
25+
header[name] = {"dtype": "U8", "shape": [size], "data_offsets": [offset, offset + size]}
26+
offset += size
27+
data = json.dumps(header).encode()
28+
data += b" " * (-len(data) % 8)
29+
with path.open("wb") as stream:
30+
stream.write(struct.pack("<Q", len(data)))
31+
stream.write(data)
32+
stream.truncate(8 + len(data) + offset) # sparse: only headers take disk space
33+
return path.stat().st_size
34+
35+
36+
def _checkpoint(path, main=4096, mapped=1600):
37+
(path / "config.json").write_text(json.dumps({
38+
"model_type": "qwen4_exp", "quantization": {"bits": 4, "group_size": 32},
39+
"max_position_embeddings": 262144,
40+
}))
41+
total = 0
42+
for shard in range(2):
43+
total += _file(path / f"model-{shard}.safetensors", {
44+
f"{NGRAM}.shard_{shard}.weight": mapped * 2 // 5,
45+
f"{NGRAM}.shard_{shard}.scales": mapped // 20,
46+
f"{NGRAM}.shard_{shard}.biases": mapped // 20,
47+
f"language_model.model.layers.{shard}.ple.key_proj.weight": main // 2,
48+
})
49+
total += _file(path / "mtp.safetensors", {"language_model.mtp.fc_hidden.weight": 64})
50+
return total
51+
52+
53+
@pytest.fixture
54+
def runtime(monkeypatch):
55+
core = ModuleType("mlx.core")
56+
core.device_info = lambda: {"max_recommended_working_set_size": 120 * GIB}
57+
core.set_memory_limit = lambda value: None
58+
core.set_cache_limit = lambda value: None
59+
mlx = ModuleType("mlx")
60+
mlx.core = core
61+
monkeypatch.setitem(sys.modules, "mlx", mlx)
62+
monkeypatch.setitem(sys.modules, "mlx.core", core)
63+
monkeypatch.delenv("TF_NGRAM_HOST", raising=False)
64+
monkeypatch.delenv("TENSORFOLD_MEMORY_LIMIT_GB", raising=False)
65+
monkeypatch.setattr(memory_budget, "physical_memory_bytes", lambda: 128 * GIB)
66+
monkeypatch.setattr("faulthandler.register", lambda *a, **k: None)
67+
return core
68+
69+
70+
@pytest.mark.parametrize("flag, fits", [(None, True), ("1", True), ("0", False)])
71+
def test_serve_fits_host_ngrams_within_the_original_budget(tmp_path, monkeypatch, runtime, flag, fits):
72+
_checkpoint(tmp_path, main=75 * GIB, mapped=30 * GIB)
73+
if flag is not None:
74+
monkeypatch.setenv("TF_NGRAM_HOST", flag)
75+
budgets = []
76+
monkeypatch.setattr(cli, "_serve_mlx", lambda args, family, path, context, required, budget, *rest:
77+
budgets.append(budget) or 0)
78+
args = cli.build_parser().parse_args(["serve", str(tmp_path), "--backend", "mlx", "--no-update-check"])
79+
if fits:
80+
assert cli.cmd_serve(args) == 0
81+
assert budgets == [int(0.70 * 128 * GIB)]
82+
else:
83+
with pytest.raises(ValueError, match=r"weights \(105\.0 GiB\) do not fit.*89\.6 GiB"):
84+
cli.cmd_serve(args)
85+
assert budgets == []
86+
87+
88+
@pytest.mark.parametrize("flag", [None, "1"])
89+
def test_host_mode_still_refuses_resident_weights_past_the_limit(tmp_path, monkeypatch, runtime, flag):
90+
_checkpoint(tmp_path, main=75 * GIB, mapped=30 * GIB)
91+
monkeypatch.setenv("TENSORFOLD_MEMORY_LIMIT_GB", "78") # exactly 75 GiB for buffers, no room for the head
92+
if flag is not None:
93+
monkeypatch.setenv("TF_NGRAM_HOST", flag)
94+
monkeypatch.setattr(cli, "_serve_mlx", lambda *a: pytest.fail("weights loaded past the budget"))
95+
args = cli.build_parser().parse_args(["serve", str(tmp_path), "--backend", "mlx", "--no-update-check"])
96+
with pytest.raises(ValueError, match=r"weights \(75\.0 GiB\) do not fit.*78\.0 GiB"):
97+
cli.cmd_serve(args)
98+
99+
100+
def test_only_mapped_table_tensors_are_subtracted(tmp_path, monkeypatch, runtime):
101+
total = _checkpoint(tmp_path)
102+
total += _file(tmp_path / "model-extra.safetensors", {
103+
f"{NGRAM}.shard_0.unrecognized": 128,
104+
"vision.ple_embedding.ngram_embedding.shard_0.weight": 256,
105+
"language_model.model.layers.1.ple.ple_embedding.ngram_heads_offsets": 64,
106+
})
107+
total += _file(tmp_path / "unused.safetensors", {f"{NGRAM}.shard_9.weight": 512})
108+
monkeypatch.setenv("TF_NGRAM_HOST", "1")
109+
assert qwen4_exp.weight_bytes(tmp_path) == total - 1600
110+
monkeypatch.setenv("TF_NGRAM_HOST", "0")
111+
monkeypatch.setattr(host_table, "read_header", lambda *a: pytest.fail("resident tables need no header scan"))
112+
assert qwen4_exp.weight_bytes(tmp_path) == total
113+
114+
115+
@pytest.mark.parametrize("flag, expected", [(None, True), ("1", True), ("0", False)])
116+
@pytest.mark.parametrize("legacy", [False, True])
117+
def test_host_selection_uses_the_loaders_threshold_and_overrides(tmp_path, monkeypatch, runtime, flag, expected, legacy):
118+
_checkpoint(tmp_path)
119+
model_size = sum(p.stat().st_size for p in tmp_path.glob("model*.safetensors"))
120+
runtime.device_info = lambda: {"max_recommended_working_set_size": model_size}
121+
if legacy:
122+
runtime.metal = SimpleNamespace(device_info=runtime.device_info)
123+
del runtime.device_info
124+
if flag is not None:
125+
monkeypatch.setenv("TF_NGRAM_HOST", flag)
126+
assert host_table.ngrams_on_host(tmp_path) is expected
127+
info = lambda: {"max_recommended_working_set_size": model_size * 2}
128+
if legacy:
129+
runtime.metal.device_info = info
130+
else:
131+
runtime.device_info = info
132+
assert host_table.ngrams_on_host(tmp_path) is (flag == "1")

0 commit comments

Comments
 (0)