Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
b523c90
Flash Next: opt-in continuous batching on native Metal
cwschroeder Oct 10, 2026
fd272ef
Preserve alternating benchmark receipts on the current upstream base
cwschroeder Oct 10, 2026
0c8d4d5
Apply Zig 0.17 formatting required by current CI
cwschroeder Oct 10, 2026
6dbf170
Flash Next: chain batch MTP drafts in one Metal command buffer
cwschroeder Oct 10, 2026
39824c6
Qualify experimental batch MTP chaining on M3 Ultra
cwschroeder Oct 10, 2026
77ebc3f
Attach final current-base host validation receipt
cwschroeder Oct 10, 2026
a5e409e
Flash Next shared sessions: FLASHNEXT_LOAD_LIMIT_GB lets the slots ta…
BobClawblaw Oct 11, 2026
1874ffe
Flash Next shared sessions sample: a request's temperature draws each…
BobClawblaw Oct 12, 2026
b7372ac
Flash Next's host sampler: an unlimited or wide top-k by a counting s…
BobClawblaw Oct 12, 2026
03cc874
FLASHNEXT_LOAD_LIMIT_GB covers the prompt cache too: the automatic bu…
BobClawblaw Oct 12, 2026
d519c08
Flash Next's wide top-k draw keeps a uniform that rounds to 1: its +i…
BobClawblaw Oct 12, 2026
5d59c76
Merge #8 from BobClawblaw: Flash Next shared sessions: FLASHNEXT_LOAD…
cwschroeder Oct 13, 2026
c930303
Merge #7 from BobClawblaw: Flash Next shared sessions sample: a reque…
cwschroeder Oct 13, 2026
04c8571
Merge upstream main (TensorFold 1.0.8) into Flash Next continuous bat…
cwschroeder Oct 13, 2026
3f24b00
Flash Next shared rounds priced from forwards timed at load; every st…
sethforprivacy Oct 12, 2026
5551aba
Flash Next shared sessions sized to the traffic: FLASHNEXT_SLOT_CONTE…
sethforprivacy Oct 12, 2026
a3085be
Flash Next: a lone request on the engine's GPU-side rounds, handed to…
sethforprivacy Oct 12, 2026
ba31b91
Flash Next sized sessions: grow on the reply's remaining work, never …
Oct 13, 2026
dd86083
Flash Next shared-round prices: time only on a session that holds the…
Oct 13, 2026
09c7262
Flash Next lone driver: read the prompt after the first token's commi…
Oct 13, 2026
3cb70f0
Merge #9 from sethforprivacy: Flash Next shared rounds priced from fo…
cwschroeder Oct 14, 2026
59df001
Merge feat/flashnext-continuous-batching (#9) into flashnext-batch-lone
Oct 14, 2026
0f679e2
Flash Next lone driver: lone's doc comment above lone again (commitFi…
Oct 14, 2026
198b3c5
Merge feat/flashnext-continuous-batching (#9) into flashnext-batch-se…
Oct 14, 2026
b1a4204
Flash Next: facts' priced-lone flag renamed from `lone`, which the me…
Oct 14, 2026
069ef4d
Flash Next sized sessions: a paused stream whose move fails ends with…
Oct 14, 2026
f70705a
Merge Flash Next batching onto current upstream, preserve both head c…
cwschroeder Oct 16, 2026
2f69e55
Merge reviewed lone-driver fixes alongside measured batching costs
cwschroeder Oct 16, 2026
15e424e
Merge sized sessions and migration failure handling with lone handoff
cwschroeder Oct 16, 2026
72d817c
Finish migration-failed peers after cancellation before freeing their…
cwschroeder Oct 16, 2026
1d0f0df
Port shared Flash Next session bindings to current upstream
cwschroeder Oct 16, 2026
dd1b741
Serve default Flash Next requests on memory-sized shared sessions
cwschroeder Oct 16, 2026
4e184b2
Retain shared-family tests after extracting the first-token lifetime …
cwschroeder Oct 16, 2026
fac5563
Describe the default shared route consistently in the README and recipe
cwschroeder Oct 16, 2026
f36482a
Gate default Flash Next serving with observed shared GPU rounds
cwschroeder Oct 16, 2026
b038a3d
Preserve Flash Next residency and lifecycle after the upstream rebase
cwschroeder Oct 16, 2026
8cee8ef
Draw shared Flash Next picks with the upstream GPU sampler
cwschroeder Oct 16, 2026
d0f6138
Avoid a second warmup when auto falls back to one Flash Next session
cwschroeder Oct 16, 2026
ef85c8b
Honor validated model load limits when keeping buffers resident
cwschroeder Oct 16, 2026
5164380
Refuse --parallel above one with --learn as with --speed-up; restore …
cwschroeder Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Flash Next: opt-in continuous batching on native Metal
Pack session windows into one target layer loop behind the shared lane core. Isolate recurrent and attention caches, normalize kept states with a fenced GPU copy, preserve draft and snapshot semantics, and keep the single-reply and TP drivers as defaults. Include CPU metadata contracts, checkpoint exactness/lifecycle gates and served concurrency comparisons.
  • Loading branch information
cwschroeder committed Oct 10, 2026
commit b523c900bb110b22012af8e2f8891b3363edd499
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ Every accepted draft must equal the token the same native engine would produce w
A resumed request must equal fresh execution, and each concurrent stream must equal its solo run.
The comparison fixes the checkpoint, backend, settings and runtime.
Different quantizations and different backends can produce different outputs.
Flash Next and Qwen3.8-27B run one active reply per engine; Nemotron, GLM and the 2B model use shared lane rounds.
Flash Next on Metal uses shared target rounds with an explicit `--parallel N` above one on a single Mac.
Its default `auto`, `--parallel 1` and two-Mac speed-up mode serve one active reply; MTP heads remain serial.
On Metal, Qwen3.8-27B runs one active reply per engine; Nemotron, GLM and the 2B model use shared lane rounds.

## Models on disk

Expand Down
8 changes: 8 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b
}) });
b.installArtifact(reuse);
b.step("tf-flashnext-reuse", "Flash Next prompt reuse against fresh prompt passes: replies at every depth and kept states' bytes").dependOn(&b.addInstallArtifact(reuse, .{}).step);
const batch = b.addExecutable(.{ .name = "tf-flashnext-batch", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/flashnext_batch.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } },
}) });
b.step("tf-flashnext-batch", "Flash Next shared rounds against fresh legacy replies with prompt admission and cancellation").dependOn(&b.addInstallArtifact(batch, .{}).step);
return exe;
}

