Skip to content

Commit 70a6113

Browse files
Chedrian07ashhart
authored andcommitted
fix: release Flash Next probe states before memory admission
Default parallel startup retains the shared-forward probe's rollback buffers in Flash Next. The following prompt-memory probe then charges those unused rows as resident memory, leaving no prompt room on a 128 GiB Mac even after host n-grams are excluded. Implement the existing release_rounds family hook for backbone and MTP states, cache references and hidden rows. Preserve the prefill schedule and memory limits. Test prompt admission after release and real GPU buffer reclamation with bit-identical subsequent shared forwards.
1 parent 923c1f0 commit 70a6113

4 files changed

Lines changed: 91 additions & 16 deletions

File tree

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

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,18 @@ def make_cache(self) -> list[Any]:
9797
caches.append(MTPCache()) # last: the model's layers never reach it
9898
return caches
9999

100+
def release_rounds(self) -> None:
101+
"""Drop the last forward's rollback and draft rows when no stream is live; the next forward rebuilds them."""
102+
103+
for fused in (self.fused, getattr(self, "mtp_fused", None)):
104+
if fused is not None:
105+
fused.row_states.clear()
106+
fused._last_heads.clear()
107+
fused.last_streams = None
108+
self._streams = None
109+
self._specs.clear()
110+
self.model.__dict__.pop("last_streams", None)
111+
100112
def adopt_cache(self, cache: list[Any]) -> list[Any]:
101113
"""A stored or copied cache without an MTP entry gets an empty one (drafts then see less context)."""
102114

@@ -117,15 +129,6 @@ def prefill_key(self) -> str:
117129
raise RuntimeError("Flash Next's prefill arithmetic changed after the snapshot key was fixed: reload")
118130
return key
119131

120-
def release_rounds(self) -> None:
121-
"""Drop the last forward's per-row states and streams (no stream keeps rows of it; the next call sets them)."""
122-
123-
if self.fused is not None:
124-
self.fused.row_states = {}
125-
self.fused.last_streams = None
126-
self.fused._last_heads = []
127-
self._streams = None
128-
129132
def prefetch_prompt(self, tokens: Any, begin: int, end: int) -> None:
130133
"""Start reading the host n-gram rows prompt chunk [begin, end) will look up (tables on the host only)."""
131134

‎tests/test_prompt_memory.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,44 @@ def test_nemotron_releases_its_last_rounds_row_states():
489489
assert family.fused.row_states == {} and family._last_hidden is None
490490

491491

492+
@pytest.mark.parametrize("fused", [False, True])
493+
def test_flash_next_sizing_releases_probe_rows_and_draft_references(fused):
494+
import weakref
495+
496+
from tensorfold.families.qwen4_exp.runtime import FlashNext
497+
498+
class Buffer:
499+
pass
500+
501+
live = weakref.WeakSet()
502+
runtime = Runtime(resident=1000)
503+
active = runtime.get_active_memory
504+
runtime.get_active_memory = lambda: active() + 150_000 * len(live)
505+
memory = controller(budget=200_000, runtime=runtime)
506+
engine = ProbeEngine(runtime)
507+
family = FlashNext.__new__(FlashNext)
508+
family.model = SimpleNamespace()
509+
family.fused = SimpleNamespace(row_states={}, _last_heads=[]) if fused else None
510+
family.mtp_fused = SimpleNamespace(row_states={}, _last_heads=[]) if fused else None
511+
family._specs = {}
512+
engine.release_rounds = family.release_rounds
513+
514+
def probes():
515+
buffer = Buffer()
516+
live.add(buffer)
517+
family._streams = family.model.last_streams = buffer
518+
family._specs[0] = (buffer, 4)
519+
for decode in (family.fused, family.mtp_fused):
520+
if decode is not None:
521+
decode.row_states[0] = [(buffer, buffer, 0)]
522+
decode._last_heads.append(buffer)
523+
decode.last_streams = buffer
524+
return "admission"
525+
526+
assert memory.sized(engine, probes) == "admission"
527+
assert not live and memory.largest_window(8192) > 0
528+
529+
492530
def test_the_engine_releases_rounds_only_with_no_stream_live():
493531
engine = FakeEngine()
494532
calls = []

‎tests/test_qwen4_exp_family.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,10 +230,15 @@ def test_releasing_rounds_drops_the_last_forwards_rows():
230230

231231
from tensorfold.families.qwen4_exp.runtime import FlashNext
232232

