mirror of
https://github.com/ashhart/TensorFold.git
synced 2026-12-06 20:43:08 +08:00
Qwen4: keep a drafter's tapped attention inputs in the feature ring
A drafter may now ask for its own ascending layers instead of the final hyper-connection streams. Tap L is layer L's attention input: the hyper-connection mix after that layer's PLE, the row its attention projections read (forward_graph.zig attention boundary, gpu_ops hcMix). The ring then holds one plane per tap. The forward hands Ops a keeper, and hcMix at a tapped layer's attention boundary copies its rows into each item's plane before scratch is reused. copyTaps gathers positions into rows of every tap in order. One tap set per engine; any other set is refused with Qwen4FeatureTaps. The adapter serves the final tap or the engine's tap set at that mode's row width. The capture only copies an existing tensor: nothing the forward computes changes, and without taps the ring is #6409's.
This commit is contained in:
@@ -34,6 +34,8 @@ pub fn Engine(comptime G: type) type {
|
||||
slots: []Slot = undefined,
|
||||
created: usize = 0,
|
||||
features: bool = false,
|
||||
taps: [8]u32 = undefined, // a drafter's tapped layers, ascending; none: the ring keeps the final streams
|
||||
tap_count: usize = 0,
|
||||
absorb_rows: usize = 0, // a drafter's longest pass over kept rows (0: a window); the ring holds it and a window
|
||||
failed: std.atomic.Value(bool) = .init(false),
|
||||
pub fn open(a: std.mem.Allocator, io: std.Io, dir: []const u8, b: *B, o: admission.Options, p: *cfg.Problem, loader: anytype) !*Self {
|
||||
@@ -190,8 +192,13 @@ pub fn Engine(comptime G: type) type {
|
||||
try e.scratch.rewind(0);
|
||||
try batch.begin();
|
||||
var ops: @import("gpu_ops.zig").Ops(G) = .{ .gpu = &e.gpu, .model = &e.model, .scratch = &e.scratch, .host = e.a, .problem = p, .trace = e.trace, .profile = profile };
|
||||
var keeper: Keeper = .{ .e = e, .items = items };
|
||||
if (e.features and e.tap_count > 0) ops.taps = .{ .ptr = &keeper, .layers = e.tapLayers(), .keep = Keeper.keep };
|
||||
const logits = try graph.forward(&ops, geometry, &batch, tokens);
|
||||
if (e.features) try e.keepRows(items, ops.hidden orelse return error.Qwen4ResidualMissing);
|
||||
if (e.features) {
|
||||
if (e.tap_count == 0) try e.keepPlane(items, ops.hidden orelse return error.Qwen4ResidualMissing, 0, e.c.wide() * 2);
|
||||
for (items) |item| (try e.own(item.state)).rows_end = item.state.base_pos + item.tokens.len;
|
||||
}
|
||||
try ops.at(.draw);
|
||||
off = 0;
|
||||
for (items) |item| {
|
||||
@@ -211,21 +218,32 @@ pub fn Engine(comptime G: type) type {
|
||||
if (rows != 1) return null;
|
||||
return if (e.gpu.profile) |*q| q else null;
|
||||
}
|
||||
/// Final hyper-connection rows (the residual before the readout) of a stream's last `featureRows()` positions.
|
||||
/// Kept positions a stream: the final streams (the residual before the readout) or each tap's attention input.
|
||||
pub fn featureRows(e: *const Self) usize {
|
||||
return @max(2 * e.o.window, e.absorb_rows + e.o.window);
|
||||
}
|
||||
/// A drafter reads final rows from here on; each forward then copies its rows in, reading the residual only.
|
||||
pub fn keepFeatures(e: *Self) !void {
|
||||
if (e.features) return;
|
||||
const bytes = try std.math.mul(usize, e.featureRows(), e.c.wide() * 2);
|
||||
pub fn tapLayers(e: *const Self) []const u32 {
|
||||
return e.taps[0..e.tap_count];
|
||||
}
|
||||
/// One position's kept bytes: the final streams, or every tap's hidden row.
|
||||
pub fn featureRowBytes(e: *const Self) usize {
|
||||
return if (e.tap_count == 0) e.c.wide() * 2 else e.tap_count * e.c.hidden * 2;
|
||||
}
|
||||
/// A drafter reads kept rows from here on (taps: ascending layers, a plane of `featureRows()` rows each).
|
||||
pub fn keepFeatures(e: *Self, taps: []const u32) !void {
|
||||
if (taps.len > e.taps.len) return error.Qwen4FeatureTaps;
|
||||
for (taps, 0..) |layer, i| if (layer >= e.c.layers or (i > 0 and layer <= taps[i - 1])) return error.Qwen4FeatureTaps;
|
||||
if (e.features) return if (std.mem.eql(u32, e.tapLayers(), taps)) {} else error.Qwen4FeatureTaps;
|
||||
@memcpy(e.taps[0..taps.len], taps);
|
||||
e.tap_count = taps.len;
|
||||
const bytes = try std.math.mul(usize, e.featureRows(), e.featureRowBytes());
|
||||
for (e.slots) |*slot| if (slot.rows == null) {
|
||||
slot.rows = try e.backend.allocate(bytes);
|
||||
};
|
||||
e.features = true;
|
||||
}
|
||||
fn keepRows(e: *Self, items: []const Segment, h: Tensor) !void {
|
||||
const width = e.c.wide() * 2;
|
||||
/// Copies each item's rows of `h` (`width` bytes a row) to its ring positions in the plane at `plane`.
|
||||
fn keepPlane(e: *Self, items: []const Segment, h: Tensor, plane: usize, width: usize) !void {
|
||||
const ring = e.featureRows();
|
||||
var off: usize = 0;
|
||||
for (items) |item| {
|
||||
@@ -234,12 +252,34 @@ pub fn Engine(comptime G: type) type {
|
||||
const n = item.tokens.len;
|
||||
// At most two contiguous pieces: up to the ring's end, then from its start.
|
||||
const first = @min(n, ring - base % ring);
|
||||
try e.backend.copy(slot.rows.?, (base % ring) * width, h.buffer, h.offset + off * width, first * width);
|
||||
if (n > first) try e.backend.copy(slot.rows.?, 0, h.buffer, h.offset + (off + first) * width, (n - first) * width);
|
||||
slot.rows_end = base + n;
|
||||
try e.backend.copy(slot.rows.?, plane + (base % ring) * width, h.buffer, h.offset + off * width, first * width);
|
||||
if (n > first) try e.backend.copy(slot.rows.?, plane, h.buffer, h.offset + (off + first) * width, (n - first) * width);
|
||||
off += item.tokens.len;
|
||||
}
|
||||
}
|
||||
/// Tap `k`'s rows go to its plane while the forward still holds them (scratch is reused after each layer).
|
||||
const Keeper = struct {
|
||||
e: *Self,
|
||||
items: []const Segment,
|
||||
fn keep(ptr: *anyopaque, k: usize, h: Tensor) !void {
|
||||
const kp: *Keeper = @ptrCast(@alignCast(ptr));
|
||||
const e = kp.e;
|
||||
if (h.width != e.c.hidden) return error.Qwen4FeatureTaps;
|
||||
try e.keepPlane(kp.items, h, k * e.featureRows() * e.c.hidden * 2, e.c.hidden * 2);
|
||||
}
|
||||
};
|
||||
/// Positions [start, start + count) as rows of every tap in order, `featureRowBytes()` each, into `to`.
|
||||
pub fn copyTaps(e: *Self, slot: *const Slot, start: usize, count: usize, to: B.Buffer, to_off: usize) !void {
|
||||
if (e.tap_count == 0 or count == 0) return error.Qwen4FeatureTaps;
|
||||
_ = try e.featureRow(slot, start);
|
||||
_ = try e.featureRow(slot, start + count - 1);
|
||||
const ring = e.featureRows();
|
||||
const row = e.c.hidden * 2;
|
||||
for (0..count) |i| for (0..e.tap_count) |k| {
|
||||
const from = k * ring * row + ((start + i) % ring) * row;
|
||||
try e.backend.copy(to, to_off + (i * e.tap_count + k) * row, slot.rows.?, from, row);
|
||||
};
|
||||
}
|
||||
/// Ring row of position `pos`, if the last forwards still hold it (the drafter copies rows out in order).
|
||||
pub fn featureRow(e: *const Self, slot: *const Slot, pos: usize) !usize {
|
||||
if (!e.features or pos >= slot.rows_end or slot.rows_end - pos > e.featureRows()) return error.Qwen4FeatureRows;
|
||||
|
||||
@@ -24,6 +24,10 @@ pub fn Ops(comptime G: type) type {
|
||||
trace_scope: []const u8 = "",
|
||||
profile: ?*Profile = null,
|
||||
part: Group = .hc_attention,
|
||||
boundary: graph.Boundary = .attention,
|
||||
taps: ?Taps = null,
|
||||
/// A drafter's tapped layers: each one's attention input (the hyper-connection mix) is kept as it is made.
|
||||
pub const Taps = struct { ptr: *anyopaque, layers: []const u32, keep: *const fn (*anyopaque, usize, Tensor) anyerror!void };
|
||||
fn note(o: *Self, layer: ?usize, scope: []const u8, node: []const u8, x: Tensor) !void {
|
||||
const sink = o.trace orelse return;
|
||||
var buffer: [192]u8 = undefined;
|
||||
@@ -97,6 +101,7 @@ pub fn Ops(comptime G: type) type {
|
||||
.readout => .readout,
|
||||
};
|
||||
try o.at(o.part);
|
||||
o.boundary = b;
|
||||
const sums = try o.scratch.take(h.rows, h.width / 256, .f32);
|
||||
const out = try o.take(h.rows, h.width);
|
||||
try o.gpu.hcNorm(o.hc(layer, b).norm, h, sums, out, eps);
|
||||
@@ -136,6 +141,9 @@ pub fn Ops(comptime G: type) type {
|
||||
const sums = try o.scratch.take(up.rows, o.model.c.hidden / 32, .f32);
|
||||
try o.gpu.hcMix(up, normed, out, sums);
|
||||
try o.note(o.trace_layer, o.trace_scope, "mix", out);
|
||||
if (o.taps) |taps| if (o.boundary == .attention) if (o.trace_layer) |layer| {
|
||||
for (taps.layers, 0..) |tapped, k| if (tapped == layer) try taps.keep(taps.ptr, k, out);
|
||||
};
|
||||
return out;
|
||||
}
|
||||
pub fn writeback(o: *Self, h: Tensor, branch: Tensor, injection: Tensor) !Tensor {
|
||||
|
||||
@@ -38,20 +38,24 @@ pub fn Adapter(comptime E: type, comptime D: type, comptime L: type) type {
|
||||
pub fn finalTap(l: *const Self) u32 {
|
||||
return @intCast(l.e.c.layers);
|
||||
}
|
||||
/// The final tap, or a drafter's own ascending layers (each layer's attention input); one set per engine.
|
||||
fn prepareFeatures(p: *anyopaque, taps: []const u32) !void {
|
||||
const l = self(p);
|
||||
if (taps.len != 1 or taps[0] != l.finalTap()) return error.Qwen4FeatureTaps;
|
||||
try l.e.keepFeatures();
|
||||
try l.e.keepFeatures(if (taps.len == 1 and taps[0] == l.finalTap()) &.{} else taps);
|
||||
}
|
||||
fn kept(l: *const Self, taps: []const u32) bool {
|
||||
if (l.e.tap_count == 0) return taps.len == 1 and taps[0] == l.finalTap();
|
||||
return std.mem.eql(u32, taps, l.e.tapLayers());
|
||||
}
|
||||
/// Rows [start, start + count) must still be in the slot's ring; Qwen4's drafter reads them from the slot.
|
||||
fn features(p: *anyopaque, s: *L.Stream, taps: []const u32, start: u64, count: u32) !be.Features {
|
||||
const l = self(p);
|
||||
if (taps.len != 1 or taps[0] != l.finalTap()) return error.Qwen4FeatureTaps;
|
||||
if (!l.kept(taps)) return error.Qwen4FeatureTaps;
|
||||
if (count == 0) return error.Qwen4FeatureRows;
|
||||
const slot = (try l.find(s)).slot.?;
|
||||
_ = try l.e.featureRow(slot, @intCast(start));
|
||||
_ = try l.e.featureRow(slot, @intCast(start + count - 1));
|
||||
return .{ .buffer = 0, .rows = count, .row_bytes = @intCast(l.e.c.wide() * 2), .space = .device, .dtype = .bf16 };
|
||||
return .{ .buffer = 0, .rows = count, .row_bytes = @intCast(l.e.featureRowBytes()), .space = .device, .dtype = .bf16 };
|
||||
}
|
||||
fn self(p: *anyopaque) *Self {
|
||||
return @ptrCast(@alignCast(p));
|
||||
|
||||
Reference in New Issue
Block a user