Skip to content

Commit 5960fe2

Browse files
committed
Bind persisted serving states to code and checkpoint changes
1 parent 54336bc commit 5960fe2

21 files changed

Lines changed: 428 additions & 20 deletions

‎docs/recipes/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL.
2929
| Spark-X2.6-4B | [Native CUDA](spark-x2.6-4b-cuda.md), [native Metal, the bf16 release, contexts to 1M](spark-x2.6-4b-metal.md) |
3030
| Nanbeige4.3-33B | [Native Metal, the bf16 and INT4 releases, the Llama family](nanbeige-4.3-33b-metal.md) |
3131

32+
[Persisted serving-state identities](persisted-serving-keys.md) lists the disk owners, their compatibility keys and stale-state host checks.
33+
3234
## Capability floor
3335

3436
The native release includes CUDA kernels for sm_80, sm_86, sm_120 and sm_121. This is a build target list, not
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Persisted serving state identities
2+
3+
A resumed state belongs to the loaded model and arithmetic that produced it. The native disk stores bind the
4+
running serving binary with a streamed SHA256 fingerprint. This covers compiled host code, embedded shaders,
5+
compiler options and snapshot layouts. Rebuilding or changing the binary can cold-start the optional disk cache.
6+
Old files remain in their original namespace and follow the existing cache budget and eviction rules.
7+
8+
| Persistence owner | Source and arithmetic | Checkpoint | KV and draft state | Weight learning |
9+
| --- | --- | --- | --- | --- |
10+
| 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 |
11+
| 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 |
12+
| 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 |
13+
| 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 |
14+
| 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 |
15+
| 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 |
16+
| 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 |
17+
| 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 |
18+
19+
Other native family adapters have no attached cross-process serving-state tier. Their snapshots remain owned by one
20+
open model. This includes the other Metal families (Qwen4, Fish, Qwen MoE, LFM2, EXLR8 GLM, Gemma, Step, Spark,
21+
MiniMax and Llama), other CUDA families (Omni, GLM, MiniMax, Kolibri, Gemma, Spark, Dory, LFM2, Fish and Qwen4),
22+
and the HIP and XPU adapters. A family name or a RAM snapshot alone does not imply persistent disk reuse.
23+
24+
Tokenizer and chat-template bytes are covered through the canonical numeric token prefix that the store actually
25+
matches. Changed rendering or tokenization that changes an ID misses. An identical ID prefix has the same target
26+
state under identical weights and arithmetic, so it can remain reusable. Planned stores also compare their chunk
27+
boundaries, while the shared cache compares decoded spans and image identities. These stores do not persist
28+
rendered answer text. No separate hot-swappable LoRA state is admitted by these persistence adapters; checkpoint
29+
changes and supported external drafters use the identities above.
30+
31+
GLM and Flash Next now include safetensors shard names, sizes, inode and modification/change stamps. A weight
32+
write with unchanged config, index, tensor header and size moves their namespace even when a fixed probe does not
33+
visit the changed tensor. Flash Next also hashes the loaded variant text and input/output/meta bindings in sorted
34+
function-name order. Captured CUDA sets hash each cubin named by the parsed manifest, through the same loader
35+
paths and size limit. A missing or changed file fails identity construction instead of opening an old namespace.
36+
37+
The executable and kernel fingerprints use a 32 KiB read buffer and check file stamps across the read. Checkpoints,
38+
executables and kernel assets must remain stable while a model opens and serves. The existing learner owns runtime
39+
weight changes and clears the store before another reply; it does not attach an old disk tier after a lesson.
40+
41+
Host checks:
42+
43+
```sh
44+
zig build test-persistence-identity-host test-cuda-persistence-source-host compile-persistence-host -j1
45+
zig build test-checkpoint-identity test-cuda-disk-open-host test-sessions test-frame-cache-identity-host -j1
46+
```
47+
48+
The first command's Metal consumer compile and checkpoint fixtures require a macOS host but execute no GPU call.
49+
These checks cover stale namespaces, real same-header shard rewrites, binary and captured-cubin mutations, loaded
50+
variant bindings, allocation failures, canonical token matching and whole-file fingerprint coverage. Actual
51+
checkpoint/device qualification still requires exact drafted/plain, resumed/fresh and concurrent/solo token arrays.

