Skip to content

Commit 153f488

Browse files
Chedrian07ashhart
authored andcommitted
fix: allow explicit MLX budgets above the default RAM share
TENSORFOLD_MEMORY_LIMIT_GB now replaces the 70% default, capped by physical RAM and the GPU recommended working set. Keep the 3 GiB process reserve and honor the resolved budget in concurrent admission without changing lower-budget behavior. Cover raised and lowered limits, hardware caps, both device-info APIs, large finite values, concurrent admission under memory pressure and the CLI's allocator/server handoff. Update the memory guidance and startup help.
1 parent 70a6113 commit 153f488

5 files changed

Lines changed: 85 additions & 16 deletions

File tree

‎src/tensorfold/cli.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from typing import Any
1414

1515
from tensorfold import __version__
16+
from tensorfold.server.memory_budget import MEMORY_FRACTION
1617

1718
COMMANDS = ("serve", "pull", "models", "info", "update")
1819

@@ -69,7 +70,7 @@ def build_parser() -> argparse.ArgumentParser:
6970
speed.add_argument("--max-snapshots", type=int, default=3, help="system-block snapshots loaded at start")
7071
speed.add_argument("--parallel", default="auto",
7172
help="requests decoded together, their windows sharing each round's forward: a number, or "
72-
"auto (Mac: up to 8, each started only while the projected memory fits 70%% of RAM; "
73+
"auto (Mac: up to 8, each started only while the projected memory fits the budget; "
7374
"CUDA: one at a time, the others waiting their turn)")
7475
speed.add_argument("--mlx-cache-gib", type=float, default=8.0, help="MLX's cache of freed buffers")
7576
speed.add_argument("--ssd-experts", type=float, default=None, metavar="GIB",
@@ -357,8 +358,6 @@ def _serve_cuda(args: argparse.Namespace, family: Any, model_dir: Path, context:
357358
return 0
358359

359360

360-
# Admit concurrent requests within this RAM fraction, or the family's, after the rest of the machine.
361-
MEMORY_FRACTION = 0.70
362361
# a resume point begins a prompt chunk when at least this many tokens follow the last chunk start
363362
MIN_CHUNK = 256
364363

@@ -443,7 +442,7 @@ def cmd_serve(args: argparse.Namespace) -> int:
443442
stream = ("stream its routed experts from SSD with --ssd-experts GIB (slower), "
444443
if args.ssd_experts is None and hasattr(family.package, "expert_bytes") else "")
445444
raise ValueError(f"{family.title}'s weights ({weights / gib:.1f} GiB) do not fit this server's "
446-
f"{memory_limit / gib:.1f} GiB memory budget ({fraction:.0%} of RAM, or "
445+
f"{memory_limit / gib:.1f} GiB memory budget ({fraction:.0%} of RAM by default, or "
447446
f"TENSORFOLD_MEMORY_LIMIT_GB): serve it on a Mac with more memory, {stream}or use a smaller "
448447
"or more quantized checkpoint")
449448
return _serve_mlx(args, family, model_dir, context, required_files, memory_limit, fraction)

‎src/tensorfold/server/app.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,21 +186,24 @@ def __init__(
186186
self._warm_known_blocks(snapshot_dir, model_id)
187187

188188
def _admission(self, fraction: float, lanes: int) -> Any:
189-
"""Admit concurrent streams only within ``fraction`` of RAM minus memory held elsewhere on the machine."""
189+
"""Admit within the default RAM share or a larger process budget, accounting for memory held elsewhere."""
190190

191191
from tensorfold.engine import memory
192192

193193
stream = memory.measure(self.engine)
194194
used = memory._mlx_used()
195195
ram = memory.ram_bytes()
196196
elsewhere = memory.used_elsewhere(used)
197-
share = self.prompt_memory.budget if self.prompt_memory is not None else int(fraction * ram)
198-
admission = memory.Admission(min(int(fraction * ram) - elsewhere, share), stream,
197+
allowance = int(fraction * ram)
198+
share = self.prompt_memory.budget if self.prompt_memory is not None else allowance
199+
if self.prompt_memory is not None:
200+
allowance = max(allowance, self.prompt_memory.process_budget)
201+
admission = memory.Admission(min(allowance - elsewhere, share), stream,
199202
used=None if self.prompt_memory is None else self.prompt_memory.held)
200203
tokens = self.default_max_tokens + 4096
201204
gib, mib = 1024**3, 1024**2
202205
print(f"[tensorfold] concurrency: up to {lanes} requests share each round; memory budget "
203-
f"{admission.budget / gib:.1f} GB (MLX's share {share / gib:.1f} GB, or {fraction:.0%} of "
206+
f"{admission.budget / gib:.1f} GB (MLX's share {share / gib:.1f} GB, or {allowance / ram:.0%} of "
204207
f"{ram / gib:.0f} GB less {elsewhere / gib:.1f} GB in use elsewhere); a stream "
205208
f"{stream.short / mib:.0f} MB at {stream.short_tokens} tokens, "
206209
f"{stream.long / mib:.0f} MB at {stream.long_tokens:,}, then {stream.per_token / 1024:.1f} KB a token; "

‎src/tensorfold/server/memory_budget.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,12 @@ def model_fraction(package: Any, ram: int | None = None) -> float:
4747

4848
def memory_limit_bytes(mx: Any, *, fraction: float = MEMORY_FRACTION,
4949
environ: Mapping[str, str] | None = None, physical_bytes: int | None = None) -> int:
50+
"""The explicit process budget or the model's share of RAM, capped by physical memory and the GPU's working set."""
51+
5052
ram = physical_memory_bytes() if physical_bytes is None else int(physical_bytes)
5153
if ram <= 0:
5254
raise ValueError("physical memory must be positive")
5355
limit = int(fraction * ram)
54-
device_info = getattr(mx, "device_info", None)
55-
if device_info is None:
56-
device_info = getattr(getattr(mx, "metal", None), "device_info", None)
57-
recommended = int(device_info().get("max_recommended_working_set_size", 0)) if device_info else 0
58-
if recommended > 0:
59-
limit = min(limit, recommended)
6056
value = (os.environ if environ is None else environ).get(LIMIT_ENV)
6157
if value is not None:
6258
try:
@@ -65,7 +61,13 @@ def memory_limit_bytes(mx: Any, *, fraction: float = MEMORY_FRACTION,
6561
raise ValueError(f"{LIMIT_ENV} must be a positive number in GiB") from None
6662
if not math.isfinite(gib) or gib <= 0:
6763
raise ValueError(f"{LIMIT_ENV} must be a positive number in GiB")
68-
limit = min(limit, max(1, int(gib * GIB)))
64+
limit = max(1, int(min(gib, ram / GIB) * GIB))
65+
device_info = getattr(mx, "device_info", None)
66+
if device_info is None:
67+
device_info = getattr(getattr(mx, "metal", None), "device_info", None)
68+
recommended = int(device_info().get("max_recommended_working_set_size", 0)) if device_info else 0
69+
if recommended > 0:
70+
limit = min(limit, recommended)
6971
return limit
7072

7173

‎tests/test_flash_next_memory.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,21 @@ def test_host_mode_still_refuses_resident_weights_past_the_limit(tmp_path, monke
9797
cli.cmd_serve(args)
9898

9999

100+
def test_serve_passes_a_raised_budget_to_the_allocator_and_server(tmp_path, monkeypatch, runtime, capsys):
101+
_checkpoint(tmp_path, main=75 * GIB, mapped=30 * GIB)
102+
monkeypatch.setenv("TENSORFOLD_MEMORY_LIMIT_GB", "110")
103+
allocations, budgets = [], []
104+
runtime.set_memory_limit = allocations.append
105+
monkeypatch.setattr(cli, "_serve_mlx", lambda args, family, path, context, required, budget, *rest:
106+
budgets.append((budget, context, args.max_tokens)) or 0)
107+
args = cli.build_parser().parse_args(["serve", str(tmp_path), "--backend", "mlx", "--no-update-check",
108+
"--context", "262144", "--max-tokens", "131072"])
109+
assert cli.cmd_serve(args) == 0
110+
assert allocations == [107 * GIB]
111+
assert budgets == [(110 * GIB, 262144, 131072)]
112+
assert "memory budget 110.0 GiB: MLX's buffers up to 107.0 GiB" in capsys.readouterr().out
113+
114+
100115
def test_only_mapped_table_tensors_are_subtracted(tmp_path, monkeypatch, runtime):
101116
total = _checkpoint(tmp_path)
102117
total += _file(tmp_path / "model-extra.safetensors", {

‎tests/test_memory_budget.py‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,57 @@ def test_mlx_buffers_are_capped_at_the_budget_less_the_rest_of_the_process():
8686
assert configure_mlx(mx, GIB // 2, environ={}, physical_bytes=48 * GIB) == int(0.70 * 48 * GIB)
8787
assert calls == [("memory", int(0.70 * 48 * GIB) - PROCESS_BYTES), ("cache", GIB // 2)]
8888
budget = memory_limit_bytes(mx, environ={"TENSORFOLD_MEMORY_LIMIT_GB": "1000"}, physical_bytes=48 * GIB)
89-
assert budget == int(0.70 * 48 * GIB)
89+
assert budget == 48 * GIB
90+
91+
92+
@pytest.mark.parametrize("legacy", [False, True])
93+
@pytest.mark.parametrize("value, recommended, expected", [
94+
("64", 120, 64), ("110", 120, 110), ("110", 96, 96), ("1000", 256, 128),
95+
("110", 0, 110), ("1e308", 0, 128),
96+
])
97+
def test_explicit_budget_can_raise_or_lower_the_default_within_hardware_limits(legacy, value, recommended, expected):
98+
info = SimpleNamespace(device_info=lambda: {"max_recommended_working_set_size": recommended * GIB})
99+
mx = SimpleNamespace(metal=info) if legacy else info
100+
assert memory_limit_bytes(mx, environ={"TENSORFOLD_MEMORY_LIMIT_GB": value},
101+
physical_bytes=128 * GIB) == expected * GIB
102+
103+
104+
def test_raised_budget_keeps_the_process_reserve_and_cache_limit():
105+
calls = []
106+
mx = SimpleNamespace(device_info=lambda: {"max_recommended_working_set_size": 120 * GIB},
107+
set_memory_limit=lambda n: calls.append(("memory", n)),
108+
set_cache_limit=lambda n: calls.append(("cache", n)))
109+
assert configure_mlx(mx, 8 * GIB, environ={"TENSORFOLD_MEMORY_LIMIT_GB": "110"},
110+
physical_bytes=128 * GIB) == 110 * GIB
111+
assert calls == [("memory", 107 * GIB), ("cache", 8 * GIB)]
112+
113+
114+
@pytest.mark.parametrize("limit, elsewhere, expected", [
115+
(None, 0, int(0.70 * 128 * GIB) - PROCESS_BYTES),
116+
(None, 8, int(0.70 * 128 * GIB) - 8 * GIB),
117+
("110", 0, 107 * GIB), ("110", 8, 102 * GIB), ("64", 20, 61 * GIB),
118+
])
119+
def test_concurrent_admission_respects_the_resolved_budget_and_other_processes(monkeypatch, capsys,
120+
limit, elsewhere, expected):
121+
from tensorfold.engine import memory
122+
from tensorfold.server.app import ChatApp
123+
124+
environ = {} if limit is None else {"TENSORFOLD_MEMORY_LIMIT_GB": limit}
125+
budget = memory_limit_bytes(SimpleNamespace(), environ=environ, physical_bytes=128 * GIB)
126+
app = ChatApp.__new__(ChatApp)
127+
app.engine, app.default_max_tokens = object(), 4096
128+
app.prompt_memory = SimpleNamespace(process_budget=budget, budget=budget - PROCESS_BYTES,
129+
held=lambda: 90 * GIB)
130+
monkeypatch.setattr(memory, "ram_bytes", lambda: 128 * GIB)
131+
monkeypatch.setattr(memory, "used_elsewhere", lambda own: elsewhere * GIB)
132+
monkeypatch.setattr(memory, "_mlx_used", app.prompt_memory.held)
133+
monkeypatch.setattr(memory, "measure", lambda engine: memory.StreamMemory(64, 1024, 2112, 2048, 1, 1, 0, 1024))
134+
admission = app._admission(0.70, 8)
135+
assert admission.budget == expected
136+
assert admission.used == app.prompt_memory.held
137+
if limit == "110":
138+
assert admission.admits(64, 128, []) # a model above the old 89.6 GiB ceiling still has request room
139+
assert "86% of 128 GB" in capsys.readouterr().out
90140

91141

92142
@pytest.mark.parametrize("value", ["", "0", "-1", "nan", "inf", "12GB"])

0 commit comments

Comments
 (0)