Expand Down
43 changes: 43 additions & 0 deletions docs/recipes/qwen3.8-flash-next.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,49 @@ path, resolved matmul route and GPU identity; changing arithmetic requires a fre
Load-time shared-forward checks compare each stream with its own call. A failed check limits forwards
to one stream, while successful checks allow the lane engine to combine requests.

## Native Metal shared sessions

The native 6-bit MTP engine enables shared target rounds with an explicit `--parallel N` above one:

```bash
tensorfold-native serve TensorFold/Qwen3.8-Flash-Next-MLX-6bit-MTP \
--parallel 4 --context 16384 --temperature 0
```

Each request holds its own recurrent state, attention cache, n-gram history and MTP cache. The scheduler packs
up to 16 target rows, including draft rows, into one layer loop. Projections and experts process those rows
together; recurrence, convolution and attention read each request's own state. MTP heads draft serially.
New requests join between rounds, and cancelling a request releases its slot for another request.

`auto` and `--parallel 1` retain the existing single-reply driver. Shared sessions currently run on one Mac;
`--parallel N` above one with `--speed-up` is refused. Use `--parallel 1` for the two-Mac link.

Additional slots allocate caches for the selected context. Startup reserves their metadata and the prompt-cache
budget, then checks the physical footprint before accepting requests. A fixed slot count that does not fit is
refused; lower the count, context or prompt-cache budget. `--prompt-cache-over-cap` overrides only the prompt-cache
budget. Greedy decoding remains required, so clients must send temperature 0.

The checkpoint gate compares shared replies with fresh legacy replies, with drafting off and on, then checks
prompt admission, cancellation, slot reuse and a restored prefix while another request remains active:

