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 @@ -15,6 +15,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
them, and the values are read as before with every default unchanged (#2306, part of #1660).
- LFM2.5-24B-A2B serves on one NVIDIA GPU from the MLX 4-bit export, on the shared CUDA kernels, with `--parallel`
streams and copy drafts; there is no drafter or prompt cache yet (#1492, part of #1488). Thanks to @jschmied.
- HIP: capture a drafter's requested target-layer taps in each stream's ring, with graph-on/off and planted kernel controls (#2314).

## 1.2.4

Expand Down
28 changes: 28 additions & 0 deletions zig/kernels/hip/decode/plan.hip
Original file line number Diff line number Diff line change
Expand Up @@ -467,4 +467,32 @@ tf_plan_keep(PlanArgs plan, const int* keep, const unsigned int* hidden, int hid
}
}


// Row r's 16-bit residual into its slot's tap ring (descriptor word before the page table; 0 skips) at its position.
__global__ void __launch_bounds__(256)
tf_plan_tap(const unsigned* x, int rows, int hidden, int tap, int taps, int tap_rows, PlanArgs plan) {
const long long i = gid();
const int pairs = hidden / 2;
if (i >= static_cast<long long>(rows) * pairs) return;
const int r = static_cast<int>(i / pairs);
const int j = static_cast<int>(i % pairs);
const unsigned long long* desc = plan_desc(plan, plan.slot[r]);
if (desc == nullptr) return;
unsigned* ring = reinterpret_cast<unsigned*>(desc[plan.pages - 1]);
if (ring == nullptr) return;
const long long at = (static_cast<long long>(plan.pos[r] % tap_rows) * taps + tap) * pairs + j;
ring[at] = x[i];
}

// tf_plan_tap for one stream's prompt rows, positions pos0 .. pos0 + rows, into `ring`.
__global__ void __launch_bounds__(256)
tf_tap_rows(const unsigned* x, unsigned* ring, int rows, int hidden, int tap, int taps, int tap_rows, long long pos0) {
const long long i = gid();
const int pairs = hidden / 2;
if (i >= static_cast<long long>(rows) * pairs) return;
const long long r = i / pairs;
const int j = static_cast<int>(i % pairs);
ring[((pos0 + r) % tap_rows * taps + tap) * pairs + j] = x[i];
}

} // extern "C"
2 changes: 1 addition & 1 deletion zig/src/core/contract/hip_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ const own_records = [_]Record{
},
},
} ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++
@import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records;
@import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records;

pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++
@import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++
Expand Down
4 changes: 2 additions & 2 deletions zig/src/core/contract/hip_records_families.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ pub const all = join: {

test "the HIP records stay main's; the family lists only regroup GLM-OCR's and the joint schema's" {
const every = @import("hip_records.zig").records;
try std.testing.expectEqual(@as(usize, 197), every.len); // main's records, GLM-OCR's 12 and the joint schema's 10 among them
try std.testing.expectEqual(@as(usize, 175), every.len - all.len);
try std.testing.expectEqual(@as(usize, 199), every.len); // 197 frozen records and two drafter-tap records
try std.testing.expectEqual(@as(usize, 177), every.len - all.len);
}
23 changes: 23 additions & 0 deletions zig/src/core/contract/hip_records_tap.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! Gate 5's records of a drafter's tap writes (plan.hip's tf_plan_tap for round rows, tf_tap_rows for prompt rows).
const Record = @import("hip_records.zig").Record;

pub const records = [_]Record{
.{
.launch = .{ .name = "drafter tap tf_plan_tap", .symbol = "tf_plan_tap", .image = "plan", .threads = 256 },
.usage = .{
.{ .vgprs = 13, .sgprs = 27, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 14, .sgprs = 27, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 13, .sgprs = 27, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 13, .sgprs = 29, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
},
},
.{
.launch = .{ .name = "drafter tap tf_tap_rows", .symbol = "tf_tap_rows", .image = "plan", .threads = 256 },
.usage = .{
.{ .vgprs = 15, .sgprs = 24, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 15, .sgprs = 24, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 15, .sgprs = 24, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 15, .sgprs = 26, .lds = 0, .private = 0, .bound = 256, .wave = 32 },
},
},
};
34 changes: 31 additions & 3 deletions zig/src/families/qwen3_5/backend/hip/engine/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ fn checkpointBytes(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !u64 {
/// What `load` found before reading the weights.
pub const Preflight = struct { pool: admission.Pool = undefined, held: u64 = 0, weights: u64 = 0 };

/// Rows a drafter reads behind a stream's newest prompt chunk or round (DFlash2's sliding window).
pub const tap_window = 2048;

pub const Engine = struct {
pub const Rows = lane_round.Rows;

Expand Down Expand Up @@ -245,7 +248,7 @@ pub const Engine = struct {
/// Device bytes beside the weights: `size`'s scratch and pool, `streams` lanes, `snapshots`, rank 0's head.
pub fn planBytes(e: *Engine, streams: usize, rows: usize, capacity: usize, pool_pages: usize, snapshots: usize) !usize {
const m = e.model();
const lane = state.Caches.deviceBytes(m, capacity) + m.spec.hidden * m.act.size();
const lane = state.Caches.deviceBytes(m, capacity) + m.spec.hidden * m.act.size() + m.taps.ringBytes(m.spec.hidden);
// under tensor parallelism only rank 0 holds the head
const head = if (e.o.rank > 0) 0 else try mtp.Head.deviceBytes(e.gpa, &e.driver, &e.lib, &e.weights, m, @min(rows, mtp.max_chains));
return try e.sizeBytes(rows, capacity, pool_pages) + streams * lane + snapshots * memory.linearBytes(m.spec) + head;
Expand Down Expand Up @@ -321,12 +324,37 @@ pub const Engine = struct {

/// Caches for `total` positions (at most the capacity) with every page taken.
pub fn newCaches(e: *Engine, total: usize) !state.Caches {
return state.Caches.initFull(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity));
var c = try state.Caches.initFull(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity));
errdefer c.deinit(e.gpa);
try e.addTap(&c);
return c;
}

/// Caches for `total` positions (at most the capacity) with no page yet: a stream takes them as it grows.
pub fn emptyCaches(e: *Engine, total: usize) !state.Caches {
return state.Caches.init(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity));
var c = try state.Caches.init(e.gpa, &e.pool, e.model(), @min(total, e.o.capacity));
errdefer c.deinit(e.gpa);
try e.addTap(&c);
return c;
}

fn addTap(e: *Engine, c: *state.Caches) !void {
const m = e.model();
if (m.taps.n > 0) try c.addTap(m.taps.ringBytes(m.spec.hidden));
}

/// The layers a drafter taps (none: off), filling rings of caches made after; captured rounds are dropped.
pub fn setTaps(e: *Engine, layers: []const u32) !void {
const m = &e.bridge.model;
if (layers.len > m.taps.layers.len) return error.TooManyTaps;
for (layers) |l| if (l >= m.spec.n_layers) return error.BadTap;
if (layers.len > 0 and m.act.size() != 2) return error.TapsNeed16Bit;
try e.stream.synchronize();
e.graphs.deinit();
e.graphs = round_graphs.Graphs.init(e.gpa);
@memcpy(m.taps.layers[0..layers.len], layers);
m.taps.n = layers.len;
m.taps.rows = if (layers.len > 0) tap_window + @max(e.o.prompt_rows, e.o.batch_rows) else 0;
}

/// Whether the draft head's greedy batches replay graphs.
Expand Down
19 changes: 19 additions & 0 deletions zig/src/families/qwen3_5/backend/hip/engine/hip_lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,25 @@ pub const Hip = struct {
}
}

/// A drafter's tapped layers, told before any stream exists: their rings then come with every stream's caches.
pub fn prepareFeatures(h: *Hip, taps: []const u32) !void {
if (h.streams.map.count() != 0) return error.TapsAfterStreams;
if (h.e.o.world != 1) return error.TapsUnderTensorParallel;
try h.e.setTaps(taps);
}

/// Rows [start, start + count) of a lane's tap ring (row = position % ring rows), the newest ring rows kept.
pub fn features(h: *Hip, lane: *const Lane, taps: []const u32, start: u64, count: u32) !be.Features {
const t = &h.e.model().taps;
if (taps.len != t.n or !std.mem.eql(u32, taps, t.layers[0..t.n])) return error.TapsMismatch;
const ring = lane.caches.tap orelse return error.NoTaps;
// a verify's rows are in the ring before its keep: they count as written until the keep drops them
const written = lane.len + if (lane.pending) |p| p.rows else 0;
if (start + count > written or start + count <= written -| t.rows) return error.RowsNotHeld;
const row_bytes = t.n * h.e.model().spec.hidden * 2;
return .{ .buffer = ring.base(), .offset = start, .rows = count, .row_bytes = @intCast(row_bytes), .space = .device, .device = h.e.o.device, .dtype = if (h.e.act == .bf16) .bf16 else .f16 };
}

/// The stream's lane freed; the other ranks free theirs.
pub fn release(h: *Hip, lane: *Lane) void {
h.tp.release(lane.id) catch {};
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/qwen3_5/backend/hip/engine/native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ fn prepare(
"the native HIP engine cannot allocate its scratch and pages ({s})",
.{@errorName(err)},
);
const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size()));
const lane = gibs(state.Caches.deviceBytes(e.model(), capacity) + e.model().taps.ringBytes(e.model().spec.hidden) + pages.pagesFor(capacity) * memory.pageBytes(e.weights.spec, e.act.size()));
const startup = try std.fmt.allocPrint(gpa, "HIP {s} device {d}, rank {d} of {d}: model {d:.2} GiB; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompt cache {d:.2} GiB ({d} pages, {d} snapshots); prompts in {d}-row chunks", .{
hip.kernels.arch, dev.index, o.rank, o.world, gibs(model), streams, if (streams == 1) "" else "s", lane, window, gibs(room), gibs(reserve), gibs(budget), cache.pages, cache.snaps, prefix.chunk,
});
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/qwen3_5/backend/hip/forward/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ pub fn span(ops: Ops, m: *const view.Model, caches: *state.Caches, ids: u64, len
try reduce.residualNorm(o, m.tp, xs, y, post_norm, normed, rows, s.hidden, @floatCast(s.eps));
const z = try mlpRows(o, m, mlp, normed, rows, true);
try residual(o, m, xs, z, rows * s.hidden);
if (m.taps.of(index)) |ti| if (caches.tap) |ring| try hip.plan_ops.tapRows(o, xs, ring.base(), rows, s.hidden, ti, m.taps.n, m.taps.rows, pos0 + start);
}
if (trace) |t| t.layer(t.ctx, index, x, len) catch |err| return if (err == error.Cancelled) error.Cancelled else error.HipFailed;
}
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/qwen3_5/backend/hip/forward/plan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub const Buffer = struct {
.count = at + 4 * l.count,
.desc = at + 4 * l.desc,
.snaps = at + 4 * l.snaps,
.pages = @intCast(state.header_words + 2 * l.layers),
.pages = @intCast(state.tableWord(l.layers)),
.pool = b.pool_pages,
};
}
Expand Down
33 changes: 29 additions & 4 deletions zig/src/families/qwen3_5/backend/hip/forward/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ pub const LayerCache = union(enum) {
/// Words of a descriptor before its layers: the positions it holds and the last kept final row.
pub const header_words = 2;

/// The descriptor word after the layers' addresses: the stream's tap ring (0: none), then the page table.
pub fn tapWord(layers: usize) usize {
return header_words + 2 * layers;
}

/// Words of a descriptor before its page table (PlanArgs.pages).
pub fn tableWord(layers: usize) usize {
return tapWord(layers) + 1;
}

pub const Caches = struct {
layers: []LayerCache,
/// Positions the page table can name.
Expand All @@ -26,6 +36,8 @@ pub const Caches = struct {
table: std.ArrayList(u32) = .empty,
/// Pages promised to this stream, not yet taken (the pool's reservation).
promised: usize = 0,
/// A drafter's tap ring (`addTap`): the newest rows of the tapped layers' residuals.
tap: ?hip.DeviceBuffer = null,

/// Device bytes the caches of `total` positions hold beside their pages: linear state and the descriptor.
pub fn deviceBytes(m: *const view.Model, total: usize) usize {
Expand All @@ -34,7 +46,7 @@ pub const Caches = struct {
for (0..s.n_layers) |i| linear += @intFromBool(!s.full(i));
const conv = (s.conv - 1) * view.convChannels(s) * 4;
const state = s.value_heads * s.value_dim * s.key_dim * 4;
return linear * (conv + state) + 8 * (header_words + 2 * s.n_layers + std.mem.alignForward(usize, pages.pagesFor(total), 2) / 2);
return linear * (conv + state) + 8 * (tableWord(s.n_layers) + std.mem.alignForward(usize, pages.pagesFor(total), 2) / 2);
}

/// Caches for up to `total` positions with no pages yet; every linear byte zeroed.
Expand Down Expand Up @@ -62,7 +74,7 @@ pub const Caches = struct {
made += 1;
}
const slots = std.mem.alignForward(usize, pages.pagesFor(total), 2);
const words = try gpa.alloc(u64, header_words + 2 * s.n_layers + slots / 2);
const words = try gpa.alloc(u64, tableWord(s.n_layers) + slots / 2);
defer gpa.free(words);
@memset(words, 0);
var desc = try hip.DeviceBuffer.alloc(d, 8 * words.len);
Expand All @@ -84,6 +96,17 @@ pub const Caches = struct {
return c;
}

/// A tap ring of `bytes` for this stream, its address in the descriptor; every byte zeroed.
pub fn addTap(c: *Caches, bytes: usize) !void {
std.debug.assert(c.tap == null);
var ring = try hip.DeviceBuffer.alloc(c.pool.d, bytes);
errdefer ring.free();
try ring.fill8(0);
const at = ring.base();
try c.desc.upload(8 * tapWord(c.layers.len), std.mem.asBytes(&at));
c.tap = ring;
}

/// The stream's last kept final row lives at `ptr`: a round's keep copies it there.
pub fn setHidden(c: *const Caches, ptr: u64) !void {
try c.desc.upload(8, std.mem.asBytes(&ptr));
Expand All @@ -105,6 +128,7 @@ pub const Caches = struct {
c.pool.ids.reserved -|= c.promised;
c.table.deinit(gpa);
c.desc.free();
if (c.tap) |*t| t.free();
for (c.layers) |*l| free(l);
gpa.free(c.layers);
c.* = undefined;
Expand All @@ -118,6 +142,7 @@ pub const Caches = struct {
/// Bytes this stream holds: its linear state and every page it names (shared ones counted whole).
pub fn held(c: *const Caches) usize {
var n: usize = c.table.items.len * c.pool.pageBytes();
if (c.tap) |t| n += t.len;
for (c.layers) |l| switch (l) {
.full => {},
.linear => |x| n += x.conv.len + x.state.len,
Expand All @@ -126,7 +151,7 @@ pub const Caches = struct {
}

fn put(c: *const Caches, first: usize, ids: []const u32) !void {
const base = 8 * (header_words + 2 * c.layers.len);
const base = 8 * tableWord(c.layers.len);
try c.desc.upload(base + 4 * first, std.mem.sliceAsBytes(ids));
}

Expand Down Expand Up @@ -184,7 +209,7 @@ pub const Caches = struct {

/// The attention kernels' view of a full layer's pages.
pub fn paged(c: *const Caches, m: *const view.Model, index: usize) hip.ops.Ops.Paged {
const base = c.desc.base() + 8 * (header_words + 2 * c.layers.len);
const base = c.desc.base() + 8 * tableWord(c.layers.len);
return .{ .k = c.pool.keys[index].base(), .v = c.pool.values[index].base(), .table = base, .kind = m.act, .kv_heads = m.spec.kv_heads, .d = m.spec.head_dim, .count = c.pool.count };
}

Expand Down
1 change: 1 addition & 0 deletions zig/src/families/qwen3_5/backend/hip/forward/window.zig
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ pub fn forward(ops: Ops, m: *const view.Model, r: Round, trace: ?fwd.Trace) fwd.
}
},
}
if (m.taps.of(index)) |ti| try pops.tap(o, x, r.plan, s.hidden, ti, m.taps.n, m.taps.rows);
if (trace) |t| t.layer(t.ctx, index, x, total) catch return error.HipFailed;
}
return out;
Expand Down
20 changes: 20 additions & 0 deletions zig/src/families/qwen3_5/backend/hip/model/view.zig
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,26 @@ pub const Model = struct {
head: Projection,
qk: QkNorm,
mtp: ?Mtp = null,
/// A drafter's tapped layers: after each, every row's residual lands in its stream's tap ring.
taps: Taps = .{},
};

/// The layers a drafter taps and the rows a stream's ring keeps (`Caches.tap`, row = position % rows).
pub const Taps = struct {
layers: [8]u32 = undefined,
n: usize = 0,
rows: usize = 0,

/// The tap index of layer `layer`, or null when it is not tapped.
pub fn of(t: *const Taps, layer: usize) ?usize {
for (t.layers[0..t.n], 0..) |l, i| if (l == layer) return i;
return null;
}

/// Bytes of one stream's ring: `rows` rows of every tapped layer's `hidden` 16-bit values.
pub fn ringBytes(t: *const Taps, hidden: usize) usize {
return t.rows * t.n * hidden * 2;
}
};

/// q and k's normalize_qk weights and eps exactly as Python makes them: double arithmetic, then fp32.
Expand Down
1 change: 1 addition & 0 deletions zig/src/hip/kernel_tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ test {
_ = @import("kernel_tests/attention_pin.zig");
_ = @import("kernel_tests/attention_edge.zig");
_ = @import("kernel_tests/stats.zig");
_ = @import("kernel_tests/tap.zig");
_ = @import("kernel_tests/ops.zig");
_ = @import("kernel_tests/conv_split.zig");
_ = @import("kernel_tests/dense.zig");
Expand Down
Loading
Loading