Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Loading: a direct-read load on Linux (Spark 2.5, Dory, Gemma 4 and Qwen 3.5 on CUDA, and Flash Next's experts) that fails now names its reader's error, such as `EndOfFile` when a shard ends inside a tensor it reads, where every failure was `ReadFailed` (#2610).

- Linux: DeepSeek-V4.1's Engram shards on a disk or file system whose direct reads need more than a 512-byte sector, such as an NVMe with 4 KiB logical blocks, are read through the page cache, where their rows used to fail with `EngramReadFailed`; on a 512-byte disk they are still read direct, extent for extent (#2610).

- Linux: an O_DIRECT checkpoint read of a file that ends inside the span it asked for reports end of file instead of a failed read, so Nemotron's CUDA checkpoint reads stop on `EndOfFile` as they do through the page cache (nothing was copied wrongly before; the error was wrong); Nemotron's CUDA checkpoint reader is now tested on the host through its io_uring ring and its thread fallback (#2602).

- CI: the nightly Linux host job now runs `test-pdf-worker`, which spawns the PDF render worker from a Linux `tensorfold-native` so its `/proc/self/statm` memory cap and `close_range` run on Linux, and the new `test-cache-fit-host`, so the prompt-cache budget's no-footprint branch runs at all; both steps were only built into the macOS Metal graph before (#2599).
Expand Down
28 changes: 28 additions & 0 deletions zig/src/core/checkpoint_direct.zig
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,34 @@ test "layerAt names a layer and the next; repoint moves a map-first loader's vie
}
}

test "a shard shortened after open stops the layer it cuts with EndOfFile, the layer before it read" {
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const names = [_][]const u8{ "layers.0.a", "layers.1.a", "head" };
const image = try testImage(gpa, &names, 3 * 4096 + 17);
defer gpa.free(image);
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();
var l = Layers.init(gpa, &ck, 2);
defer l.deinit();
if (!l.on()) return error.SkipZigTest;
// the file now ends on a 4 KiB boundary inside layers.1.a (no mapped byte past it is touched)
const f = &ck.files.items[0];
const at: u64 = @intFromPtr(f.get("layers.1.a").?.bytes.ptr) - @intFromPtr(f.map.memory.ptr);
{
const file = try tmp.dir.openFile(io, "model.safetensors", .{ .mode = .read_write });
defer file.close(io);
try file.setLength(io, std.mem.alignForward(u64, at + 1, 4096));
}
try l.enter("layers.0.", null);
try std.testing.expectEqual(@as(usize, 3 * 4096 + 17), (try ck.get("layers.0.a")).bytes.len);
try std.testing.expectError(error.EndOfFile, l.enter("layers.1.", null));
}

test "TF_LOAD_DIRECT off or no readers leaves every call a no-op" {
const gpa = std.testing.allocator;
var ck: Checkpoint = .{ .gpa = gpa, .io = std.testing.io };
Expand Down
72 changes: 63 additions & 9 deletions zig/src/core/direct_gather.zig
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,24 @@ fn find(joined: []const Range, file: usize, lo: u64) usize {
return a;
}

fn ErrorOf(comptime f: anytype) type {
return @typeInfo(@typeInfo(@TypeOf(f)).@"fn".return_type.?).error_union.error_set;
}

/// What a reader's open or read of a piece fails with.
const Failure = ErrorOf(direct_io.File.open) || ErrorOf(direct_io.File.read);

const Work = struct {
sources: []const Source,
pieces: []const Piece,
arena: []align(direct_io.alignment) u8,
next: std.atomic.Value(usize) = .init(0),
failed: std.atomic.Value(bool) = .init(false),
first: Failure = error.ReadFailed, // written once, by the reader that set `failed`

fn fail(w: *Work, err: Failure) void {
if (w.failed.cmpxchgStrong(false, true, .monotonic, .monotonic) == null) w.first = err;
}
};

fn readAll(g: *Gather, sources: []const Source, pieces: []const Piece) !void {
Expand All @@ -199,7 +211,8 @@ fn readAll(g: *Gather, sources: []const Source, pieces: []const Piece) !void {
for (threads[1..n]) |*t| t.* = std.Thread.spawn(.{}, run, .{&w}) catch null;
run(&w);
for (threads[1..n]) |t| if (t) |th| th.join();
if (w.failed.load(.monotonic)) return error.ReadFailed;
// the joins order every reader's writes before this read
if (w.failed.load(.monotonic)) return w.first;
}

/// One reader: pieces off the shared cursor, each file opened once by this reader (direct where it is allowed).
Expand All @@ -210,15 +223,9 @@ fn run(w: *Work) void {
const i = w.next.fetchAdd(1, .monotonic);
if (i >= w.pieces.len) return;
const p = w.pieces[i];
if (files[p.file] == null) files[p.file] = direct_io.File.open(w.sources[p.file].path) catch {
w.failed.store(true, .monotonic);
return;
};
if (files[p.file] == null) files[p.file] = direct_io.File.open(w.sources[p.file].path) catch |err| return w.fail(err);
const dst: direct_io.Buffer = @alignCast(w.arena[p.dst..][0..direct_io.span(p.lo, p.len)]);
_ = files[p.file].?.read(dst, p.lo, p.len) catch {
w.failed.store(true, .monotonic);
return;
};
_ = files[p.file].?.read(dst, p.lo, p.len) catch |err| return w.fail(err);
}
}

Expand Down Expand Up @@ -298,6 +305,53 @@ test "a pair reads ahead into one arena while the other's views stay readable" {
try std.testing.expect(@intFromPtr(c.ptr) < @intFromPtr(p.gathers[0].arena.ptr) + p.gathers[0].arena.len);
}

test "a reader's error reaches the caller by name: a file shortened after it was mapped, or gone" {
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const io = std.testing.io;
const n = 3 * chunk + 12345;
const bytes = try gpa.alloc(u8, n);
defer gpa.free(bytes);
var prng = std.Random.DefaultPrng.init(13);
prng.random().bytes(bytes);
try tmp.dir.writeFile(io, .{ .sub_path = "s.bin", .data = bytes });
const real = try tmp.dir.realPathFileAlloc(io, "s.bin", gpa);
defer gpa.free(real);
const path = try gpa.dupeSentinel(u8, real, 0);
defer gpa.free(path);
const sources = [_]Source{.{ .path = path, .memory = bytes }};
const buf = try gpa.alignedAlloc(u8, .fromByteUnits(direct_io.alignment), direct_io.span(3 * chunk, n - 3 * chunk));
defer gpa.free(buf);
var g = Gather.init(gpa, 4);
defer g.deinit();
var p = Pair.init(gpa, 4);
defer p.deinit();
// one view, four pieces on four readers; the file ends inside the last piece, on and off a 4 KiB boundary
for ([_]u64{ 3 * chunk + 4096, 3 * chunk + 4096 + 77 }) |cut| {
try tmp.dir.writeFile(io, .{ .sub_path = "s.bin", .data = bytes });
{
const file = try tmp.dir.openFile(io, "s.bin", .{ .mode = .read_write });
defer file.close(io);
try file.setLength(io, cut);
}
// direct_io's own answer for the last piece: EndOfFile, but O_DIRECT off a boundary follows direct_io's rule
var f = try direct_io.File.open(path);
defer f.close();
const want: anyerror = if (f.read(buf, 3 * chunk, n - 3 * chunk)) |_| return error.TestUnexpectedResult else |err| err;
if (cut % direct_io.alignment == 0 or !f.direct) try std.testing.expectEqual(error.EndOfFile, want);
var view: []const u8 = bytes[5..];
try std.testing.expectError(want, g.read(&sources, &.{&view}));
try std.testing.expectEqual(bytes[5..].ptr, view.ptr); // not pointed at a partial copy
try p.start(&sources, &.{&view}, null);
try std.testing.expectError(want, p.wait());
}
try tmp.dir.deleteFile(io, "s.bin");
var gone: []const u8 = bytes[5..][0..10];
try std.testing.expectError(error.FileNotFound, g.read(&sources, &.{&gone}));
try std.testing.expectEqual(bytes[5..].ptr, gone.ptr);
}

test "a view outside every mapping is refused" {
const gpa = std.testing.allocator;
const a: [16]u8 = @splat(1);
Expand Down
29 changes: 29 additions & 0 deletions zig/src/families/deepseek_v41/engram_dio.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//! Whether a shard opened O_DIRECT takes its sector-aligned extent reads; one that refuses them is read buffered.
const std = @import("std");
const builtin = @import("builtin");
const linux = std.os.linux;
const sector = @import("engram_rows.zig").sector;

/// A test's disk in place of the system's pread (null: the system's).
pub var test_pread: if (builtin.is_test) ?*const fn (linux.fd_t, [*]u8, usize, i64) usize else void = if (builtin.is_test) null else {};

/// The pread of every serial and threaded Engram read.
pub fn pread(fd: linux.fd_t, buf: [*]u8, len: usize, off: i64) usize {
if (comptime builtin.is_test) if (test_pread) |f| return f(fd, buf, len, off);
return linux.pread(fd, buf, len, off);
}

/// `fd`, opened O_DIRECT, kept direct if it reads a sector at a sector; refused (EINVAL), O_DIRECT is cleared on it.
pub fn direct(fd: linux.fd_t, buf: []align(4096) u8) !bool {
while (true) switch (linux.errno(pread(fd, buf.ptr, sector, sector))) {
.INTR => continue,
.INVAL => break,
// bytes, the end of the file or an I/O error: the reads that follow report their own
else => return true,
};
const flags = linux.fcntl(fd, linux.F.GETFL, 0);
if (linux.errno(flags) != .SUCCESS) return error.EngramReadFailed;
const flag: usize = @as(u32, @bitCast(linux.O{ .DIRECT = true }));
if (linux.errno(linux.fcntl(fd, linux.F.SETFL, flags & ~flag)) != .SUCCESS) return error.EngramReadFailed;
return false;
}
97 changes: 97 additions & 0 deletions zig/src/families/deepseek_v41/engram_dio_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//! Linux Engram shards on a disk whose direct reads need 4 KiB, or 512 bytes as today: the same rows in every mode.
const std = @import("std");
const testing = std.testing;
const linux = std.os.linux;
const er = @import("engram_rows.zig");
const dio = @import("engram_dio.zig");
const fixture = @import("engram_fixture.zig");

const o_direct: usize = @as(u32, @bitCast(linux.O{ .DIRECT = true }));

fn isDirect(fd: linux.fd_t) bool {
return linux.fcntl(fd, linux.F.GETFL, 0) & o_direct != 0;
}

/// A disk whose direct reads start and end on `unit` (0: anywhere); any other fails with EINVAL, as the kernel's does.
const Disk = struct {
var unit: u64 = 0;
var refused: std.atomic.Value(u32) = .init(0);
var taken: std.atomic.Value(u32) = .init(0); // direct reads it served

fn pread(fd: linux.fd_t, buf: [*]u8, len: usize, off: i64) usize {
if (isDirect(fd)) {
if (unit != 0 and (@as(u64, @intCast(off)) % unit != 0 or len % unit != 0)) {
_ = refused.fetchAdd(1, .monotonic);
return @bitCast(-@as(isize, @backingInt(linux.E.INVAL)));
}
_ = taken.fetchAdd(1, .monotonic);
}
return linux.pread(fd, buf, len, off);
}
};

const Mode = enum { sync, pool, uring, aio };

fn openRows(a: std.mem.Allocator, root: []const u8, mode: Mode) !*er.Rows {
const r = try er.Rows.open(a, root, 0, 2, &.{1}, 4096);
errdefer r.close();
if (mode == .aio) {
try r.startAio();
r.aio.?.poll = false;
return r;
}
if (r.aio) |*x| {
x.deinit();
r.aio = null;
}
if (mode != .uring) if (r.ring) |*g| {
g.deinit();
r.ring = null;
};
if (mode == .pool and r.pool == null) try r.startPool(8);
if (mode == .sync) r.stopPool();
return r;
}

test "engram rows: a disk whose direct reads need 4 KiB reads its shard buffered, every row the same in every mode" {
const a = testing.allocator;
const io = testing.io;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
var lut_sha: [32]u8 = undefined;
const fx = try fixture.parseFx(arena.allocator(), &lut_sha);
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try fixture.writeShard(a, io, tmp.dir, fx);
const root = try tmp.dir.realPathFileAlloc(io, ".", a);
defer a.free(root);
dio.test_pread = Disk.pread;
defer dio.test_pread = null;
defer Disk.unit = 0;
// each mode's extents on today's disk: a 512-byte disk and a 4 KiB one read the same
var base: [4][2]u64 = undefined;
for ([_]u64{ 0, 512, 4096 }) |unit| for ([_]Mode{ .sync, .pool, .uring, .aio }, &base) |mode, *b| {
Disk.unit = unit;
Disk.refused.store(0, .monotonic);
Disk.taken.store(0, .monotonic);
const r = try openRows(a, root, mode);
defer r.close();
const t = &r.tables[0];
if (unit == 0 and !t.direct) return error.SkipZigTest; // this file system refuses O_DIRECT: nothing to refuse
for (fx.sets) |s| {
const out = try a.alloc(u16, s.idx.len * 256);
defer a.free(out);
try r.rows(0, s.idx, 256, out);
try testing.expectEqual(s.sha, fixture.sha(out));
}
if (unit == 0) b.* = .{ r.stats.reads, r.stats.bytes } else try testing.expectEqual(b.*, [2]u64{ r.stats.reads, r.stats.bytes });
// the 4 KiB disk refused one read, the check at open, and served none direct; the others refused none
const four = unit == 4096;
try testing.expectEqual(!four, t.direct);
try testing.expectEqual(!four, isDirect(t.fd));
try testing.expectEqual(@as(u32, @intFromBool(four)), Disk.refused.load(.monotonic));
// open's check and header read, then the serial and threaded reads of the rows
const taken = Disk.taken.load(.monotonic);
if (four) try testing.expectEqual(@as(u32, 0), taken) else if (mode == .sync or mode == .pool) try testing.expect(taken > 2);
};
}
7 changes: 5 additions & 2 deletions zig/src/families/deepseek_v41/engram_io.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const std = @import("std");
const linux = std.os.linux;
const engram_rows = @import("engram_rows.zig");
const dio = @import("engram_dio.zig");
const Rows = engram_rows.Rows;
const Header = engram_rows.Header;
const header_bytes = engram_rows.header_bytes;
Expand Down Expand Up @@ -265,6 +266,8 @@ pub fn openTable(gpa: std.mem.Allocator, path: [:0]const u8, cap: u32) !Table {
if (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &st)) != .SUCCESS) return error.StatFailed;
const hb = try gpa.alignedAlloc(u8, .fromByteUnits(page), page);
defer gpa.free(hb);
// a disk or file system whose direct reads need more than a sector (4 KiB blocks) reads this shard buffered
if (direct) direct = try dio.direct(fd, hb);
try preadAll(fd, hb, 0);
if (!direct) _ = linux.fadvise(fd, 0, page, linux.POSIX_FADV.DONTNEED);
const h = try Header.parse(hb[0..48], st.size);
Expand Down Expand Up @@ -557,7 +560,7 @@ pub fn readAt(fd: linux.fd_t, size: u64, direct: bool, buf: []u8, off: u64) !voi
const want = @min(buf.len, size - off);
var done: usize = 0;
while (done < want) {
const rc = linux.pread(fd, buf[done..].ptr, buf.len - done, @intCast(off + done));
const rc = dio.pread(fd, buf[done..].ptr, buf.len - done, @intCast(off + done));
switch (linux.errno(rc)) {
.SUCCESS => {},
.INTR => continue,
Expand All @@ -572,7 +575,7 @@ pub fn readAt(fd: linux.fd_t, size: u64, direct: bool, buf: []u8, off: u64) !voi
pub fn preadAll(fd: linux.fd_t, out: []u8, off: u64) !void {
var done: usize = 0;
while (done < out.len) {
const rc = linux.pread(fd, out[done..].ptr, out.len - done, @intCast(off + done));
const rc = dio.pread(fd, out[done..].ptr, out.len - done, @intCast(off + done));
switch (linux.errno(rc)) {
.SUCCESS => {},
.INTR => continue,
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/deepseek_v41/shared_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ test {
_ = @import("engram_shared_test.zig");
if (@import("builtin").os.tag == .linux or @import("builtin").os.tag == .macos) _ = @import("engram_rows_test.zig");
if (@import("builtin").os.tag == .macos) _ = @import("engram_rows_darwin_test.zig");
if (@import("builtin").os.tag == .linux) _ = @import("engram_dio_test.zig");
if (@import("builtin").os.tag == .linux or @import("builtin").os.tag == .macos) _ = @import("engram_pack_test.zig");
if (@import("builtin").os.tag == .linux or @import("builtin").os.tag == .macos) _ = @import("engram_manifest_test.zig");
std.testing.refAllDecls(@import("engram_rows.zig").Rows);
Expand Down
Loading