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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
- Flash Next on RDNA 3.5 iGPUs (gfx1150 to gfx1153) fills prompts in 4,096-row chunks by default on one GPU, falling back to 1,024 when the larger chunk would admit fewer streams. Tokens are unchanged (#1651, fixes #1649). Thanks to @gilby.

- CUDA's Qwen DFlash2 drafters must declare sliding attention on every layer (`use_sliding_window` and one `sliding_attention` per layer), which the kernels run, so a drafter declaring a full-attention layer is refused before loading instead of running through the sliding ring (#1946, part of #1863). Thanks to @garvrao80.
- Flash Next on HIP gathers n-gram drafts in parallel and releases the checkpoint's weight pages after uploading them, so the page cache falls from 31.5 to 2.8 GiB and the first cold prompt runs in 28.55 s instead of 48.44 s on a gfx1151 (#1611). Thanks to @gilby.

- `serve --profile stable` names today's defaults explicitly, and startup reports the profile and any registered switch set away from it; seven CUDA KV switches (`TF_QWEN_KV_PAGES`, `TF_QWEN_KV_SHARE`, `TF_GLM_KV_SHARE`, `TF_KV_SHARE`, `TF_FLASHNEXT_KV_PAGES` and two `_ALL` checks) are read through one registry, with environment values winning byte for byte; `fast-exact` and `fast` are refused until qualified (#1944, part of #1660). Thanks to @garvrao80.

Expand Down
4 changes: 2 additions & 2 deletions zig/cuda_checkpoint_cache_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn scope(comptime path: []const u8, function: []const u8, variable: []const u8)
var block: [2]Ast.Node.Index = undefined;
const cleanup = tree.blockStatements(&block, call).?;
try t.expectEqual(@as(usize, 2), cleanup.len);
try t.expectEqualStrings("file.release()", tree.getNodeSource(cleanup[0]));
try t.expectEqualStrings("file.release(gpa)", tree.getNodeSource(cleanup[0]));
try t.expectEqualStrings("file.close(io)", tree.getNodeSource(cleanup[1]));
continue;
}
Expand Down Expand Up @@ -112,7 +112,7 @@ test "CUDA load cache: Flash Next sweep follows MTP and retains live PLE files"
const drop = std.mem.indexOf(u8, s, ".dropPageCache(io, dir, e.ngram.files.items)") orelse return error.NoPleExclusion;
try t.expect(std.mem.indexOf(u8, s, "mtp.Head.init").? < drop);
const owner = @embedFile("src/families/flashnext/cuda_prompt_wt.zig");
try t.expect(std.mem.indexOf(u8, owner, "if (!runtimePages(self.f.names.keys())) self.f.release()") != null);
try t.expect(std.mem.indexOf(u8, owner, "if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator)") != null);
}

test "CUDA load cache: LFM2 decision model releases its direct-read fallback" {
Expand Down
29 changes: 28 additions & 1 deletion zig/src/core/checkpoint.zig
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,12 @@ pub const Checkpoint = struct {

/// Every file's pages out of the page cache (safetensors.File.release).
pub fn release(self: *const Checkpoint) void {
for (self.files.items) |*f| f.release();
for (self.files.items) |*f| f.release(self.gpa);
}

/// `release`, leaving `keep`'s bytes (parts of these files read later) in the pages they live in.
pub fn releaseExcept(self: *const Checkpoint, keep: []const []const u8) void {
for (self.files.items) |*f| f.releaseExcept(keep, self.gpa);
}

/// Every tensor named `short`... read into the page cache by `readers` threads of their own until `join`.
Expand Down Expand Up @@ -321,6 +326,28 @@ test "after release the mapping stays readable: a later read faults the same byt
try std.testing.expectEqualSlices(u8, image[image.len - 4096 ..], t.bytes);
}

test "releaseExcept keeps the kept tensor's bytes where they are, and a read of them is unchanged" {
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const image = try testImage(gpa, "x", 1 << 20);
defer gpa.free(image);
for (image[image.len - (1 << 20) ..], 0..) |*b, i| b.* = @truncate(i * 13 + 3);
try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = image });
var path: [64]u8 = undefined;
var ck = try Checkpoint.openModel(gpa, io, try std.fmt.bufPrint(&path, ".zig-cache/tmp/{s}", .{tmp.sub_path}));
defer ck.close();
const t = try ck.get("x");
// a middle span, so bytes are dropped on both sides of it and the mapping stays readable either way
const keep = t.bytes[4096 .. 4096 + 8192];
const copy = try gpa.dupe(u8, keep);
defer gpa.free(copy);
ck.releaseExcept(&.{keep});
try std.testing.expectEqualSlices(u8, copy, keep);
try std.testing.expectEqualSlices(u8, image[image.len - (1 << 20) ..], t.bytes);
}