233-
fused = SimpleNamespace(row_states={0: [("conv", "ssm", 0)]}, last_streams="streams", _last_heads=["head"])
234-
runtime = SimpleNamespace(fused=fused, _streams="streams")
233+
heads = [SimpleNamespace(row_states={0: [("conv", "ssm", 0)]}, last_streams="streams", _last_heads=["head"])
234+
for _ in range(2)]
235+
model = SimpleNamespace(last_streams="prompt streams")
236+
runtime = SimpleNamespace(fused=heads[0], mtp_fused=heads[1], _streams="streams", _specs={1: ("out", 2)},
237+
model=model)
235238
FlashNext.release_rounds(runtime)
236-
assert fused.row_states == {} and fused.last_streams is None and fused._last_heads == [] and runtime._streams is None
239+
for fused in heads:
240+
assert fused.row_states == {} and fused.last_streams is None and fused._last_heads == []
241+
assert runtime._streams is None and runtime._specs == {} and "last_streams" not in vars(model)
237242

238243

239244
def test_the_head_absorbs_every_prompt_row_into_its_cache_and_carries_only_the_last():

‎tests/test_qwen4_exp_prefill.py‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -328,22 +328,22 @@ def test_ngram_lookup_through_the_fused_tables_is_bit_identical():
328328
emb = q4bits(q4.NGramEmbedding(config(), 0))
329329
tables = K.PleTables(emb)
330330
tokens = np.random.default_rng(8).integers(6, 97, size=(1, 200))
331-
tokens[0, 50] = 5
331+
tokens[0, 50] = 5 # an EOS: the n-grams restart after it
332332
ids = emb.ids(np.full((1, emb.context), emb.eos, dtype=np.int64), tokens)
333333
ref = emb(ids)
334334
emb.__dict__["fused_tables"] = tables
335335
assert bool(mx.array_equal(emb(ids), ref).item())
336336

337337

338-
def tiny_model(seed: int = 0) -> q4.Qwen4Exp:
338+
def tiny_model(seed: int = 0, **overrides) -> q4.Qwen4Exp:
339339
"""Four layers (3 DeltaNet, 1 attention, PLE on the first), 512 wide, 32 experts, 4-bit but the router."""
340340

341341
from mlx.utils import tree_flatten
342342

343343
from tensorfold.families.qwen4_exp.decode import FusedDecode
344344

345345
mx.random.seed(seed)
346-
model = q4.Qwen4Exp(config(hidden_size=512, num_experts=32))
346+
model = q4.Qwen4Exp(config(**{"hidden_size": 512, "num_experts": 32, **overrides}))
347347
# centred norms start at zero; give them some weight so (1 + w) is exercised
348348
model.load_weights([(name, 0.1 * mx.random.normal(v.shape) if "norm" in name and name.endswith("weight") else v)
349349
for name, v in tree_flatten(model.parameters())])
@@ -357,7 +357,7 @@ def test_whole_model_prefill_is_as_exact_as_the_reference(monkeypatch):
357357
"""Two chunks, then four decode steps: the prefill path lands as close to fp32 as the bf16 reference does."""
358358

359359
tokens = np.random.default_rng(11).integers(6, 97, size=(1, 404))
360-
tokens[0, 100] = 5
360+
tokens[0, 100] = 5 # an EOS: the n-grams restart after it
361361

362362
def run(model, fused=None):
363363
cache = model.make_cache()
@@ -392,6 +392,35 @@ def error(a):
392392
assert fast_err < 1.2 * ref_err and fast_top > ref_top - 0.04, (fast_err, ref_err, fast_top, ref_top)
393393

394394

395+
def test_releasing_probe_rounds_frees_buffers_and_preserves_the_next_forward(monkeypatch):
396+
import gc
397+
import weakref
398+
399+
from tensorfold.families.qwen4_exp.runtime import FlashNext
400+
401+
monkeypatch.setattr(FlashNext, "check_windows", lambda self: (4, {1: 1.0, 4: 2.0}))
402+
model = tiny_model(vocab_size=128, moe_intermediate_size=512, shared_expert_intermediate_size=512)
403+
runtime = FlashNext(model, drafts=0)
404+
caches = [runtime.make_cache() for _ in range(2)]
405+
heads = [weakref.ref(cache[0]) for cache in caches]
406+
tokens = [[7, 11, 13, 17], [19, 23, 29]]
407+
logits = runtime.head(runtime.hidden_rows(tokens, caches))
408+
assert bool(mx.all(mx.isfinite(logits)).item())
409+
want = np.array(logits.view(mx.uint16))
410+
del logits
411+
del caches
412+
gc.collect()
413+
before = mx.get_active_memory()
414+
assert all(head() is not None for head in heads) # the last shared forward keeps these alive
415+
runtime.release_rounds()
416+
gc.collect()
417+
assert all(head() is None for head in heads)
418+
assert mx.get_active_memory() < before
419+
fresh = [runtime.make_cache() for _ in range(2)]
420+
got = np.array(runtime.head(runtime.hidden_rows(tokens, fresh)).view(mx.uint16))
421+
assert np.array_equal(got, want)
422+
423+
395424
def test_snapshot_keys_name_the_prefill_path(monkeypatch):
396425
from types import SimpleNamespace
397426

0 commit comments

Comments
 (0)