‎zig/build/cuda_family_host.zig‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B
66
const metal_scope = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/config.zig"), .target = host }), .filters = &.{ "Metal 2B format scope:", "admit the affine 2B", "admit untied heads" } }));
77
b.step("test-qwen35-metal-scope-host", "Metal 2B format admission without device or Metal compiler").dependOn(&metal_scope.step);
88
@import("load_prefetch_host.zig").tests(b, mods.core, step);
9+
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"} }));
10+
b.step("test-cuda-persistence-source-host", "Captured CUDA source keys without loading a driver").dependOn(&captured.step);
11+
step.dependOn(&captured.step);
12+
913
@import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step);
1014
@import("cuda_groups_host.zig").host(b, cuda, mods, step);
1115
const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen stepped prefill:"} }));

‎zig/build/gemma4_host.zig‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,16 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M
4747
b.step("test-glm-disk-charge-host", "Actual GLM snapshot save/read byte accounting without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = &.{"GLM disk charge:"} })).step);
4848
const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} });
4949
@import("disk_identity_host.zig").metal(b, metal, engine, api);
50+
const identity_root = b.createModule(.{ .root_source_file = b.path("zig/persistence_identity_test.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "engine_api", .module = api } } });
51+
const identity_filter = b.option([]const u8, "persistence-identity-filter", "One persisted-state identity regression");
52+
const identity_run = b.addRunArtifact(b.addTest(.{ .root_module = identity_root, .filters = if (identity_filter) |f| &.{f} else &.{"persistence identity:"} }));
53+
identity_run.has_side_effects = true;
54+
if (b.top_level_steps.get("test")) |all| all.step.dependOn(&identity_run.step);
55+
b.step("test-persistence-identity-host", "Actual checkpoint producers and safe stale namespace misses without a GPU").dependOn(&identity_run.step);
56+
const persistence_root = b.createModule(.{ .root_source_file = b.path("zig/flashnext_persistence_compile.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } });
57+
const persistence_object = b.addObject(.{ .name = "persistence-host-compile", .root_module = persistence_root });
58+
_ = persistence_object.getEmittedBin();
59+
b.step("compile-persistence-host", "Compile actual GLM and both Flash Next disk-store startup paths without devices").dependOn(&persistence_object.step);
5060
const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/gemma4.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } });
5161
const root = b.createModule(.{ .root_source_file = b.path("zig/gemma4_host_compile.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "host", .module = host }, .{ .name = "tensorfold", .module = engine } } });
5262
const object = b.addObject(.{ .name = "gemma4-host-compile", .root_module = root });
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
//! Compile all Metal disk-store startup consumers without device discovery or shader compilation.
2+
export fn compiledPersistenceConsumers() usize {
3+
return @intFromPtr(&@import("src/native/glm_host.zig").open) ^
4+
@intFromPtr(&@import("src/native/flashnext_host.zig").open) ^
5+
@intFromPtr(&@import("src/native/flashnext_batch_host.zig").openConfigured);
6+
}

‎zig/persistence_identity_test.zig‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
//! Real checkpoint metadata and persisted namespace checks; no model, device or shader is opened.
2+
const std = @import("std");
3+
const disk = @import("src/native/disk_identity.zig");
4+
const glm = @import("src/families/glm/load_plan.zig");
5+
const pack = @import("src/families/flashnext/pack_io.zig");
6+
const Imprint = @import("engine_api").prompt_imprint.Imprint;
7+
const binary = @import("sys").file_identity;
8+
const t = std.testing;
9+
const io = t.io;
10+
const Kind = enum { glm, flashnext };
11+
const config = "{}";
12+
const index = "{\"weight_map\":{\"unprobed.weight\":\"model.safetensors\"}}";
13+
const header = "{\"unprobed.weight\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}";
14+
15+
fn legacy(a: std.mem.Allocator, dir: []const u8, kind: Kind) !u64 {
16+
if (kind == .glm) return glm.modelHash(a, dir, config);
17+
const text = try pack.sourceIdentity(a, io, dir);
18+
defer a.free(text);
19+
return std.hash.Wyhash.hash(0x6964, text);
20+
}
21+
22+
fn allocatingScope(a: std.mem.Allocator, dir: []const u8) !void {
23+
_ = try disk.scoped(a, io, dir, 7);
24+
}
25+
26+
fn changedWeightMiss(kind: Kind) !void {
27+
const a = t.allocator;
28+
var tmp = t.tmpDir(.{});
29+
defer tmp.cleanup();
30+
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
31+
defer a.free(dir);
32+
const root = try std.fs.path.join(a, &.{ dir, "states" });
33+
defer a.free(root);
34+
try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = config });
35+
try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index });
36+
var shard: [8 + header.len + 4]u8 = @splat(0);
37+
std.mem.writeInt(u64, shard[0..8], header.len, .little);
38+
@memcpy(shard[8..][0..header.len], header);
39+
try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &shard });
40+
const old = try legacy(a, dir, kind);
41+
if (kind == .glm) try t.checkAllAllocationFailures(a, allocatingScope, .{dir});
42+
const before = try disk.scoped(a, io, dir, old);
43+
try t.expectEqual(before, try disk.scoped(a, io, dir, old));
44+
const tokens = [_]u32{ 7, 11, 13 };
45+
const key = Imprint.keyOf(&tokens);
46+
{
47+
var state = try Imprint.open(a, root, before, 1 << 20);
48+
defer state.deinit();
49+
try state.add(key, 2, &tokens, &.{}, 4);
50+
try t.expect(state.best(&tokens, &.{}, false, 0) != null);
51+
}
52+
// An unvisited tensor can change without changing a fixed probe, config, index or shard header.
53+
try std.Io.sleep(io, .fromMilliseconds(5), .awake);
54+
shard[shard.len - 1] = 1;
55+
try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &shard });
56+
try t.expectEqual(old, try legacy(a, dir, kind));
57+
const after = try disk.scoped(a, io, dir, old);
58+
var fresh = try Imprint.open(a, root, after, 1 << 20);
59+
defer fresh.deinit();
60+
try t.expectEqual(@as(usize, 0), fresh.metas.items.len);
61+
try t.expect(fresh.best(&tokens, &.{}, false, 0) == null);
62+
var preserved = try Imprint.open(a, root, before, 1 << 20);
63+
defer preserved.deinit();
64+
try t.expect(preserved.best(&tokens, &.{}, false, 0) != null);
65+
}
66+
67+
test "persistence identity: GLM same-header weight rewrite misses the old serving namespace" {
68+
try changedWeightMiss(.glm);
69+
}
70+
71+
test "persistence identity: Flash Next same-header weight rewrite misses the old serving namespace" {
72+
try changedWeightMiss(.flashnext);
73+
}
74+
75+
test {
76+
_ = @import("src/native/variant_identity.zig");
77+
}
78+
79+
test "persistence identity: changed serving binary bytes move an otherwise identical namespace" {
80+
const a = std.testing.allocator;
81+
var tmp = std.testing.tmpDir(.{});
82+
defer tmp.cleanup();
83+
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
84+
defer a.free(dir);
85+
const path = try std.fs.path.join(a, &.{ dir, "server" });
86+
defer a.free(path);
87+
try tmp.dir.writeFile(io, .{ .sub_path = "server", .data = "compiled code one" });
88+
const first = try binary.hash(io, path, 1024);
89+
try std.testing.expectEqual(first, try binary.hash(io, path, 1024));
90+
try std.testing.expectError(error.IdentityFileTooLarge, binary.hash(io, path, 1));
91+
var before = std.hash.Wyhash.init(17);
92+
binary.bind(&before, first);
93+
const root = try std.fs.path.join(a, &.{ dir, "kept" });
94+
defer a.free(root);
95+
const ids = [_]u32{ 5, 7, 11 };
96+
var kept = try Imprint.open(a, root, before.final(), 1 << 20);
97+
defer kept.deinit();
98+
try kept.add(Imprint.keyOf(&ids), 2, &ids, &.{}, 4);
99+
try tmp.dir.writeFile(io, .{ .sub_path = "server", .data = "compiled code two" });
100+
var after = std.hash.Wyhash.init(17);
101+
binary.bind(&after, try binary.hash(io, path, 1024));
102+
try std.testing.expect(before.final() != after.final());
103+
var next = try Imprint.open(a, root, after.final(), 1 << 20);
104+
defer next.deinit();
105+
try t.expect(next.best(&ids, &.{}, false, 0) == null);
106+
try t.expect(kept.best(&ids, &.{}, false, 0) != null);
107+
}
108+
109+
test "persistence identity: file fingerprints cover every block and agree with the whole-file SHA256" {
110+
const a = t.allocator;
111+
var tmp = t.tmpDir(.{});
112+
defer tmp.cleanup();
113+
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
114+
defer a.free(dir);
115+
const path = try std.fs.path.join(a, &.{ dir, "code" });
116+
defer a.free(path);
117+
const data = try a.alloc(u8, 2 * 32768 + 17);
118+
defer a.free(data);
119+
for (data, 0..) |*value, i| value.* = @truncate(i *% 131);
120+
try tmp.dir.writeFile(io, .{ .sub_path = "code", .data = data });
121+
var expected: [32]u8 = undefined;
122+
std.crypto.hash.sha2.Sha256.hash(data, &expected, .{});
123+
try t.expectEqual(expected, try binary.hash(io, path, data.len));
124+
data[32768 + 100] ^= 1;
125+
try tmp.dir.writeFile(io, .{ .sub_path = "code", .data = data });
126+
try t.expect(!std.mem.eql(u8, &expected, &(try binary.hash(io, path, data.len))));
127+
}
128+
129+
test "persistence identity: tokenizer and template edits reuse only identical canonical token prefixes" {
130+
const a = t.allocator;
131+
var tmp = t.tmpDir(.{});
132+
defer tmp.cleanup();
133+
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
134+
defer a.free(dir);
135+
try tmp.dir.writeFile(io, .{ .sub_path = "tokenizer.json", .data = "first tokenizer" });
136+
try tmp.dir.writeFile(io, .{ .sub_path = "chat_template.jinja", .data = "first template" });
137+
const identity = try disk.scoped(a, io, dir, 1);
138+
const root = try std.fs.path.join(a, &.{ dir, "states" });
139+
defer a.free(root);
140+
var kept = try Imprint.open(a, root, identity, 1 << 20);
141+
defer kept.deinit();
142+
const ids = [_]u32{ 5, 7, 11 };
143+
try kept.add(Imprint.keyOf(&ids), 2, &ids, &.{1}, 4);
144+
try tmp.dir.writeFile(io, .{ .sub_path = "tokenizer.json", .data = "other tokenizer" });
145+
try tmp.dir.writeFile(io, .{ .sub_path = "chat_template.jinja", .data = "other template" });
146+
try t.expectEqual(identity, try disk.scoped(a, io, dir, 1));
147+
try t.expect(kept.best(&ids, &.{ 1, 2 }, true, 0) != null);
148+
try t.expect(kept.best(&.{ 5, 9, 11 }, &.{ 1, 2 }, true, 0) == null);
149+
try t.expect(kept.best(&.{ 5, 7, 13 }, &.{ 1, 2 }, true, 0) == null);
150+
try t.expect(kept.best(&ids, &.{ 0, 2 }, true, 0) == null);
151+
}

