Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Persisted prompt states (the prompt cache's disk tier and `--learn-conversations`): every family that saves states to disk now keys them by what its loaded run actually computed with, not only the flags as set: resolved arithmetic and kernel choices, every indexed weight shard (subfolders included), and external loaded inputs such as the CUDA Qwen rotary table, a Flash Next pack outside its folder, Flash Next on CUDA's chunk heights and kernel forms, and Nemotron's precision, expert ranks, ModelOpt lane and captured attention variant. A state computed differently now misses instead of resuming, and a resumed state still equals a fresh one. Upgrading starts every kept state once cold, and so does changing a GLM or Qwen Metal prompt chunk height. `GLM_EHPROJ_NAX` now takes only `0` or `1`; other text, which used to read as on, is refused at start (#2287, part of #2131).

- Docs: a reply that quotes a template marker can finish with `ignore_eos` and a stop list for the model's end-of-text and next-turn-open spellings, then a strip of the trailing turn marker; measured on two Qwen checkpoints on a GB10, with the agent-shaped runs reported in #2399 (#2437, refs #2399). Thanks to @javierbits and @robertung88.
- Conformance: the cancel and evict gates check that a cut reply and an evicted prompt leave the server as a fresh one, with a planted fault for each; the Qwen3.8-27B Metal profile skips evict with its measured reason, and the CUDA profiles run both (#2611). Thanks to @jschmied.

Expand Down
1 change: 1 addition & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi
| `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 |
| `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default |
| `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero |
| `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds |
| `XPU_A8_BITS` | Exactly `4` or `8`, for the XPU quantization study; unset keeps the study's existing setting |
| `LFM3_FUSE` | Whole u32 fusion mask; default 7 |
| `TF_SLIDE_POCKET_KEY` | Exactly `auto`, `reply`, `subject` or `both`; default `auto` |
Expand Down
48 changes: 39 additions & 9 deletions docs/recipes/persisted-serving-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ Old files remain in their original namespace and follow the existing cache budge

| Persistence owner | Source and arithmetic | Checkpoint | KV and draft state | Weight learning |
| --- | --- | --- | --- | --- |
| Nemotron, Metal | Binary, kernel texts, precision mode, probe, OS build and GPU | Config, index, shard stamps and MTP header | Canonical snapshot, head flag and probe | Shared host clears RAM and detaches disk stores when weights move |
| Dense Qwen hybrid, Metal | Binary, shared/family shader texts, tensor/ANE modes, probe, OS build and GPU | Config, index and shard stamps for target and external drafter | Canonical recurrence/KV/tap image and draft end | Unsupported learners refuse; the store remains scoped to its loaded model |
| GLM, Metal | Binary, compiled source hash, rank/chunk modes, probe, OS build and GPU | Config/index identity plus current shard stamps | Canonical KDA/MLA image and checked snapshot header | Unsupported learner on this adapter |
| Flash Next, Metal | Binary, actual loaded shader texts/bindings, rotary/precision policy, probe, OS build and GPU | Pack metadata identity plus current shard stamps | Checked snapshot layout; canonical session image | Unsupported learner on this adapter |
| Nemotron, CUDA | Binary, embedded images, captured manifest and cubin bytes, probe, GPU and driver | Config, index and shard stamps | Head flag and canonical state image | Shared host clears RAM and detaches disk stores when weights move |
| Qwen dense/MoE hybrids, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Explicit BF16/FP8 format, tap flag and prompt-int8 mode; image states stay off disk | Same shared learning barrier |
| Flash Next, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Head flag and canonical recurrence/KV/PLE image; tensor-rank disk persistence is refused | Same shared learning barrier |
| Nemotron, Metal | Binary, kernel texts, precision mode, prompt step, loaded coop K-slice split and its scratch rows, probe, OS build and GPU | Config, index, shard stamps and MTP header | Canonical snapshot, head flag and probe | Shared host clears RAM and detaches disk stores when weights move |
| Dense Qwen hybrid, Metal | Binary, shared/family shader texts, tensor mode, loaded ANE columns and prompt policy, probe, OS build and GPU | Config, index and shard stamps for target and external drafter | Canonical recurrence/KV/tap image and draft end | Unsupported learners refuse; the store remains scoped to its loaded model |
| GLM, Metal | Binary, compiled source hash, resolved rank/route/prompt policy, probe, OS build and GPU | Config/index identity plus current shard stamps | Canonical KDA/MLA image and checked snapshot header | Unsupported learner on this adapter |
| Flash Next, Metal | Binary, actual loaded shader texts/bindings, rotary/precision and resolved execution policy, probe, OS build and GPU | Pack metadata identity, current source and loaded-pack stamps, loaded reference bytes | Checked snapshot layout; canonical session image | Unsupported learner on this adapter |
| Nemotron, CUDA | Binary, embedded images, captured manifest and cubin bytes, resolved checkpoint math, expert ranks, NVFP4 decode form, lane half-tile threshold, expert grids and captured attention variant, probe, GPU and driver | Config, index and shard stamps | Head flag and canonical state image | Shared host clears RAM and detaches disk stores when weights move |
| Qwen dense/MoE hybrids, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Explicit BF16/FP8 format, tap flag, prompt-int8 mode and actual rotary table; image states stay off disk | Same shared learning barrier |
| Flash Next, CUDA | Same shared CUDA identity, plus resolved prompt chunk heights, prompt kernel forms and tile thresholds, expert grids and captured-set use | Same shared checkpoint identity | Head flag and canonical recurrence/KV/PLE image; tensor-rank disk persistence is refused | Same shared learning barrier |
| DeepSeek sessions, CUDA reference path | Config/options/mode, checkpoint digest, rank, selected layers and piece layout | Checkpoint digest required | Versioned lossless session pieces and exact token prefix | No learner; the disk tier starts fresh for each process |

Other native family adapters have no attached cross-process serving-state tier. Their snapshots remain owned by one
Expand All @@ -28,11 +28,40 @@ boundaries, while the shared cache compares decoded spans and image identities.
rendered answer text. No separate hot-swappable LoRA state is admitted by these persistence adapters; checkpoint
changes and supported external drafters use the identities above.

GLM and Flash Next now include safetensors shard names, sizes, inode and modification/change stamps. A weight
Checkpoint keys include every validated indexed shard path, including subfolders and any suffix accepted by the loader, plus
auxiliary top-level safetensors files. Their names, sizes, inodes and modification/change stamps are bound. A weight
write with unchanged config, index, tensor header and size moves their namespace even when a fixed probe does not
visit the changed tensor. Flash Next also hashes the loaded variant text and input/output/meta bindings in sorted
function-name order. Captured CUDA sets hash each cubin named by the parsed manifest, through the same loader
paths and size limit. A missing or changed file fails identity construction instead of opening an old namespace.
paths and size limit. A missing or changed file fails identity construction instead of opening an old namespace;
a shard the index names but the folder lacks is refused as `IndexedShardMissing`, as the loaders refuse it.

Resolved policies are bound even when a fixed startup probe does not exercise their difference. The Metal Qwen
key includes loaded ANE columns and the prompt chunk height, not the frame's buffer rows. GLM includes effective
rank slices, routing, its prompt chunk height and sparse kernel, and whether the MTP head's prompt eh_proj runs on
the tile kernel as the load built it (`GLM_EHPROJ_NAX=0` or a failed tile build: scalar). A different chunk height
starts these two stores cold: GLM's prompt windows and chunks sum in different orders (#743), and Qwen's may too.
Flash Next includes its resolved execution branches, including the DeltaNet window kernels, but not the serial
encoder choice, which orders the same launches. It also binds stamps of the files actually indexed (including an
external weight pack) and the bytes of loaded metadata such as a supplied reference. Descriptor and mapping order
do not change that key. CUDA Qwen keys include the rotary table the target consumes, for dense and routed
checkpoints. These additions change the optional disk namespace; snapshot payloads and layouts are unchanged.

Flash Next on CUDA keys what its prompt passes resolved at load: the solo and busy chunk heights (a different
`TF_FLASHNEXT_CHUNK` or `_CHUNK_SOLO`, or `--parallel 1` taking the larger pass, starts cold), the DeltaNet, read-out,
hyper-connection and in-pass mark forms, the NVFP4 prompt-tile threshold, K32 tile, BF16 prompt tiles and the SM count
they are weighed against, the lane's half-tile threshold (`TF_QMMF_HALF_BELOW`), the experts' decode warps and resident
grids, and whether a captured set runs with which entries on our glue. `TF_FLASHNEXT_KV_PAGES` and `_KV_PAGES_ALL` are
keyed through the profile rows. Its draft, window, round, graph, lane-parts (`TF_FLASHNEXT_LANE_PARTS`), load-thread, I/O and dense-split settings and
`TF_FLASHNEXT_KV_PAGE_TEST` are not keyed: kept states come only from prompt passes, which those settings either never
reach, reach with the same launches or the same kernels addressing pages, or refuse for disk at `--tp 2`.
Nemotron on CUDA keys `--precision checkpoint`'s math, the expert ranks of `TF_NEMOTRON_WORLD`, a ModelOpt
checkpoint's NVFP4 decode warps and lane half-tile threshold, the experts' resident grids and, with a captured set, the
attention variant `--context` picks by its chunk count. Its pages, poison fill, carveout, segments, graph log and trace,
and the context on our own glue, are not keyed: they place memory, fill pages before use, log, run only passes that
keep no state (segments), or set a stride our merge ignores. Nemotron on Metal also keys `TF_COOP_SPLIT` as loaded and,
with the split on, the scratch rows a prompt chunk's partials must fit; its page plan and stream count otherwise only
size buffers.

The executable and kernel fingerprints use a 32 KiB read buffer and check file stamps across the read. Checkpoints,
executables and kernel assets must remain stable while a model opens and serves. The existing learner owns runtime
Expand All @@ -43,6 +72,7 @@ Host checks:
```sh
zig build test-persistence-identity-host test-cuda-persistence-source-host compile-persistence-host -j1
zig build test-checkpoint-identity test-cuda-disk-open-host test-sessions test-frame-cache-identity-host -j1
zig build test-disk-identity-host -j1
```

The first command's Metal consumer compile and checkpoint fixtures require a macOS host but execute no GPU call.
Expand Down
6 changes: 5 additions & 1 deletion zig/build/cuda_family_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B
b.step("test-qwen35-metal-scope-host", "Metal 2B format admission without device or Metal compiler").dependOn(&metal_scope.step);
@import("load_prefetch_host.zig").tests(b, mods.core, step);
const captured = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/cuda/aot_identity.zig"), .target = host, .link_libc = true }), .filters = &.{"persistence identity: captured CUDA"} }));
b.step("test-cuda-persistence-source-host", "Captured CUDA source keys without loading a driver").dependOn(&captured.step);
const wiring = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/nemotron_key_wiring_test.zig"), .target = host }) }));
const source_keys = b.step("test-cuda-persistence-source-host", "Captured CUDA source keys and Nemotron key wiring without loading a driver");
source_keys.dependOn(&captured.step);
source_keys.dependOn(&wiring.step);
step.dependOn(&captured.step);
step.dependOn(&wiring.step);

b.step("test-qwen35-request-starts-host", "Request-start and shared-KV startup refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"request starts:"} })).step);
@import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step);
Expand Down
45 changes: 45 additions & 0 deletions zig/nemotron_key_wiring_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//! Nemotron's disk and learned keys take their resolved policies where the keys are made, read from the source.
const std = @import("std");

/// The block of the function `head` opens, brace to matching brace, with no whitespace or line comments.
fn body(a: std.mem.Allocator, source: []const u8, head: []const u8) ![]const u8 {
const at = std.mem.indexOf(u8, source, head) orelse return error.FunctionMissing;
const open = at + (std.mem.indexOf(u8, source[at..], "{\n") orelse return error.FunctionMissing);
var out: std.ArrayList(u8) = .empty;
var depth: usize = 0;
var lines = std.mem.splitScalar(u8, source[open..], '\n');
while (lines.next()) |whole| {
const line = if (std.mem.indexOf(u8, whole, "//")) |c| whole[0..c] else whole;
for (line) |ch| {
if (!std.ascii.isWhitespace(ch)) try out.append(a, ch);
if (ch == '{') depth += 1;
if (ch == '}') {
depth -= 1;
if (depth == 0) return out.items;
}
}
}
return error.FunctionUnclosed;
}

fn expectCall(source: []const u8, head: []const u8, call: []const u8) !void {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const b = try body(arena.allocator(), source, head);
if (std.mem.indexOf(u8, b, call) == null) std.debug.print("`{s}` no longer has `{s}`\n", .{ head, call });
try std.testing.expect(std.mem.indexOf(u8, b, call) != null);
}

test "persistence identity: Nemotron CUDA's disk key extends its identity with the policy the engine resolved" {
try expectCall(@embedFile("src/native/cuda_disk.zig"), "pub fn identity(", "return.{.id=withPolicy(id,t.e),");
}

test "persistence identity: Nemotron Metal's learned key extends its identity with the backend's policy" {
try expectCall(@embedFile("src/native/metal_identity.zig"), "pub fn learned(", "return.{.id=withPolicy(h.final(),b),");
}

test "persistence identity: Nemotron Metal's backend keeps TF_COOP_SPLIT as its forward pass resolves it" {
const source = @embedFile("src/families/nemotron/backend.zig");
try std.testing.expect(std.mem.indexOf(u8, source, "\nconst fwd = @import(\"forward.zig\");\n") != null);
try expectCall(source, "pub fn init(gpa: std.mem.Allocator, m: *Model,", ".coop_split=fwd.splitOn(),");
}
52 changes: 52 additions & 0 deletions zig/persistence_checkpoint_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! Indexed subfolders are admitted loader inputs that a top-level scan cannot stamp.
const std = @import("std");
const disk = @import("src/native/disk_identity.zig");
const nemo = @import("src/native/metal_identity.zig");
const fixture = @import("src/native/persistence_fixture.zig");
const t = std.testing;
const Family = enum { nemo, qwen, glm, flash };

fn key(a: std.mem.Allocator, dir: []const u8, family: Family) !u64 {
var h = std.hash.Wyhash.init(@backingInt(family));
if (family == .nemo) try nemo.shardStamps(&h, a, t.io, dir) else try disk.checkpoint(&h, a, t.io, dir);
return h.final();
}
fn nestedMiss(comptime family: Family) !void {
var tmp = t.tmpDir(.{});
defer tmp.cleanup();
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a);
try tmp.dir.createDirPath(t.io, "tensors");
try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" });
try tmp.dir.writeFile(t.io, .{ .sub_path = "model.safetensors.index.json", .data = "{\"weight_map\":{\"unprobed.weight\":\"tensors/native-QB.safetensors\"}}" });
const header = "{\"unprobed.weight\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}";
var shard: [8 + header.len + 4]u8 = @splat(0);
std.mem.writeInt(u64, shard[0..8], header.len, .little);
@memcpy(shard[8..][0..header.len], header);
try tmp.dir.writeFile(t.io, .{ .sub_path = "tensors/native-QB.safetensors", .data = &shard });
const before = try key(a, dir, family);
const same = try key(a, dir, family);
shard[shard.len - 1] = 1;
try fixture.rewrite(tmp.dir, "tensors/native-QB.safetensors", &shard);
try fixture.misses(before, same, &.{try key(a, dir, family)});
try tmp.dir.deleteFile(t.io, "tensors/native-QB.safetensors");
try t.expectError(error.IndexedShardMissing, key(a, dir, family));
}

test "persistence identity: Nemotron Metal indexed shard rewrite misses with the same probe" {
try nestedMiss(.nemo);
}
test "persistence identity: Qwen Metal indexed shard rewrite misses with the same probe" {
try nestedMiss(.qwen);
}
test "persistence identity: GLM Metal indexed shard rewrite misses with the same probe" {
try nestedMiss(.glm);
}
test "persistence identity: Flash Next Metal indexed shard rewrite misses with the same probe" {
try nestedMiss(.flash);
}
test {
_ = nemo; // its top-level shard rewrite test
}
12 changes: 10 additions & 2 deletions zig/persistence_identity_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const disk = @import("src/native/disk_identity.zig");
const glm = @import("src/families/glm/load_plan.zig");
const pack = @import("src/families/flashnext/pack_io.zig");
const Imprint = @import("engine_api").prompt_imprint.Imprint;
const fixture = @import("src/native/persistence_fixture.zig");
const binary = @import("sys").file_identity;
const t = std.testing;
const io = t.io;
Expand Down Expand Up @@ -50,9 +51,8 @@ fn changedWeightMiss(kind: Kind) !void {
try t.expect(state.best(&tokens, &.{}, false, 0) != null);
}
// An unvisited tensor can change without changing a fixed probe, config, index or shard header.
try std.Io.sleep(io, .fromMilliseconds(5), .awake);
shard[shard.len - 1] = 1;
try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &shard });
try fixture.rewrite(tmp.dir, "model.safetensors", &shard);
try t.expectEqual(old, try legacy(a, dir, kind));
const after = try disk.scoped(a, io, dir, old);
var fresh = try Imprint.open(a, root, after, 1 << 20);
Expand Down Expand Up @@ -149,3 +149,11 @@ test "persistence identity: tokenizer and template edits reuse only identical ca
try t.expect(kept.best(&.{ 5, 7, 13 }, &.{ 1, 2 }, true, 0) == null);
try t.expect(kept.best(&ids, &.{ 0, 2 }, true, 0) == null);
}

test {
_ = @import("persistence_policy_test.zig");
}

test {
_ = @import("persistence_checkpoint_test.zig");
}
Loading
Loading