diff --git a/CHANGELOG.md b/CHANGELOG.md index 124928b35c0..1bd2d3eb800 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). +- Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). - Server: an image URL's host lookup stops at 3 seconds (or the request's deadline, if sooner) even when the system resolver keeps retrying, at most 64 lookups run at once, and a refused connection falls through to the host's next checked address (#3127). - Living Weights: a fact graph write the OS refuses names its cause, for example "ShardWrite (ISDIR)" (#3126). diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index ce6bba865ae..e6dba586ffb 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -93,7 +93,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { } /// macOS: tf-kernel-contract over the engine's Metal kernels; `kernel-contract` runs it on this Mac's GPU. -pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module) void { +pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { @import("rotary_sweep.zig").steps(b, target, metal_mod); const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), @@ -131,6 +131,18 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil }, }) }); b.step("test-ling-route-gpu", "Ling grouped route on this GPU against the host formula").dependOn(&b.addRunArtifact(ling_gpu).step); + const ling_kda_gpu = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_kda_gpu.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "kda", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/kda.zig") }) }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + }, + }) }); + b.step("test-ling-kda-gpu", "Ling KDA mixer on this GPU against kda.zig, using k3_kda").dependOn(&b.addRunArtifact(ling_kda_gpu).step); } /// Linux: `kernel-contract` runs tf-cuda-test's kernel-contract command (kernels from -Dnvcc or -Dfatbins). diff --git a/zig/build/ling_host.zig b/zig/build/ling_host.zig index faf3c94a9a5..b802cbd518a 100644 --- a/zig/build/ling_host.zig +++ b/zig/build/ling_host.zig @@ -7,6 +7,6 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu .target = target, }); const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); - b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing").dependOn(&run.step); + b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer").dependOn(&run.step); test_step.dependOn(&run.step); } diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 0211c0aca39..1df2fb794cc 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -438,7 +438,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s // The core lane, shared-context and Qwen3.8-27B programs and host tests. qwen27_build.targets(b, target, optimize, metal, sources, engine, lanes, mods.qwen27, test_step); core_checks.targets(b, target, optimize, metal, engine); - contract_build.metal(b, target, optimize, metal, engine, sources); + contract_build.metal(b, target, optimize, metal, engine, sources, kimi_bytes); glm_checks.targets(b, target, optimize, metal, engine, sources); flashnext_checks.targets(b, target, optimize, metal, engine); diff --git a/zig/src/families/ling/fixtures/kda_tiny_h16_r2.bin b/zig/src/families/ling/fixtures/kda_tiny_h16_r2.bin new file mode 100644 index 00000000000..52db68b16c6 Binary files /dev/null and b/zig/src/families/ling/fixtures/kda_tiny_h16_r2.bin differ diff --git a/zig/src/families/ling/fixtures/kda_tiny_h16_r4.bin b/zig/src/families/ling/fixtures/kda_tiny_h16_r4.bin new file mode 100644 index 00000000000..315634faab5 Binary files /dev/null and b/zig/src/families/ling/fixtures/kda_tiny_h16_r4.bin differ diff --git a/zig/src/families/ling/host_test.zig b/zig/src/families/ling/host_test.zig index 9cc556cf1eb..e339b37f0c2 100644 --- a/zig/src/families/ling/host_test.zig +++ b/zig/src/families/ling/host_test.zig @@ -9,6 +9,7 @@ test { _ = @import("tiny_test.zig"); _ = @import("synth.zig"); _ = @import("route.zig"); + _ = @import("kda.zig"); } test "the float64 oracle handles tiny's null SwiGLU lists" { diff --git a/zig/src/families/ling/kda.zig b/zig/src/families/ling/kda.zig new file mode 100644 index 00000000000..20a9eab8387 --- /dev/null +++ b/zig/src/families/ling/kda.zig @@ -0,0 +1,362 @@ +//! Ling KDA mixer: k3_kda job (conv, gates, delta, RMS). D=128, 4 taps; host formula plus GPU check. +const std = @import("std"); +const config = @import("config.zig"); + +pub const dim = config.fixed.kda_dim; +pub const taps = config.fixed.conv; +/// Stack conv window in mixAs. Tiny is 16 heads x 128 = 2048. Wider Lings need a heap window. +pub const max_width: u32 = 2048; +pub const dump_h16_r2 = @embedFile("fixtures/kda_tiny_h16_r2.bin"); +pub const dump_h16_r4 = @embedFile("fixtures/kda_tiny_h16_r4.bin"); +const q_scale: f32 = 0.08838834764831845; // 1/sqrt(128) + +pub const Shape = struct { + heads: u32, + lower_bound: f32, + eps: f32, + + pub fn of(c: *const config.Config) Shape { + return .{ .heads = c.kda_heads, .lower_bound = c.lower_bound, .eps = c.eps }; + } + + pub fn width(s: Shape) u32 { + return s.heads * dim; + } +}; + +fn sig(comptime T: type, x: T) T { + return 1.0 / (1.0 + @exp(-x)); +} + +/// Same round-trip as Metal `float(bfloat(x))` / `k3_kda`'s conv and delta output. +fn roundBf16(v: f32) f32 { + const bits: u32 = @bitCast(v); + const h: u16 = @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + return @bitCast(@as(u32, h) << 16); +} + +fn maybeRound(comptime T: type, comptime to_bf16: bool, v: T) T { + if (!to_bf16) return v; + return @floatCast(roundBf16(@floatCast(v))); +} + +fn mixAs( + comptime T: type, + comptime to_bf16: bool, + y: []T, + S: []T, + proj: []const f32, + fgate: []const f32, + braw: []const f32, + g2: []const f32, + conv_q: []const f32, + conv_k: []const f32, + conv_v: []const f32, + A_log: []const f32, + dt_bias: []const f32, + o_norm: []const f32, + s: Shape, + rows: u32, +) void { + const W = s.width(); + const H = s.heads; + const window_cap = 3 * max_width; + var windows: [window_cap][3]T = @splat(.{ 0, 0, 0 }); + const scale: T = if (T == f32) q_scale else 1.0 / @sqrt(@as(T, @floatFromInt(dim))); + const lower: T = @floatCast(s.lower_bound); + const eps: T = @floatCast(s.eps); + + for (0..rows) |r| { + for (0..H) |h| { + var q: [dim]T = undefined; + var k: [dim]T = undefined; + var v: [dim]T = undefined; + var a: [dim]T = undefined; + const rate = @exp(@as(T, @floatCast(A_log[h]))); + for (0..dim) |d| { + const ch_base = h * dim + d; + inline for (.{ 0, 1, 2 }, .{ &q, &k, &v }, .{ conv_q, conv_k, conv_v }) |part, slot, cw| { + const ch = part * W + ch_base; + const x: T = @floatCast(proj[r * 3 * W + ch]); + const w = windows[ch]; + const acc = w[0] * @as(T, @floatCast(cw[ch_base * taps])) + + w[1] * @as(T, @floatCast(cw[ch_base * taps + 1])) + + w[2] * @as(T, @floatCast(cw[ch_base * taps + 2])) + + x * @as(T, @floatCast(cw[ch_base * taps + 3])); + slot[d] = maybeRound(T, to_bf16, acc * sig(T, acc)); + windows[ch] = .{ w[1], w[2], x }; + } + const g = @as(T, @floatCast(fgate[r * W + ch_base])) + @as(T, @floatCast(dt_bias[ch_base])); + a[d] = @exp(lower * sig(T, rate * g)); + } + const beta = sig(T, @floatCast(braw[r * H + h])); + var ss_q: T = 0; + var ss_k: T = 0; + for (0..dim) |d| { + ss_q += q[d] * q[d]; + ss_k += k[d] * k[d]; + } + const rq = @sqrt(ss_q + 1e-6); + const rk = @sqrt(ss_k + 1e-6); + for (0..dim) |d| { + q[d] = q[d] / rq * scale; + k[d] = k[d] / rk; + } + const Sh = S[h * dim * dim ..][0 .. dim * dim]; + var o: [dim]T = undefined; + for (0..dim) |j| { + var p: T = 0; + for (0..dim) |i| p += Sh[j * dim + i] * a[i] * k[i]; + const u = (v[j] - p) * beta; + for (0..dim) |i| Sh[j * dim + i] = Sh[j * dim + i] * a[i] + k[i] * u; + var acc: T = 0; + for (0..dim) |i| acc += Sh[j * dim + i] * q[i]; + o[j] = maybeRound(T, to_bf16, acc); + } + var var_o: T = 0; + for (o) |v_o| var_o += v_o * v_o; + const rstd = 1.0 / @sqrt(var_o / @as(T, @floatFromInt(dim)) + eps); + for (0..dim) |v_i| { + const g2v = sig(T, @floatCast(g2[r * W + h * dim + v_i])); + y[r * W + h * dim + v_i] = maybeRound(T, to_bf16, o[v_i] * rstd * @as(T, @floatCast(o_norm[v_i])) * g2v); + } + } + } +} + +/// One stream of `rows` through one KDA layer, f32 with the kernel's bf16 rounds. `proj` is q|k|v at 3W. +pub fn mix( + y: []f32, + S: []f32, + proj: []const f32, + fgate: []const f32, + braw: []const f32, + g2: []const f32, + conv_q: []const f32, + conv_k: []const f32, + conv_v: []const f32, + A_log: []const f32, + dt_bias: []const f32, + o_norm: []const f32, + s: Shape, + rows: u32, +) error{KdaWidthTooWide}!void { + if (s.width() > max_width) return error.KdaWidthTooWide; + mixAs(f32, true, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); +} + +/// Same mixer in float64, no extra rounding: oracle/kda_inner.py (copy of Model.kda, r = identity). +pub fn mixF64( + y: []f64, + S: []f64, + proj: []const f32, + fgate: []const f32, + braw: []const f32, + g2: []const f32, + conv_q: []const f32, + conv_k: []const f32, + conv_v: []const f32, + A_log: []const f32, + dt_bias: []const f32, + o_norm: []const f32, + s: Shape, + rows: u32, +) error{KdaWidthTooWide}!void { + if (s.width() > max_width) return error.KdaWidthTooWide; + mixAs(f64, false, y, S, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); +} + +test "tiny KDA geometry is the k3_kda kernel's: 16 heads, D=128, 4 taps, lower_bound -5" { + const tiny = @embedFile("fixtures/tiny_config.json"); + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, tiny, &why); + const s = Shape.of(&c); + try std.testing.expectEqual(@as(u32, 16), s.heads); + try std.testing.expectEqual(@as(u32, 128), dim); + try std.testing.expectEqual(@as(u32, 4), taps); + try std.testing.expectEqual(@as(u32, 18), c.countKind(.kda)); + try std.testing.expect(c.lower_bound == -5); +} + +test "a zero stream stays zero: empty proj and gates give y = 0" { + const s = Shape{ .heads = 1, .lower_bound = -5, .eps = 1e-6 }; + var y: [dim]f32 = undefined; + var S: [dim * dim]f32 = @splat(0); + const z3: [3 * dim]f32 = @splat(0); + const z1: [dim]f32 = @splat(0); + const braw = [_]f32{0}; + var conv: [dim * taps]f32 = @splat(0); + const A = [_]f32{0}; + const on: [dim]f32 = @splat(1); + try mix(&y, &S, &z3, &z1, &braw, &z1, &conv, &conv, &conv, &A, &z1, &on, s, 1); + for (y) |v| try std.testing.expect(v == 0); +} + +test "mix refuses width over 2048 so ReleaseFast cannot overrun the stack window" { + const s = Shape{ .heads = 17, .lower_bound = -5, .eps = 1e-6 }; + try std.testing.expect(s.width() > max_width); + try std.testing.expectError(error.KdaWidthTooWide, mix(&.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, s, 1)); + try std.testing.expectError(error.KdaWidthTooWide, mixF64(&.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, &.{}, s, 1)); +} + +fn takeU32(b: []const u8, off: *usize) u32 { + const v = std.mem.readInt(u32, b[off.*..][0..4], .little); + off.* += 4; + return v; +} + +fn takeF32(b: []const u8, off: *usize) f32 { + const v = takeU32(b, off); + return @bitCast(v); +} + +fn takeF32s(a: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f32 { + const x = try a.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 4]); + off.* += n * 4; + return x; +} + +fn checkOracle(bytes: []const u8) !void { + const a = std.testing.allocator; + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGK1")); + var off: usize = 8; + const heads = takeU32(bytes, &off); + const rows = takeU32(bytes, &off); + const d = takeU32(bytes, &off); + const tp = takeU32(bytes, &off); + try std.testing.expectEqual(dim, d); + try std.testing.expectEqual(taps, tp); + const lower = takeF32(bytes, &off); + const eps = takeF32(bytes, &off); + off += 8; // seed, unused at check time + const s = Shape{ .heads = heads, .lower_bound = lower, .eps = eps }; + const W = s.width(); + const H = s.heads; + const proj = try takeF32s(a, bytes, &off, rows * 3 * W); + defer a.free(proj); + const fgate = try takeF32s(a, bytes, &off, rows * W); + defer a.free(fgate); + const braw = try takeF32s(a, bytes, &off, rows * H); + defer a.free(braw); + const g2 = try takeF32s(a, bytes, &off, rows * W); + defer a.free(g2); + const conv_q = try takeF32s(a, bytes, &off, W * taps); + defer a.free(conv_q); + const conv_k = try takeF32s(a, bytes, &off, W * taps); + defer a.free(conv_k); + const conv_v = try takeF32s(a, bytes, &off, W * taps); + defer a.free(conv_v); + const A_log = try takeF32s(a, bytes, &off, H); + defer a.free(A_log); + const dt_bias = try takeF32s(a, bytes, &off, W); + defer a.free(dt_bias); + const o_norm = try takeF32s(a, bytes, &off, dim); + defer a.free(o_norm); + const want_n = rows * W; + const want = try a.alloc(f64, want_n); + defer a.free(want); + @memcpy(std.mem.sliceAsBytes(want), bytes[off .. off + want_n * 8]); + off += want_n * 8; + try std.testing.expectEqual(bytes.len, off); + + const got64 = try a.alloc(f64, want_n); + defer a.free(got64); + const S64 = try a.alloc(f64, H * dim * dim); + defer a.free(S64); + @memset(S64, 0); + try mixF64(got64, S64, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + var worst64: f64 = 0; + for (want, got64) |w_y, g_y| worst64 = @max(worst64, @abs(w_y - g_y)); + std.debug.print("mixF64 vs kda_inner.py worst abs {e} ({d} heads, {d} rows)\n", .{ worst64, H, rows }); + try std.testing.expect(worst64 < 1e-8); + + const got_math = try a.alloc(f32, want_n); + defer a.free(got_math); + const S_math = try a.alloc(f32, H * dim * dim); + defer a.free(S_math); + @memset(S_math, 0); + mixAs(f32, false, got_math, S_math, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + try gateMixMath(want, got_math, W, rows, H); + + const got32 = try a.alloc(f32, want_n); + defer a.free(got32); + const S32 = try a.alloc(f32, H * dim * dim); + defer a.free(S32); + @memset(S32, 0); + try mix(got32, S32, proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, s, rows); + var row: u32 = 0; + while (row < rows) : (row += 1) { + var worst: f64 = 0; + const lo = row * W; + for (want[lo .. lo + W], got32[lo .. lo + W]) |w_y, g_y| + worst = @max(worst, @abs(w_y - @as(f64, g_y))); + std.debug.print("mix vs dump row {d} worst abs {d:.6} ({d} heads)\n", .{ row, worst, H }); + } +} + +fn mixMathRatio(want: []const f64, got: []const f32, W: u32, rows: u32, k: i32) f64 { + const u = std.math.ldexp(@as(f64, 1.0), -k); + var worst: f64 = 0; + var r: u32 = 0; + while (r < rows) : (r += 1) { + const lo = r * W; + var rowmax: f64 = 0; + for (want[lo .. lo + W]) |v| rowmax = @max(rowmax, @abs(v)); + for (want[lo .. lo + W], got[lo .. lo + W]) |y, g| { + const err = @abs(y - @as(f64, g)); + const tol = @abs(y) * u + rowmax * u; + if (tol == 0) { + if (err != 0) worst = std.math.inf(f64); + } else { + worst = @max(worst, err / tol); + } + } + } + return worst; +} + +fn gateMixMath(want: []const f64, got: []const f32, W: u32, rows: u32, H: u32) !void { + const k: i32 = 16; + const ratio = mixMathRatio(want, got, W, rows, k); + const margin: f64 = if (ratio > 0) 1.0 / ratio else std.math.inf(f64); + std.debug.print("mixAs f32 no-bf16 vs dump 2^-{d} margin {d:.2}x ({d} heads, {d} rows)\n", .{ k, margin, H, rows }); + try std.testing.expect(ratio <= 0.5); +} + +test "roundBf16 ties to even, subnormals, inf and NaN" { + const Case = struct { src: u32, want: u32 }; + const cases = [_]Case{ + .{ .src = 0x00000000, .want = 0x00000000 }, // +0 + .{ .src = 0x80000000, .want = 0x80000000 }, // -0 + .{ .src = 0x3f800000, .want = 0x3f800000 }, // 1.0 + .{ .src = 0xbf800000, .want = 0xbf800000 }, // -1.0 + .{ .src = 0x3f808000, .want = 0x3f800000 }, // tie to even + .{ .src = 0x3f807fff, .want = 0x3f800000 }, // just below that tie + .{ .src = 0x3f808001, .want = 0x3f810000 }, // just above that tie + .{ .src = 0x3f818000, .want = 0x3f820000 }, // odd tie rounds up + .{ .src = 0x3f817fff, .want = 0x3f810000 }, + .{ .src = 0x3f818001, .want = 0x3f820000 }, + .{ .src = 0x00000001, .want = 0x00000000 }, // tiny subnormal -> 0 + .{ .src = 0x00008000, .want = 0x00000000 }, // subnormal tie to even 0 + .{ .src = 0x00008001, .want = 0x00010000 }, // just above, smallest +bf16 subnormal + .{ .src = 0x7f7f0000, .want = 0x7f7f0000 }, // largest finite bf16 + .{ .src = 0x7f7fffff, .want = 0x7f800000 }, // largest finite f32 -> inf + .{ .src = 0x7f800000, .want = 0x7f800000 }, // +inf + .{ .src = 0xff800000, .want = 0xff800000 }, // -inf + .{ .src = 0x7fc00000, .want = 0x7fc00000 }, // qNaN + .{ .src = 0xffc00000, .want = 0xffc00000 }, + }; + for (cases) |c| { + const got: u32 = @bitCast(roundBf16(@bitCast(c.src))); + try std.testing.expectEqual(c.want, got); + } +} + +test "mixF64 matches oracle/kda_inner.py on tiny 16 heads x 2 rows" { + try checkOracle(@embedFile("fixtures/kda_tiny_h16_r2.bin")); +} + +test "mixF64 matches oracle/kda_inner.py on tiny 16 heads x 4 rows" { + try checkOracle(@embedFile("fixtures/kda_tiny_h16_r4.bin")); +} diff --git a/zig/src/families/ling/oracle/kda_inner.py b/zig/src/families/ling/oracle/kda_inner.py new file mode 100644 index 00000000000..08586710383 --- /dev/null +++ b/zig/src/families/ling/oracle/kda_inner.py @@ -0,0 +1,124 @@ +"""Stdlib float64 dump of Ling's KDA mixer (conv through y, r = identity).""" +# Copy of Model.kda after linears, before o_proj. It does not import Model.kda and has no mixer-only entry point. +from __future__ import annotations + +import math +import struct + +MAGIC = b"TFLINGK1" +Q_SCALE = 1.0 / math.sqrt(128.0) + + +def sigmoid(x: float) -> float: + return 1.0 / (1.0 + math.exp(-x)) + + +def kda_inner( + proj, + fgate, + braw, + g2, + conv_q, + conv_k, + conv_v, + A_log, + dt_bias, + o_norm, + heads: int, + dim: int, + taps: int, + lower_bound: float, + eps: float, + rows: int, +): + """proj [rows, 3W] q|k|v, fgate/g2 [rows, W], braw [rows, heads], conv_* [W, taps], y [rows, W].""" + W = heads * dim + windows = [[0.0, 0.0, 0.0] for _ in range(3 * W)] + S = [0.0] * (heads * dim * dim) + y = [0.0] * (rows * W) + q_scale = 1.0 / math.sqrt(dim) + for r in range(rows): + for h in range(heads): + q = [0.0] * dim + k = [0.0] * dim + v = [0.0] * dim + a = [0.0] * dim + rate = math.exp(A_log[h]) + for d in range(dim): + ch_base = h * dim + d + for part, slot, cw in ((0, q, conv_q), (1, k, conv_k), (2, v, conv_v)): + ch = part * W + ch_base + x = proj[r * 3 * W + ch] + w0, w1, w2 = windows[ch] + acc = ( + w0 * cw[ch_base * taps] + + w1 * cw[ch_base * taps + 1] + + w2 * cw[ch_base * taps + 2] + + x * cw[ch_base * taps + 3] + ) + slot[d] = acc * sigmoid(acc) + windows[ch] = [w1, w2, x] + g = fgate[r * W + ch_base] + dt_bias[ch_base] + a[d] = math.exp(lower_bound * sigmoid(rate * g)) + beta = sigmoid(braw[r * heads + h]) + ss_q = sum(t * t for t in q) + ss_k = sum(t * t for t in k) + rq = math.sqrt(ss_q + 1e-6) + rk = math.sqrt(ss_k + 1e-6) + q = [t / rq * q_scale for t in q] + k = [t / rk for t in k] + base = h * dim * dim + o = [0.0] * dim + for j in range(dim): + p = sum(S[base + j * dim + i] * a[i] * k[i] for i in range(dim)) + u = (v[j] - p) * beta + for i in range(dim): + S[base + j * dim + i] = S[base + j * dim + i] * a[i] + k[i] * u + o[j] = sum(S[base + j * dim + i] * q[i] for i in range(dim)) + var_o = sum(t * t for t in o) + rstd = 1.0 / math.sqrt(var_o / dim + eps) + for vi in range(dim): + y[r * W + h * dim + vi] = o[vi] * rstd * o_norm[vi] * sigmoid(g2[r * W + h * dim + vi]) + return y + + +def fill(seed: int, n: int): + out = [] + for _ in range(n): + seed = (seed * 1103515245 + 12345) & 0xFFFFFFFFFFFFFFFF + out.append(float((seed >> 16) & 0x7FFF) / 16384.0 - 1.0) + return seed, out + + +def dump(path: str, heads: int, rows: int, seed: int, lower_bound: float = -5.0, eps: float = 1e-6, dim: int = 128, taps: int = 4): + W = heads * dim + seed, proj = fill(seed, rows * 3 * W) + seed, fgate = fill(seed, rows * W) + seed, braw = fill(seed, rows * heads) + seed, g2 = fill(seed, rows * W) + seed, conv_q = fill(seed, W * taps) + seed, conv_k = fill(seed, W * taps) + seed, conv_v = fill(seed, W * taps) + seed, A_log = fill(seed, heads) + seed, dt_bias = fill(seed, W) + seed, o_norm = fill(seed, dim) + o_norm = [0.5 + 0.5 * v for v in o_norm] + y = kda_inner(proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm, heads, dim, taps, lower_bound, eps, rows) + arrays = (proj, fgate, braw, g2, conv_q, conv_k, conv_v, A_log, dt_bias, o_norm) + with open(path, "wb") as f: + f.write(MAGIC) + f.write(struct.pack("<4I", heads, rows, dim, taps)) + f.write(struct.pack("<2f", lower_bound, eps)) + f.write(struct.pack("