‎zig/src/cuda/aot.zig‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! A captured set of Triton cubins (aot.json + cubins/): each launch picks the variant Triton itself would have picked.
22

33
const std = @import("std");
4+
pub const identity = @import("aot_identity.zig");
45
const abi = @import("abi.zig");
56
const Driver = @import("driver.zig").Driver;
67
const Stream = @import("stream.zig").Stream;

‎zig/src/cuda/aot_identity.zig‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//! Captured CUDA serving identity covers the manifest and the cubins the loader reads.
2+
const std = @import("std");
3+
const aot = @import("aot.zig");
4+
5+
pub fn hash(a: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 {
6+
const path = try std.fs.path.join(a, &.{ dir, "aot.json" });
7+
defer a.free(path);
8+
const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 24));
9+
defer a.free(text);
10+
const parsed = try aot.parseSpecs(a, text);
11+
defer parsed.deinit();
12+
var h = std.hash.Wyhash.init(0x616f74);
13+
h.update(text);
14+
for (parsed.value.kernels) |k| {
15+
const cubin = try std.fmt.allocPrint(a, "{s}/cubins/{s}.cubin", .{ dir, k.hash });
16+
defer a.free(cubin);
17+
const digest = try @import("sys").file_identity.hash(io, cubin, 1 << 26);
18+
h.update(&digest);
19+
}
20+
return h.final();
21+
}
22+
23+
test "persistence identity: captured CUDA cubin replacement moves an unchanged manifest key" {
24+
const a = std.testing.allocator;
25+
const io = std.testing.io;
26+
var tmp = std.testing.tmpDir(.{});
27+
defer tmp.cleanup();
28+
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
29+
defer a.free(dir);
30+
const manifest = "{\"kernels\":[{\"fn\":\"f\",\"hash\":\"h\",\"name\":\"k\",\"num_warps\":4,\"params\":[],\"consts\":{}}]}";
31+
try tmp.dir.writeFile(io, .{ .sub_path = "aot.json", .data = manifest });
32+
try tmp.dir.createDir(io, "cubins", .default_dir);
33+
try tmp.dir.writeFile(io, .{ .sub_path = "cubins/h.cubin", .data = "first cubin" });
34+
const before = try hash(a, io, dir);
35+
try std.testing.expectEqual(before, try hash(a, io, dir));
36+
try tmp.dir.writeFile(io, .{ .sub_path = "cubins/h.cubin", .data = "other cubin" });
37+
try std.testing.expect(before != try hash(a, io, dir));
38+
try tmp.dir.deleteFile(io, "cubins/h.cubin");
39+
try std.testing.expectError(error.FileNotFound, hash(a, io, dir));
40+
}

0 commit comments

Comments
 (0)