test "release keeps a map that fell back to reads (no mmap): its heap copy is the only one" {
const gpa = std.testing.allocator;
var threaded: std.Io.Threaded = .init(gpa, .{ .disable_memory_mapping = true });
Expand Down
64 changes: 60 additions & 4 deletions zig/src/core/safetensors.zig
Original file line number Diff line number Diff line change
Expand Up @@ -256,12 +256,20 @@ pub const File = struct {
}

/// The file's pages out of the mapping and the page cache (unified memory needs the room); Linux only, refaults.
pub fn release(self: *const File) void {
pub fn release(self: *const File, scratch: std.mem.Allocator) void {
self.releaseExcept(&.{}, scratch);
}

/// `release`, with `keep`'s bytes (parts of this mapping read later) left in the pages they live in.
pub fn releaseExcept(self: *const File, keep: []const []const u8, scratch: std.mem.Allocator) void {
if (@import("builtin").os.tag != .linux) return;
const linux = std.os.linux;
// a map that fell back to a heap copy (no mmap) holds the only bytes: DONTNEED would zero them
if (self.map.section != null) _ = linux.madvise(self.map.memory.ptr, self.map.memory.len, linux.MADV.DONTNEED);
_ = linux.fadvise(self.file.handle, 0, 0, linux.POSIX_FADV.DONTNEED);
const mem = self.map.memory;
if (self.map.section == null) {
_ = std.os.linux.fadvise(self.file.handle, 0, 0, std.os.linux.POSIX_FADV.DONTNEED);
return;
}
dropExcept(mem.ptr, mem.len, self.file.handle, keep, scratch);
}

pub fn get(self: *const File, name: []const u8) ?Tensor {
Expand All @@ -270,6 +278,54 @@ pub const File = struct {
}
};

/// A mapped file's pages out of memory and its page cache, except the pages holding `keep`'s bytes.
fn dropExcept(
map: [*]u8,
map_len: usize,
fd: std.posix.fd_t,
keep: []const []const u8,
scratch: std.mem.Allocator,
) void {
const linux = std.os.linux;
const base = @intFromPtr(map);
const page = std.heap.pageSize();
var spans: [8][2]usize = undefined;
const kept = if (keep.len <= spans.len) spans[0..keep.len] else scratch.alloc([2]usize, keep.len) catch {
_ = linux.madvise(map, map_len, linux.MADV.DONTNEED);
_ = linux.fadvise(fd, 0, 0, linux.POSIX_FADV.DONTNEED);
return;
};
defer if (kept.len > spans.len) scratch.free(kept);
var n: usize = 0;
for (keep) |k| {
if (k.len == 0) continue;
const lo = @intFromPtr(k.ptr);
if (lo < base or lo + k.len > base + map_len) continue;
kept[n] = .{
std.mem.alignBackward(usize, lo - base, page),
@min(map_len, std.mem.alignForward(usize, lo - base + k.len, page)),
};
n += 1;
}
std.mem.sort([2]usize, kept[0..n], {}, struct {
fn less(_: void, x: [2]usize, y: [2]usize) bool {
return x[0] < y[0];
}
}.less);
var at: usize = 0;
for (kept[0..n]) |sp| {
if (sp[0] > at) gap(map, fd, at, sp[0] - at);
at = @max(at, sp[1]);
}
if (at < map_len) gap(map, fd, at, map_len - at);
}

/// One run of a mapped shard's bytes out of memory and the page cache: a later read faults them back in.
fn gap(map: [*]u8, fd: std.posix.fd_t, at: usize, len: usize) void {
_ = std.os.linux.madvise(map + at, len, std.os.linux.MADV.DONTNEED);
_ = std.os.linux.fadvise(fd, @intCast(at), @intCast(len), std.os.linux.POSIX_FADV.DONTNEED);
}

test "header entries" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/flashnext/cuda_prompt_wt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const Shard = struct {

fn close(self: *Shard) void {
// A shard may mix loaded tensors with the n-gram table still read at runtime.
if (!runtimePages(self.f.names.keys())) self.f.release();
if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator); // no keep list: scratch unused
self.f.close(self.io);
}

Expand Down Expand Up @@ -190,7 +190,7 @@ pub const Store = struct {
pub fn release(self: *Store) void {
for (self.held.items) |h| {
// the borrowers' pages leave this process (their bytes are copied), except the n-gram table's (Shard.close)
if (!runtimePages(h.file.f.names.keys())) h.file.f.release();
if (!runtimePages(h.file.f.names.keys())) h.file.f.release(self.gpa);
self.released.append(self.gpa, h) catch {
var kept = h.file;
kept.close();
Expand Down
3 changes: 3 additions & 0 deletions zig/src/families/flashnext/hip/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ pub const Engine = struct {
errdefer e.host.staging.free();
e.eos = e.tables.hasher.ref.eos;
e.narrowed = null;
// every weight is on the device now: only the n-gram rows a gather reads stay resident
const live = try e.tables.spans(e.keep.allocator());
e.ck.releaseExcept(live);
e.arena = try hip.Arena.init(&e.driver, try e.fittedScratch());
errdefer e.arena.deinit();
e.drawer = try serve.draw.Drawer.init(
Expand Down
8 changes: 4 additions & 4 deletions zig/src/families/flashnext/hip/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ pub const Inputs = struct {
pub fn stage(m: *const model.Model, host: *Host, segs: []const Seg, window: bool) !Staged {
const d = m.dims;
const t = host.tables;
if (d.ple_dim / t.dims != ngram.heads) return error.UnsupportedNgramHeads;
if (d.ple_dim / t.rows.dims != ngram.heads) return error.UnsupportedNgramHeads;
var rows: usize = 0;
for (segs) |g| rows += g.tokens.len;
const n16 = rows * ngram.heads;
Expand Down Expand Up @@ -268,9 +268,9 @@ fn ple(
@backingInt(Kind.bf16),
@ptrFromInt(in.local),
@intCast(rows * ngram.heads),
t.bits,
@intCast(t.group),
@intCast(t.dims),
t.rows.bits,
@intCast(t.rows.group),
@intCast(t.rows.dims),
@ptrFromInt(emb.ptr),
@backingInt(m.act),
o.stream,
Expand Down
Loading
Loading