```bash
zig build tf-flashnext-batch
python tools/zig/flashnext_batch_prompts.py MODEL_DIR /tmp/flashnext-prompts
FZ_N=128 zig-out/bin/tf-flashnext-batch MODEL_DIR /tmp/flashnext-prompts/*.json
```

Run with one model process on the GPU. For a served comparison with identical requests and settings:

```bash
zig build native
python tools/zig/flashnext_batch_serve.py zig-out/native/bin/tensorfold-native \
MODEL_DIR /tmp/flashnext-prompts /tmp/flashnext-served --parallel 1,4
```

The served gate starts one server at a time on loopback port 52417, compares response bodies with the serial
reference and records wall time, generated tokens and peak running and waiting requests. End-to-end time includes
the prompts. The checkpoint gate separately establishes exact token equality.

## CUDA

On CUDA Flash Next serves NVFP4 and EXL3 checkpoints, and the MLX 4-bit checkpoint as the portable option: the same
Expand Down
36 changes: 36 additions & 0 deletions tools/zig/flashnext_batch_prompts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Write public, deterministic token fixtures for tf-flashnext-batch using a local checkpoint tokenizer."""
import argparse
import json
from pathlib import Path

from transformers import AutoTokenizer


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("model", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True)
args.output.mkdir(parents=True, exist_ok=True)
cases = [
("short", "List the first twenty prime numbers, with no introduction.", False),
("thinking", "Explain why a square root of two cannot be a rational number.", True),
("sparse", "\n".join(f"Item {i}: value {i % 97}." for i in range(240))
+ "\nSummarize the list and explain how the values repeat.", False),
("sparse-thinking", "\n".join(f"Row {i}: the box contains {i % 31} blue counters." for i in range(720))
+ "\nDescribe an algorithm to calculate the total number of blue counters.", True),
]
for name, text, thinking in cases:
tokens = tokenizer.apply_chat_template(
[{"role": "user", "content": text}], tokenize=True,
add_generation_prompt=True, enable_thinking=thinking, return_dict=False,
)
path = args.output / f"{name}.json"
path.write_text(json.dumps({"prompt": tokens, "text": text, "thinking": thinking}) + "\n")
print(f"{path.name}: {len(tokens)} prompt tokens, thinking={thinking}")


if __name__ == "__main__":
main()
159 changes: 159 additions & 0 deletions tools/zig/flashnext_batch_serve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Compare serial and shared native HTTP replies on identical public fixtures, with one server at a time."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import subprocess
import threading
import time
import urllib.request


BASE = "http://127.0.0.1:52417"


def get(path):
with urllib.request.urlopen(BASE + path, timeout=3) as response:
return response.read().decode()


def request(case, tokens, gate):
payload = {
"model": "batch-gate", "messages": [{"role": "user", "content": case["text"]}],
"max_tokens": tokens, "temperature": 0, "stream": False,
"chat_template_kwargs": {"enable_thinking": case["thinking"]},
}
gate.wait()
start = time.monotonic()
req = urllib.request.Request(BASE + "/v1/chat/completions", json.dumps(payload).encode(),
{"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=300) as response:
result = json.load(response)
choice = result["choices"][0]
usage = result["usage"]
token_sha = result["tensorfold"].get("token_sha")
if not isinstance(token_sha, str) or len(token_sha) != 12 or any(c not in "0123456789abcdef" for c in token_sha):
raise RuntimeError("missing native token fingerprint")
prompt = usage["prompt_tokens"]
cached = usage["prompt_tokens_details"]["cached_tokens"]
tokens = usage["completion_tokens"]
if type(prompt) is not int or prompt < 1 or type(cached) is not int or cached != 0 or type(tokens) is not int or tokens < 1:
raise RuntimeError("invalid token counts or unexpected prefix reuse")
return {
"reply": {"message": choice["message"], "finish_reason": choice["finish_reason"]},
"tokens": tokens, "prompt_tokens": prompt, "cached_tokens": cached, "token_sha": token_sha,
"seconds": time.monotonic() - start,
}


def run(args, slots, cases):
log_path = args.output / f"serve-{slots}.log"
with log_path.open("w") as log:
process = subprocess.Popen([
str(args.binary), "serve", str(args.model), "--name", "batch-gate", "--host", "127.0.0.1",
"--port", "52417", "--context", "16384", "--parallel", str(slots),
"--temperature", "0", "--prompt-cache-gib", "0", "--no-update-check",
], stdout=log, stderr=subprocess.STDOUT)
(args.output / "server.pid").write_text(str(process.pid) + "\n")
try:
deadline = time.monotonic() + 240
while time.monotonic() < deadline:
if process.poll() is not None:
raise RuntimeError(f"native server exited {process.returncode}; inspect {log_path.name}")
try:
health = json.loads(get("/health"))
if health.get("status") == "ok" and not health.get("warming", False):
break
except (OSError, ValueError):
pass
time.sleep(0.2)
else:
raise TimeoutError("native server startup")
batches = []
for iteration in range(args.rounds):
stop = threading.Event()
peaks = [0, 0]

def monitor():
while not stop.is_set():
try:
for line in get("/v1/metrics").splitlines():
for index, key in enumerate(("tensorfold:requests_running", "tensorfold:requests_waiting")):
if line.startswith(key + " "):
peaks[index] = max(peaks[index], int(float(line.split()[1])))
except (OSError, ValueError):
pass
stop.wait(0.05)

watcher = threading.Thread(target=monitor, daemon=True)
watcher.start()
start = time.monotonic()
try:
gate = threading.Barrier(len(cases))
with ThreadPoolExecutor(max_workers=len(cases)) as pool:
futures = [pool.submit(request, case, args.tokens, gate) for case in cases]
results = [future.result() for future in futures]
seconds = time.monotonic() - start
finally:
stop.set()
watcher.join(timeout=4)
generated = sum(result["tokens"] for result in results)
batch = {"iteration": iteration, "seconds": seconds, "tokens": generated,
"tokens_per_second": generated / seconds, "peak_running": peaks[0],
"peak_waiting": peaks[1], "results": results}
batches.append(batch)
print(json.dumps({"parallel": slots, **{key: batch[key] for key in
("iteration", "seconds", "tokens", "tokens_per_second", "peak_running", "peak_waiting")}}), flush=True)
return batches
finally:
process.terminate()
try:
process.wait(timeout=15)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
(args.output / "server.pid").unlink(missing_ok=True)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary", type=Path)
parser.add_argument("model", type=Path)
parser.add_argument("fixtures", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--tokens", type=int, default=128)
parser.add_argument("--rounds", type=int, default=3)
parser.add_argument("--parallel", default="1,4")
args = parser.parse_args()
if args.tokens < 1 or args.rounds < 1:
parser.error("tokens and rounds must be positive")
slots = [int(value) for value in args.parallel.split(",")]
if not slots or slots[0] != 1 or any(value < 1 or value > 16 for value in slots):
parser.error("parallel must start with 1 and stay within 1..16")
args.output.mkdir(parents=True, exist_ok=True)
cases = [json.loads((args.fixtures / f"{name}.json").read_text()) for name in
("short", "thinking", "sparse", "sparse-thinking")]
receipt = {"reply_token_limit": args.tokens, "rounds": args.rounds, "runs": {}}
reference = None
for count in slots:
batches = run(args, count, cases)
receipt["runs"][str(count)] = batches
for batch in batches:
replies = [{key: result[key] for key in ("reply", "tokens", "prompt_tokens", "token_sha")}
for result in batch["results"]]
if reference is None:
reference = replies
if replies != reference:
receipt["exact"] = False
(args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
raise RuntimeError("HTTP replies differ from serial reference")
if count > 1 and not any(batch["peak_running"] > 1 for batch in batches):
raise RuntimeError("no simultaneous HTTP sessions observed")
(args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
receipt["exact"] = True
(args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions zig/flashnext_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
test {
_ = @import("src/families/flashnext/host_test.zig");
_ = @import("src/families/flashnext/pack.zig");
_ = @import("src/families/flashnext/batch_meta_test.zig");
}
Loading