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 CUDA loads its experts about 12% faster with the direct load: the next chunk is read while the current one packs, and the store switches shards without reopening them. Replies are unchanged (#1960). Thanks to @jschmied.

- Gemma 4 on CUDA keeps its global layers' caches in pages of the core KV pool, every stream on pages, so with `TF_KV_SHARE` its prompts can be kept and resumed as pool pages; unset, tokens and speed are unchanged (#1619, part of #1657). Thanks to @jschmied.

- TensorFold Starlight moves to its own repository, [ashhart/tf-starlight](https://github.com/ashhart/tf-starlight), with its history: it pins the TensorFold release it is tested with and checks the engine contract against that release in CI (#1972, fixes #1970).
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/flashnext/cuda_fp8_experts_load_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const fp8 = @import("cuda_fp8_experts_load.zig");
const experts = @import("cuda_modelopt_experts.zig");
const wt = @import("cuda_prompt_wt.zig");
const lanes_bytes = @import("cuda_lanes_bytes.zig");
const Fake = @import("cuda_modelopt_threads_test.zig").Fake;
const Fake = @import("cuda_modelopt_threads_fixture.zig").Fake;
const env = @import("sys").env;
const fx = cuda.experts.Fp8Experts;
const ta = std.testing.allocator;
Expand Down
87 changes: 74 additions & 13 deletions zig/src/families/flashnext/cuda_modelopt_threads.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,59 @@ pub const View = struct { codes: []const u8, scales: []const u8 = &.{}, fixed: [
/// Readers a direct load gathers each chunk's planes with (the NVMe's O_DIRECT rate holds from 4 streams).
const direct_readers = 4;

const Source = core.direct_gather.Source;
const GatherError = @typeInfo(@typeInfo(@TypeOf(core.direct_gather.Gather.read)).@"fn".return_type.?).error_union.error_set;

/// A store's hook at chunk k's gather start (`gather`) or pack end (a test's; the weight store has none).
fn mark(store: anytype, gather: bool, k: usize) void {
if (comptime @hasDecl(std.meta.Child(@TypeOf(store)), "chunkMark")) store.chunkMark(gather, k);
}

/// The chunk's plane views as the gather repoints them: codes, scales, fixed and exceptions of each.
fn planes(part: []View, ptrs: []*[]const u8) []*[]const u8 {
for (part, 0..) |*v, j| {
ptrs[4 * j] = &v.codes;
ptrs[4 * j + 1] = &v.scales;
ptrs[4 * j + 2] = &v.fixed;
ptrs[4 * j + 3] = &v.exceptions;
}
return ptrs[0 .. 4 * part.len];
}

/// One chunk's gather on its own thread (inline if none starts) while the chunk before it packs.
fn Next(comptime S: type) type {
return struct {
store: S,
g: *core.direct_gather.Gather,
sources: []const Source,
ptrs: []const *[]const u8,
k: usize,
thread: ?std.Thread = null,
failed: ?GatherError = null,

fn run(self: *@This()) void {
mark(self.store, true, self.k);
self.g.read(self.sources, self.ptrs) catch |err| {
self.failed = err;
};
}

fn start(self: *@This()) void {
self.thread = std.Thread.spawn(.{}, run, .{self}) catch blk: {
self.run();
break :blk null;
};
}

/// Joined (idempotent), then its error if the gather failed.
fn wait(self: *@This()) GatherError!void {
if (self.thread) |t| t.join();
self.thread = null;
if (self.failed) |err| return err;
}
};
}

/// The store as slice.stored reads it, every tensor's pages read ahead (this loader copies all of each).
fn Ahead(comptime S: type) type {
return struct {
Expand Down Expand Up @@ -179,8 +232,9 @@ pub fn loadMode(a: std.mem.Allocator, d: *const cuda.Driver, store: anytype, pre
views[3 * i + 1] = try viewOf(store, try std.fmt.bufPrint(&buf, "{s}.experts.{d}.up_proj", .{ prefix, i }), width, dims, direct);
views[3 * i + 2] = try viewOf(store, try std.fmt.bufPrint(&buf, "{s}.experts.{d}.down_proj", .{ prefix, i }), dims, width, direct);
}
var gather = core.direct_gather.Gather.init(a, direct_readers);
defer gather.deinit();
// two arenas: chunk k packs from one while chunk k + 1 is gathered into the other
var gathers = [2]core.direct_gather.Gather{ .init(a, direct_readers), .init(a, direct_readers) };
defer for (&gathers) |*g| g.deinit();
var held: [core.direct_gather.max_sources]core.direct_gather.Source = undefined;
// a layer whose shards don't fit one gather reads through the mapping, as a file system without O_DIRECT does
const sources: ?[]core.direct_gather.Source = if (direct) store.sources(&held) catch |err| switch (err) {
Expand All @@ -191,7 +245,7 @@ pub fn loadMode(a: std.mem.Allocator, d: *const cuda.Driver, store: anytype, pre
if (direct) {
// every global first (a 4-byte read each, joined where they sit together), checked as viewOf checks them
for (views, 0..) |*v, j| ptrs[j] = &v.global_bytes;
if (sources) |s| try gather.read(s, ptrs[0..view_count]);
if (sources) |src| try gathers[0].read(src, ptrs[0..view_count]);
for (views) |*v| try globalOf(v);
}
var up = try cuda.DeviceBuffer.alloc(d, up_total);
Expand All @@ -201,25 +255,32 @@ pub fn loadMode(a: std.mem.Allocator, d: *const cuda.Driver, store: anytype, pre
// the store's pinned staging, kept across a load's layers and freed by its dropStaging or deinit on any path
const chunk = @max(1, @min(count, stage_cap / (up_bytes + down_bytes)));
const stage = try store.pinned(d, chunk * (up_bytes + down_bytes));
if (sources) |src| {
mark(store, true, 0);
try gathers[0].read(src, planes(views[0 .. 3 * @min(chunk, count)], ptrs));
}
var lo: usize = 0;
while (lo < count) : (lo += chunk) {
var k: usize = 0;
while (lo < count) : ({
lo += chunk;
k += 1;
}) {
const m = @min(chunk, count - lo);
if (sources) |s| {
const part = views[3 * lo ..][0 .. 3 * m];
for (part, 0..) |*v, j| {
ptrs[4 * j] = &v.codes;
ptrs[4 * j + 1] = &v.scales;
ptrs[4 * j + 2] = &v.fixed;
ptrs[4 * j + 3] = &v.exceptions;
}
try gather.read(s, ptrs[0 .. 4 * part.len]);
// the next chunk's gather runs while this one packs; the main thread allocates nothing from `a` meanwhile
var next: Next(@TypeOf(store)) = .{ .store = store, .g = &gathers[(k + 1) % 2], .sources = sources orelse &.{}, .ptrs = &.{}, .k = k + 1 };
defer next.wait() catch {};
if (sources != null and lo + chunk < count) {
next.ptrs = planes(views[3 * (lo + chunk) ..][0 .. 3 * @min(chunk, count - lo - chunk)], ptrs);
next.start();
}
const up_words = std.mem.bytesAsSlice(u32, stage[0 .. m * up_bytes]);
const down_words: []u32 = @alignCast(std.mem.bytesAsSlice(u32, stage[m * up_bytes ..][0 .. m * down_bytes]));
try pack(views[3 * lo ..][0 .. 3 * m], up_words, down_words, width, dims, n);
mark(store, false, k);
// synchronous from pinned memory, as cuda_pocket.zig's staged: done before return, so the next chunk may refill
try d.check(d.api.cuMemcpyHtoD_v2(try up.at(lo * up_bytes), stage.ptr, m * up_bytes), "cuMemcpyHtoD pinned experts");
try d.check(d.api.cuMemcpyHtoD_v2(try down.at(lo * down_bytes), stage.ptr + m * up_bytes, m * down_bytes), "cuMemcpyHtoD pinned experts");
try next.wait();
// the next chunk's gather reuses these views' memory: only their globals are read after this
for (views[3 * lo ..][0 .. 3 * m]) |*v| v.* = .{ .codes = &.{}, .global = v.global };
}
Expand Down
238 changes: 238 additions & 0 deletions zig/src/families/flashnext/cuda_modelopt_threads_fixture.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
//! The Flash Next expert loader tests' fake driver, checkpoint fixture and the one-expert loop's words.
const std = @import("std");
const cuda = @import("cuda");
const ex = cuda.experts.Nvfp4Experts;

pub const abi = cuda.abi;
pub const wt = @import("cuda_prompt_wt.zig");
pub const experts = @import("cuda_modelopt_experts.zig");
pub const io = std.testing.io;
pub const ta = std.testing.allocator;
pub const env = @import("sys").env;

/// A driver whose device memory is host memory, counting calls and live allocations; cuda.memory's limit refuses.
pub const Fake = struct {
pub const Kind = enum { pinned, device, copy };
pub var calls: [3]usize = @splat(0);
pub var live_pinned: usize = 0;
pub var live_device: usize = 0;
var spans: [256][]u8 = undefined;
var nspans: usize = 0;

pub fn reset() void {
calls = @splat(0);
}
fn tally(k: Kind) void {
calls[@backingInt(k)] += 1;
}
fn take(n: usize) ?[]u8 {
if (nspans == spans.len) @panic("the fake driver holds 256 allocations at most");
const m = std.heap.page_allocator.alloc(u8, @max(n, 1)) catch return null;
spans[nspans] = m;
nspans += 1;
return m;
}
fn give(p: usize) void {
for (spans[0..nspans], 0..) |m, i| if (@intFromPtr(m.ptr) == p) {
std.heap.page_allocator.free(m);
nspans -= 1;
spans[i] = spans[nspans];
return;
};
@panic("freed memory the fake never gave");
}
fn hostAlloc(p: *?*anyopaque, n: usize, _: c_uint) callconv(.c) abi.Result {
tally(.pinned);
const m = take(n) orelse return 2;
p.* = m.ptr;
live_pinned += 1;
return abi.success;
}
fn hostFree(p: ?*anyopaque) callconv(.c) abi.Result {
give(@intFromPtr(p));
live_pinned -= 1;
return abi.success;
}
fn devAlloc(p: *abi.DevicePtr, n: usize) callconv(.c) abi.Result {
tally(.device);
const m = take(n) orelse return 2;
p.* = @intFromPtr(m.ptr);
live_device += 1;
return abi.success;
}
pub fn devFree(p: abi.DevicePtr) callconv(.c) abi.Result {
give(p);
live_device -= 1;
return abi.success;
}
fn copy(dst: abi.DevicePtr, src: ?*const anyopaque, n: usize) callconv(.c) abi.Result {
tally(.copy);
@memcpy(@as([*]u8, @ptrFromInt(dst))[0..n], @as([*]const u8, @ptrCast(src.?))[0..n]);
return abi.success;
}
fn sync(_: abi.Stream) callconv(.c) abi.Result {
return abi.success;
}
fn syncCtx() callconv(.c) abi.Result {
return abi.success;
}
fn name(_: abi.Result, s: *?[*:0]const u8) callconv(.c) abi.Result {
s.* = null;
return 1;
}
pub fn driver() cuda.Driver {
var d: cuda.Driver = undefined;
d.func_name = null;
d.api.cuMemHostAlloc = hostAlloc;
d.api.cuMemFreeHost = hostFree;
d.api.cuMemAlloc_v2 = devAlloc;
d.api.cuMemFree_v2 = devFree;
d.api.cuMemcpyHtoD_v2 = copy;
d.api.cuStreamSynchronize = sync;
d.api.cuCtxSynchronize = syncCtx;
d.api.cuGetErrorName = name;
d.api.cuGetErrorString = name;
return d;
}
};

pub const layer_w = 64; // the experts' intermediate width
pub const layer_d = 64; // the model width
pub const layer_n = 12; // experts a layer, each projection in its own shard: 36 shards

/// One expert projection's planes: FP4 codes, row-major E4M3 scales a 16 (decoded, for CSF), the global.
pub const Planes = struct { codes: []u8, scales: []u8, global: f32 };

pub const Layer = struct { index: usize, csf: bool = false };

/// A CSF plane of `scales` [rows, cols], as core/nvfp4_csf_test.zig builds one: row bases, offsets, exceptions.
pub fn csfPlanes(scales: []u8, rows: usize, cols: usize, fixed: *std.ArrayList(u8), exceptions: *std.ArrayList(u8)) !void {
try fixed.appendNTimes(ta, 0, rows + rows * cols / 2);
for (0..rows) |row| {
const base: u8 = 0x30;
const slab = row / 16 * (16 + cols * 8);
fixed.items[slab + row % 16] = base;
for (0..cols) |col| {
const i = row * cols + col;
const delta: u8 = if (scales[i] >= base and scales[i] - base < 16) scales[i] - base else 0;
fixed.items[slab + 16 + row % 16 * (cols / 2) + col / 2] |= delta << @as(u3, if (col % 2 == 0) 0 else 4);
if (base + delta != scales[i]) try exceptions.appendSlice(ta, &std.mem.toBytes(std.mem.nativeToLittle(u32, @as(u32, @intCast(i)) | (@as(u32, scales[i]) << 24))));
}
}
}

/// `layers` with every expert projection in its own shard; `missing` drops one down projection's global.
pub fn fixture(dir: std.Io.Dir, layers: []const Layer, missing: ?struct { layer: usize, expert: usize }, planes: []Planes) !void {
var index: std.Io.Writer.Allocating = .init(ta);
defer index.deinit();
try index.writer.writeAll("{\"weight_map\":{");
var prng = std.Random.DefaultPrng.init(0xe1);
const r = prng.random();
var first = true;
var at: usize = 0;
for (layers) |layer| for (0..layer_n) |e| for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }, 0..) |proj, pi| {
const n: usize = if (pi == 2) layer_d else layer_w;
const k: usize = if (pi == 2) layer_w else layer_d;
const p = &planes[at];
at += 1;
p.* = .{ .codes = try ta.alloc(u8, n * k / 2), .scales = try ta.alloc(u8, n * k / 16), .global = 0.5 + 0.01 * @as(f32, @floatFromInt(e)) };
r.bytes(p.codes);
// finite E4M3 bytes; one in 9 off the CSF slab's 16-byte window (an exception)
for (p.scales) |*s| s.* = if (r.uintLessThan(u8, 9) == 0) 0x10 + r.uintLessThan(u8, 16) else 0x30 + r.uintLessThan(u8, 16);
const base = try std.fmt.allocPrint(ta, "language_model.model.layers.{d}.mlp.experts.{d}.{s}", .{ layer.index, e, proj });
defer ta.free(base);
const file = try std.fmt.allocPrint(ta, "l{d}-e{d}-{s}.safetensors", .{ layer.index, e, proj });
defer ta.free(file);
const drop = if (missing) |m| m.layer == layer.index and m.expert == e and pi == 2 else false;
var header: std.Io.Writer.Allocating = .init(ta);
defer header.deinit();
var data: std.ArrayList(u8) = .empty;
defer data.deinit(ta);
var parts: [4][]const u8 = undefined;
var nparts: usize = 0;
try data.appendSlice(ta, p.codes);
try header.writer.print("{{\"{s}.weight\":{{\"dtype\":\"U8\",\"shape\":[{d},{d}],\"data_offsets\":[0,{d}]}}", .{ base, n, k / 2, data.items.len });
parts[nparts] = "weight";
nparts += 1;
if (layer.csf) {
var fixed: std.ArrayList(u8) = .empty;
defer fixed.deinit(ta);
var exc: std.ArrayList(u8) = .empty;
defer exc.deinit(ta);
try csfPlanes(p.scales, n, k / 16, &fixed, &exc);
const f0 = data.items.len;
try data.appendSlice(ta, fixed.items);
try header.writer.print(",\"{s}.weight_scale.nvfp4_csf_fixed\":{{\"dtype\":\"U8\",\"shape\":[{d},{d}],\"data_offsets\":[{d},{d}]}}", .{ base, n / 16, 16 + 8 * (k / 16), f0, data.items.len });
const x0 = data.items.len;
try data.appendSlice(ta, exc.items);
try header.writer.print(",\"{s}.weight_scale.nvfp4_csf_exceptions\":{{\"dtype\":\"U32\",\"shape\":[{d}],\"data_offsets\":[{d},{d}]}}", .{ base, exc.items.len / 4, x0, data.items.len });
parts[nparts] = "weight_scale.nvfp4_csf_fixed";
parts[nparts + 1] = "weight_scale.nvfp4_csf_exceptions";
nparts += 2;
} else {
const s0 = data.items.len;
try data.appendSlice(ta, p.scales);
try header.writer.print(",\"{s}.weight_scale\":{{\"dtype\":\"F8_E4M3\",\"shape\":[{d},{d}],\"data_offsets\":[{d},{d}]}}", .{ base, n, k / 16, s0, data.items.len });
parts[nparts] = "weight_scale";
nparts += 1;
}
if (!drop) {
const g0 = data.items.len;
try data.appendSlice(ta, &std.mem.toBytes(@as(u32, @bitCast(p.global))));
try header.writer.print(",\"{s}.weight_scale_2\":{{\"dtype\":\"F32\",\"shape\":[],\"data_offsets\":[{d},{d}]}}", .{ base, g0, data.items.len });
parts[nparts] = "weight_scale_2";
nparts += 1;
}
try header.writer.writeByte('}');
var image: std.Io.Writer.Allocating = .init(ta);
defer image.deinit();
try image.writer.writeAll(&std.mem.toBytes(std.mem.nativeToLittle(u64, header.written().len)));
try image.writer.writeAll(header.written());
try image.writer.writeAll(data.items);
try dir.writeFile(io, .{ .sub_path = file, .data = image.written() });
for (parts[0..nparts]) |part| {
if (!first) try index.writer.writeByte(',');
first = false;
try index.writer.print("\"{s}.{s}\":\"{s}\"", .{ base, part, file });
}
};
try index.writer.writeAll("}}");
try dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.written() });
}

pub fn freePlanes(planes: []Planes) void {
for (planes) |p| {
ta.free(p.codes);
ta.free(p.scales);
}
}

pub fn prefixOf(buf: []u8, layer: usize) ![]const u8 {
return std.fmt.bufPrint(buf, "language_model.model.layers.{d}.mlp", .{layer});
}

/// The words and globals the one-expert loop packs for a layer's planes, against the device buffers.
pub fn expectLoopWords(owned: experts.Owned, planes: []const Planes) !void {
const up_words = ex.bytes(1, layer_w, layer_d, 2) / 4;
const down_words = ex.bytes(1, layer_d, layer_w, 1) / 4;
const want_up = try ta.alloc(u32, layer_n * up_words);
defer ta.free(want_up);
const want_down = try ta.alloc(u32, layer_n * down_words);
defer ta.free(want_down);
for (0..layer_n) |i| {
const g = planes[3 * i];
const u = planes[3 * i + 1];
const o = planes[3 * i + 2];
ex.packGateUp(want_up[i * up_words ..][0..up_words], .{ g.codes, g.scales }, .{ u.codes, u.scales }, layer_w, layer_d);
ex.packOne(want_down[i * down_words ..][0..down_words], o.codes, o.scales, layer_d, layer_w);
}
try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want_up), @as([*]const u8, @ptrFromInt(owned.up.ptr))[0..owned.up.len]);
try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(want_down), @as([*]const u8, @ptrFromInt(owned.down.ptr))[0..owned.down.len]);
const ug: [*]const f32 = @ptrFromInt(owned.up_scale.ptr);
const dg: [*]const f32 = @ptrFromInt(owned.down_scale.ptr);
for (0..layer_n) |i| {
try std.testing.expectEqual(planes[3 * i].global, ug[2 * i]);
try std.testing.expectEqual(planes[3 * i + 1].global, ug[2 * i + 1]);
try std.testing.expectEqual(planes[3 * i + 2].global, dg[i]);
}
}
Loading
Loading