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

- Flash Next on HIP advises random access over the n-gram table's mapped tensors, so a gather's scattered single-row reads fault only their own pages instead of whole readahead windows: the first request after start decodes at 35.8 tok/s instead of 24.4, and a cold 7K-token prompt starts in 28.9 s instead of 48.4 s on a Strix Halo (gfx1151), with every reply token-equal (#1615, fixes #1602, thanks @gilby).

- `TF_KV_SHARE=n` keeps a paged CUDA family's prompts as its core pool's pages (Gemma 4, Kolibri-1), with replies equal to a fresh prefill; it's opt-in, and costs about 3.5% decode after a short cold prompt on Kolibri-1 (#1755, part of #1657). Thanks to @jschmied.

- Docs: the GLM CUDA recipe gives `TF_GLM_OVERLAP_PIECES=8` beside `TF_GLM_CHUNK_SOLO` at TP=3 with `TF_GLM_ROCE_MULTI` (#2067). Thanks to @Bizuayeu.
Expand Down
66 changes: 66 additions & 0 deletions zig/src/core/checkpoint.zig
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,17 @@ pub const Checkpoint = struct {
return prefetching.start(self, self.scoped(&buf, short) catch return .{}, readers);
}

/// `short`'s bytes marked read in no order (safetensors.File.adviseRandom): a table's rows, not its file.
pub fn adviseRandom(self: *Checkpoint, short: []const u8) !void {
var buf: [320]u8 = undefined;
const name = try self.scoped(&buf, short);
for (self.files.items) |*f| if (f.get(name)) |t| {
f.adviseRandom(t.bytes);
return;
};
return error.MissingTensor;
}

/// Names no `get` took (the loader refuses a checkpoint with leftovers).
pub fn unused(self: *const Checkpoint) usize {
var n: usize = 0;
Expand Down Expand Up @@ -309,6 +320,61 @@ test "has finds a name without taking it; skip marks a prefix used" {
try std.testing.expectEqual(@as(usize, 0), ck.unused());
}

/// Whether the smaps block holding `at` is marked read in no order (`rr`, MADV_RANDOM); null with no such block.
fn randomAdviceAt(gpa: std.mem.Allocator, io: Io, at: usize) !?bool {
// procfs reports size 0: read the stream, not the length
var file = try Io.Dir.cwd().openFile(io, "/proc/self/smaps", .{});
defer file.close(io);
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
var buf: [64 << 10]u8 = undefined;
while (true) {
const got = file.readStreaming(io, &.{&buf}) catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
if (got == 0) break;
try text.appendSlice(gpa, buf[0..got]);
}
var lines = std.mem.splitScalar(u8, text.items, '\n');
var inside = false;
while (lines.next()) |line| {
if (std.mem.indexOfScalar(u8, line, '-')) |dash| {
const sp = std.mem.indexOfScalarPos(u8, line, dash, ' ') orelse continue;
const lo = std.fmt.parseInt(usize, line[0..dash], 16) catch continue;
const hi = std.fmt.parseInt(usize, line[dash + 1 .. sp], 16) catch continue;
inside = at >= lo and at < hi;
} else if (inside and std.mem.startsWith(u8, line, "VmFlags:")) {
var flags = std.mem.tokenizeAny(u8, line["VmFlags:".len..], " ");
while (flags.next()) |flag| if (std.mem.eql(u8, flag, "rr")) return true;
return false;
}
}
return null;
}

test "adviseRandom marks the mapping's pages as read in no order, and leaves the bytes alone" {
if (@import("builtin").os.tag != .linux) return error.SkipZigTest;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const image = try testImage(gpa, "x", 64 << 10);
defer gpa.free(image);
for (image[image.len - (64 << 10) ..], 0..) |*b, i| b.* = @truncate(i * 7 + 1);
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");
const at = @intFromPtr(t.bytes.ptr);
// a fresh mapping: the kernel has not been told how it will be read
try std.testing.expectEqual(@as(?bool, false), try randomAdviceAt(gpa, io, at));
try ck.adviseRandom("x");
try std.testing.expectEqual(@as(?bool, true), try randomAdviceAt(gpa, io, at));
try std.testing.expectEqualSlices(u8, image[image.len - (64 << 10) ..], t.bytes);
}

test "after release the mapping stays readable: a later read faults the same bytes back in" {
const io = std.testing.io;
const gpa = std.testing.allocator;
Expand Down
11 changes: 11 additions & 0 deletions zig/src/core/safetensors.zig
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,17 @@ pub const File = struct {
dropExcept(mem.ptr, mem.len, self.file, keep, scratch);
}

/// `bytes` (part of this file's mapping) marked read in no order, e.g. a table's rows; Linux only.
pub fn adviseRandom(self: *const File, bytes: []const u8) void {
if (@import("builtin").os.tag != .linux or bytes.len == 0) return;
// a map that fell back to a heap copy has no file pages to advise
if (self.map.section == null) return;
const page = std.heap.pageSize();
const lo = std.mem.alignBackward(usize, @intFromPtr(bytes.ptr), page);
const hi = std.mem.alignForward(usize, @intFromPtr(bytes.ptr) + bytes.len, page);
_ = std.os.linux.madvise(@ptrFromInt(lo), hi - lo, std.os.linux.MADV.RANDOM);
}

pub fn get(self: *const File, name: []const u8) ?Tensor {
const e = self.names.get(name) orelse return null;
return .{ .dtype = e.dtype, .rank = e.rank, .shape = e.shape, .bytes = self.map.memory[self.data + e.begin .. self.data + e.end] };
Expand Down
3 changes: 3 additions & 0 deletions zig/src/families/flashnext/hip/tables.zig
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ pub const Tables = struct {
if (spec == null)
spec = (try c.declared(stem, core.quant.keys.canonical)) orelse return error.UnsupportedQuantization;
if (w.shape[0] != n or sc.dtype != .bf16 or bi.dtype != .bf16) return error.UnexpectedNgramTable;
// a gather reads these rows in no order: readahead per row would fetch a window for it
for ([_][]const u8{ "weight", "scales", "biases" }) |part|
try ck.adviseRandom(try std.fmt.allocPrint(a, "{s}.{s}", .{ stem, part }));
s.* = .{ .words = w.bytes, .scales = sc.bytes, .biases = bi.bytes };
}
const dims = c.ple_dim / heads;
Expand Down
Loading