diff --git a/CHANGELOG.md b/CHANGELOG.md index a30ebd92fcb..2125ed694d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](docs/release-notes-1.0.0.md) for the native binary's supported models and migration details. For Desktop installers and changes awaiting a Desktop build, see the [Desktop changelog](app/CHANGELOG.md). ## Unreleased +- CUDA attention: guard stable-max rescale operations and keep warp reductions unconditional (#4520). - Inkling 2 Mini on Metal: split router and gate passes are vectorized and the ungated all-reduce feeds the norm directly, with tokens unchanged; decode is about 1% faster on M3 and M5 Ultra (#5207, refs #5191). Thanks to @gilby. diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 62ea017c46f..9480c4cbde1 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -17,6 +17,9 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { b.step("test-kernel-seed-host", "Named contract fixtures keep their seed when entries are inserted").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module(b, b.graph.host, .debug), .filters = &.{"contract seed:"} })).step); const step = b.step("test-kernel-contract", "The kernel contract's host tests: gate logic, controls, every launch against every chip"); step.dependOn(&run.step); + const cuda_identity = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/cuda_softmax_identity_host.zig"), .target = b.graph.host, .optimize = .debug }) })); + b.step("test-cuda-softmax-identity-host", "CUDA rescale arithmetic, exceptional inputs and convergent warp source guards").dependOn(&cuda_identity.step); + step.dependOn(&cuda_identity.step); const q27_pages = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/q27_paged_cases.zig"), .target = b.graph.host, @@ -310,6 +313,9 @@ pub fn cuda(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build for (names, h3_image) |n, file| if (file) |f| install.dependOn(&b.addInstallFile(f, b.fmt("fatbin/{s}.fatbin", .{n})).step); const run = b.addRunArtifact(runner); run.addArg("kernel-contract"); + const identity = b.addRunArtifact(runner); + identity.addArgs(&.{ "kernel-contract", "attn", "attention", "hpattn", "window", "tree", "mla", "sink", "dflash", "qwen35", "qwen36", "paged", "vision", "prefill", "muse", "hy4", "drama3", "codec" }); + b.step("cuda-softmax-contract", "CUDA softmax families and their byte records").dependOn(&identity.step); b.step("kernel-contract", "Every registered CUDA kernel through the contract's gates on this GPU, each control red").dependOn(&run.step); const prefill_many = b.addRunArtifact(runner); prefill_many.addArg("qmm-prefill-many-contract"); diff --git a/zig/cuda_softmax_identity_host.zig b/zig/cuda_softmax_identity_host.zig new file mode 100644 index 00000000000..6fc50856f29 --- /dev/null +++ b/zig/cuda_softmax_identity_host.zig @@ -0,0 +1,7 @@ +//! Run the CUDA identity arithmetic/source suite with zig/ as its package root. +const std = @import("std"); +const suite = @import("tests/contract/cuda_softmax_identity.zig"); + +test { + std.testing.refAllDecls(suite); +} diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index e94d10265eb..f9dbf2d3146 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -12,18 +12,18 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228", &hash(@embedFile("kernels/cuda/gdn.cu"))); try std.testing.expectEqualStrings("dba5aae94115571ed48933d80f646fff31b2a7da226569867c74a1dc061d2ca2", &hash(@embedFile("kernels/cuda/lane_gemv.cu"))); // #2239 adds head-64 attention for Qwen3-ASR; #3790 reuses it for GLM; existing instances keep their SASS - try std.testing.expectEqualStrings("9d9faedafd8e06afd667839a187118b6b220c794c2948532f0a849f901627a23", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); + try std.testing.expectEqualStrings("776774090e4b189db61d48550b3bac5ade8e8379a3357e1c98aaebadd33c59e9", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); const group = @embedFile("kernels/cuda/qmm_group.cu"); try std.testing.expectEqualStrings("ceff4ee13e97b5aa93cbe7a1edc9a524c78aaa145dd1e5c82dcb05a3011aae23", &hash(group[0..16095])); try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); // #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel. try std.testing.expectEqualStrings("e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); // KIA14 adds all_rows (false keeps selection/arithmetic); #4706 adds TF_QWEN_PDL prologues - try std.testing.expectEqualStrings("79e97b0992f82e891ff8a80cdad68b534e07606b98feef3dffe25101477c99e1", &hash(@embedFile("kernels/cuda/qwen35.cu"))); + try std.testing.expectEqualStrings("e7dd075319e32b706863404302be1033e31cd783bed45db212366ab498b91f32", &hash(@embedFile("kernels/cuda/qwen35.cu"))); // #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh"))); // 67711a6aa7's bytes: the opt-in DSpine draft kernels (#2633); default serving unchanged - try std.testing.expectEqualStrings("df06cb0ef07d12ca2296f7d1691678d0649a148f4abcbb3cb69f0d839e45295c", &hash(@embedFile("kernels/cuda/qwen35_draft.cu"))); + try std.testing.expectEqualStrings("1f1b93181dc01caeaa876eb91396c4e4d048eb623c81ba270a8736459410e562", &hash(@embedFile("kernels/cuda/qwen35_draft.cu"))); try std.testing.expectEqualStrings("403cf841b89ad61da0818bdad8976ed4b286b3282c8c22df7171921b7e06eb6d", &hash(@embedFile("kernels/cuda/qwen35_keep.cu"))); try std.testing.expectEqualStrings("d1a379a98cf7504a7ed3b3f2d24c8ab6a39fe5511bcded6449e598ce5c3c79e7", &hash(@embedFile("kernels/cuda/scan_rows.cu"))); } diff --git a/zig/kernels/cuda/attn_fold.cuh b/zig/kernels/cuda/attn_fold.cuh index bc90875ac4e..f5b365b486d 100644 --- a/zig/kernels/cuda/attn_fold.cuh +++ b/zig/kernels/cuda/attn_fold.cuh @@ -1,5 +1,6 @@ // block_attention.cu's and sparse_attention.cu's fold: 16 mma rows a warp over 32-key tiles, P as bf16 into P x V. #pragma once +#include "common/softmax_identity.cuh" #include #include @@ -83,8 +84,9 @@ struct Fold { tm1 = fmaxf(tm1, __shfl_xor_sync(0xffffffffu, tm1, x)); } const float n0 = fmaxf(m0, tm0), n1 = fmaxf(m1, tm1); - const float a0 = tm0 == -INFINITY ? 1.f : (m0 == -INFINITY ? 0.f : texp(__fsub_rn(m0, n0))); - const float a1 = tm1 == -INFINITY ? 1.f : (m1 == -INFINITY ? 0.f : texp(__fsub_rn(m1, n1))); + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.f : (tm0 == -INFINITY ? 1.f : (m0 == -INFINITY ? 0.f : texp(__fsub_rn(m0, n0)))); + const float a1 = same1 ? 1.f : (tm1 == -INFINITY ? 1.f : (m1 == -INFINITY ? 0.f : texp(__fsub_rn(m1, n1)))); float c0 = 0.f, c1 = 0.f; #pragma unroll for (int n = 0; n < 4; ++n) { @@ -99,16 +101,16 @@ struct Fold { c0 = __fadd_rn(c0, __shfl_xor_sync(0xffffffffu, c0, x)); c1 = __fadd_rn(c1, __shfl_xor_sync(0xffffffffu, c1, x)); } - l0 = __fmaf_rn(l0, a0, c0); - l1 = __fmaf_rn(l1, a1, c1); + l0 = (same0 && isfinite(__fadd_rn(l0, c0))) ? __fadd_rn(l0, c0) : __fmaf_rn(l0, a0, c0); + l1 = (same1 && isfinite(__fadd_rn(l1, c1))) ? __fadd_rn(l1, c1) : __fmaf_rn(l1, a1, c1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < NB; ++i) { - o[i][0] = KEEP ? attn_odd::keep(o[i][0], a0) : __fmul_rn(o[i][0], a0); - o[i][1] = KEEP ? attn_odd::keep(o[i][1], a0) : __fmul_rn(o[i][1], a0); - o[i][2] = KEEP ? attn_odd::keep(o[i][2], a1) : __fmul_rn(o[i][2], a1); - o[i][3] = KEEP ? attn_odd::keep(o[i][3], a1) : __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = KEEP ? attn_odd::keep(o[i][0], a0) : __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = KEEP ? attn_odd::keep(o[i][1], a0) : __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = KEEP ? attn_odd::keep(o[i][2], a1) : __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = KEEP ? attn_odd::keep(o[i][3], a1) : __fmul_rn(o[i][3], a1); } uint32_t pa[2][4]; #pragma unroll diff --git a/zig/kernels/cuda/common/mla.cuh b/zig/kernels/cuda/common/mla.cuh index 2097ea5ab5f..1083d35ad29 100644 --- a/zig/kernels/cuda/common/mla.cuh +++ b/zig/kernels/cuda/common/mla.cuh @@ -1,3 +1,4 @@ +#include "softmax_identity.cuh" // MLA bodies shared by GLM (glm_glue), Hy4-flash and the mla image: chunk tiles over the latent (+ roped columns). #pragma once @@ -152,13 +153,13 @@ __device__ void chunks_wide(const __nv_bfloat16* qa, const __nv_bfloat16* lc, co if ((t & 3) == 0) stat[t / 4] = v; } __syncthreads(); - float alpha[MT][2]; + float alpha[MT][2]; bool same[MT][2]; for (int i = 0; i < MT; ++i) for (int hf = 0; hf < 2; ++hf) { const float tm = stat[i * 16 + hf * 8 + g]; const bool active = tm != -INFINITY; const float nm = active ? fmaxf(m[i][hf], tm) : m[i][hf]; - alpha[i][hf] = active ? (m[i][hf] == -INFINITY ? 0.0f : glm_triton::exp_approx(m[i][hf] - nm)) : 1.0f; + same[i][hf] = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m[i][hf]; alpha[i][hf] = same[i][hf] ? 1.0f : (active ? (m[i][hf] == -INFINITY ? 0.0f : glm_triton::exp_approx(m[i][hf] - nm)) : 1.0f); if (i == hh) { float p[2]; for (int e = 0; e < 2; ++e) { @@ -182,7 +183,7 @@ __device__ void chunks_wide(const __nv_bfloat16* qa, const __nv_bfloat16* lc, co } for (int i = 0; i < MT; ++i) for (int j = 0; j < 8; ++j) - for (int e = 0; e < 4; ++e) o[i][j][e] = __fmul_rn(o[i][j][e], alpha[i][e / 2]); + for (int e = 0; e < 4; ++e) if (!same[i][e / 2] || !isfinite(o[i][j][e])) o[i][j][e] = __fmul_rn(o[i][j][e], alpha[i][e / 2]); #pragma unroll for (int k16 = 0; k16 < KT; k16 += 16) { uint32_t a[MT][4]; @@ -199,7 +200,7 @@ __device__ void chunks_wide(const __nv_bfloat16* qa, const __nv_bfloat16* lc, co } __syncthreads(); for (int i = 0; i < MT; ++i) - for (int hf = 0; hf < 2; ++hf) l[i][hf] = __fmaf_rn(l[i][hf], alpha[i][hf], stat[HB + i * 16 + hf * 8 + g]); + for (int hf = 0; hf < 2; ++hf) l[i][hf] = (same[i][hf] && isfinite(__fadd_rn(l[i][hf], stat[HB + i * 16 + hf * 8 + g]))) ? __fadd_rn(l[i][hf], stat[HB + i * 16 + hf * 8 + g]) : __fmaf_rn(l[i][hf], alpha[i][hf], stat[HB + i * 16 + hf * 8 + g]); if (tile + 2 < tiles) load_kv(tile + 2); commit(); } @@ -240,9 +241,9 @@ __device__ __forceinline__ void merge_part(const float* po, const float* pm, con for (int j = 0; j < 4; ++j) o[j] = __fmaf_rn(b, po[base * LW + k0 + j], 0.0f); l = __fmaf_rn(b, cl, 0.0f); } else { - const float a = active ? (m == -INFINITY ? 0.0f : glm_triton::exp_approx(m - nm)) : 1.0f; - for (int j = 0; j < 4; ++j) o[j] = __fmaf_rn(o[j], a, __fmul_rn(b, po[base * LW + k0 + j])); - l = __fmaf_rn(l, a, __fmul_rn(b, cl)); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m; const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : glm_triton::exp_approx(m - nm)) : 1.0f); + for (int j = 0; j < 4; ++j) o[j] = (same && isfinite(__fadd_rn(o[j], __fmul_rn(b, po[base * LW + k0 + j])))) ? __fadd_rn(o[j], __fmul_rn(b, po[base * LW + k0 + j])) : __fmaf_rn(o[j], a, __fmul_rn(b, po[base * LW + k0 + j])); + l = (same && isfinite(__fadd_rn(l, __fmul_rn(b, cl)))) ? __fadd_rn(l, __fmul_rn(b, cl)) : __fmaf_rn(l, a, __fmul_rn(b, cl)); } m = nm; } @@ -267,10 +268,11 @@ __device__ __forceinline__ void merge_sink(const float* numerator, const float* float acc[4] = {}; for (int i = 0; i < chunks; ++i) { const int64_t base = i * plane + row_head; - const float p = expf(maxima[base] - top); - denom = __fmaf_rn(mass[base], p, denom); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(top) && top == maxima[base]; + const float p = same ? 1.0f : expf(maxima[base] - top); + denom = (same && isfinite(__fadd_rn(mass[base], denom))) ? __fadd_rn(mass[base], denom) : __fmaf_rn(mass[base], p, denom); #pragma unroll - for (int j = 0; j < 4; ++j) acc[j] = __fmaf_rn(numerator[base * latent + column + j], p, acc[j]); + for (int j = 0; j < 4; ++j) acc[j] = (same && isfinite(__fadd_rn(numerator[base * latent + column + j], acc[j]))) ? __fadd_rn(numerator[base * latent + column + j], acc[j]) : __fmaf_rn(numerator[base * latent + column + j], p, acc[j]); } #pragma unroll for (int j = 0; j < 4; ++j) output[row_head * latent + column + j] = __float2bfloat16_rn(acc[j] / denom); diff --git a/zig/kernels/cuda/common/softmax_identity.cuh b/zig/kernels/cuda/common/softmax_identity.cuh new file mode 100644 index 00000000000..b249d689a5c --- /dev/null +++ b/zig/kernels/cuda/common/softmax_identity.cuh @@ -0,0 +1,5 @@ +// Compile-time control for exact finite stable-max rescale shortcuts. +#pragma once +#ifndef TF_CUDA_SOFTMAX_IDENTITY_GUARD +#define TF_CUDA_SOFTMAX_IDENTITY_GUARD 1 +#endif diff --git a/zig/kernels/cuda/drama3_attn.cuh b/zig/kernels/cuda/drama3_attn.cuh index 68c51062eb6..21e5cc9e130 100644 --- a/zig/kernels/cuda/drama3_attn.cuh +++ b/zig/kernels/cuda/drama3_attn.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // drama3 gated full attention (backbone and tower): 16 query heads, 2 KV heads, head dim 256, rotary on 64 dims. #pragma once #include "drama3_common.cuh" @@ -63,16 +64,16 @@ extern "C" __global__ void __launch_bounds__(256) d3_attn_decode(const bf16* __r const float sc = warp_sum(dot8(qv, kv)) * scale; const uint4 vv = reinterpret_cast(vc + ((size_t)p * 2 + g) * 256)[lane]; const float nm = fmaxf(m, sc); - const float corr = expf(m - nm), e = expf(sc - nm); - l = l * corr + e; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m; const float corr = same ? 1.0f : expf(m - nm), e = expf(sc - nm); + l = (same && isfinite(l + e)) ? l + e : l * corr + e; acc[0] = acc[0] * corr + e * lo(vv.x); acc[1] = acc[1] * corr + e * hi(vv.x); - acc[2] = acc[2] * corr + e * lo(vv.y); - acc[3] = acc[3] * corr + e * hi(vv.y); - acc[4] = acc[4] * corr + e * lo(vv.z); - acc[5] = acc[5] * corr + e * hi(vv.z); - acc[6] = acc[6] * corr + e * lo(vv.w); - acc[7] = acc[7] * corr + e * hi(vv.w); + acc[2] = (same && isfinite(acc[2] + e * lo(vv.y))) ? acc[2] + e * lo(vv.y) : acc[2] * corr + e * lo(vv.y); + acc[3] = (same && isfinite(acc[3] + e * hi(vv.y))) ? acc[3] + e * hi(vv.y) : acc[3] * corr + e * hi(vv.y); + acc[4] = (same && isfinite(acc[4] + e * lo(vv.z))) ? acc[4] + e * lo(vv.z) : acc[4] * corr + e * lo(vv.z); + acc[5] = (same && isfinite(acc[5] + e * hi(vv.z))) ? acc[5] + e * hi(vv.z) : acc[5] * corr + e * hi(vv.z); + acc[6] = (same && isfinite(acc[6] + e * lo(vv.w))) ? acc[6] + e * lo(vv.w) : acc[6] * corr + e * lo(vv.w); + acc[7] = (same && isfinite(acc[7] + e * hi(vv.w))) ? acc[7] + e * hi(vv.w) : acc[7] * corr + e * hi(vv.w); m = nm; } __shared__ float sm[8], sl[8], sacc[8][256]; @@ -91,9 +92,9 @@ extern "C" __global__ void __launch_bounds__(256) d3_attn_decode(const bf16* __r #pragma unroll for (int k = 0; k < 8; ++k) { if (sm[k] == -INFINITY) continue; - const float c = expf(sm[k] - M); - Lsum += sl[k] * c; - A += sacc[k][i] * c; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(M) && M == sm[k]; const float c = same ? 1.0f : expf(sm[k] - M); + Lsum = (same && isfinite(Lsum + sl[k])) ? Lsum + sl[k] : Lsum + sl[k] * c; + A = (same && isfinite(A + sacc[k][i])) ? A + sacc[k][i] : A + sacc[k][i] * c; } const float a = rb(A / Lsum); const float gt = b2f(proj[(size_t)t * ps + gate_off + h * gate_head_stride + i]); @@ -123,16 +124,16 @@ extern "C" __global__ void __launch_bounds__(256) d3_attn_partial(const bf16* __ const uint4 vv = reinterpret_cast(vc + ((size_t)p * 2 + g) * 256)[lane]; const float sc = warp_sum(dot8(qv, kv)) * 0.0625f; const float nm = fmaxf(m, sc); - const float corr = expf(m - nm), e = expf(sc - nm); - l = l * corr + e; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m; const float corr = same ? 1.0f : expf(m - nm), e = expf(sc - nm); + l = (same && isfinite(l + e)) ? l + e : l * corr + e; acc[0] = acc[0] * corr + e * lo(vv.x); acc[1] = acc[1] * corr + e * hi(vv.x); - acc[2] = acc[2] * corr + e * lo(vv.y); - acc[3] = acc[3] * corr + e * hi(vv.y); - acc[4] = acc[4] * corr + e * lo(vv.z); - acc[5] = acc[5] * corr + e * hi(vv.z); - acc[6] = acc[6] * corr + e * lo(vv.w); - acc[7] = acc[7] * corr + e * hi(vv.w); + acc[2] = (same && isfinite(acc[2] + e * lo(vv.y))) ? acc[2] + e * lo(vv.y) : acc[2] * corr + e * lo(vv.y); + acc[3] = (same && isfinite(acc[3] + e * hi(vv.y))) ? acc[3] + e * hi(vv.y) : acc[3] * corr + e * hi(vv.y); + acc[4] = (same && isfinite(acc[4] + e * lo(vv.z))) ? acc[4] + e * lo(vv.z) : acc[4] * corr + e * lo(vv.z); + acc[5] = (same && isfinite(acc[5] + e * hi(vv.z))) ? acc[5] + e * hi(vv.z) : acc[5] * corr + e * hi(vv.z); + acc[6] = (same && isfinite(acc[6] + e * lo(vv.w))) ? acc[6] + e * lo(vv.w) : acc[6] * corr + e * lo(vv.w); + acc[7] = (same && isfinite(acc[7] + e * hi(vv.w))) ? acc[7] + e * hi(vv.w) : acc[7] * corr + e * hi(vv.w); m = nm; } __shared__ float sm[8], sl[8], sacc[8][256]; @@ -151,9 +152,9 @@ extern "C" __global__ void __launch_bounds__(256) d3_attn_partial(const bf16* __ #pragma unroll for (int k = 0; k < 8; ++k) { if (sm[k] == -INFINITY) continue; - const float c = expf(sm[k] - M); - Ls += sl[k] * c; - A += sacc[k][i] * c; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(M) && M == sm[k]; const float c = same ? 1.0f : expf(sm[k] - M); + Ls = (same && isfinite(Ls + sl[k])) ? Ls + sl[k] : Ls + sl[k] * c; + A = (same && isfinite(A + sacc[k][i])) ? A + sacc[k][i] : A + sacc[k][i] * c; } const size_t slot = ((size_t)t * 16 + h) * S + sp; pacc[slot * 256 + i] = A; @@ -175,9 +176,9 @@ extern "C" __global__ void d3_attn_merge(const float* __restrict__ pml, const fl for (int k = 0; k < S; ++k) { const float mk = pml[(base + k) * 2]; if (mk == -INFINITY) continue; - const float c = expf(mk - M); - Ls += pml[(base + k) * 2 + 1] * c; - A += pacc[(base + k) * 256 + i] * c; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(M) && M == mk; const float c = same ? 1.0f : expf(mk - M); + Ls = (same && isfinite(Ls + pml[(base + k) * 2 + 1])) ? Ls + pml[(base + k) * 2 + 1] : Ls + pml[(base + k) * 2 + 1] * c; + A = (same && isfinite(A + pacc[(base + k) * 256 + i])) ? A + pacc[(base + k) * 256 + i] : A + pacc[(base + k) * 256 + i] * c; } const float a = rb(A / Ls); const float gt = b2f(proj[(size_t)t * ps + gate_off + h * gate_head_stride + i]); diff --git a/zig/kernels/cuda/drama3_codec.cu b/zig/kernels/cuda/drama3_codec.cu index 0b4c15a0571..1dcd363bf4d 100644 --- a/zig/kernels/cuda/drama3_codec.cu +++ b/zig/kernels/cuda/drama3_codec.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // ours: drama3's codec (Fish S2 modded DAC) in fp32: the glue between cuBLAS SGEMMs, time-major [rows, channels]. #include #include @@ -166,8 +167,8 @@ extern "C" __global__ void c_attn(const float* __restrict__ qkv, const float* __ const size_t r = (size_t)(p % ring) * 1024 + h * 64 + 2 * lane; const float sc = warp_sum(q0 * kc[r] + q1 * kc[r + 1]); const float nm = fmaxf(m, sc); - const float corr = expf(m - nm), e = expf(sc - nm); - l = l * corr + e; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m; const float corr = same ? 1.0f : expf(m - nm), e = expf(sc - nm); + l = (same && isfinite(l + e)) ? l + e : l * corr + e; a0 = a0 * corr + e * vc[r]; a1 = a1 * corr + e * vc[r + 1]; m = nm; diff --git a/zig/kernels/cuda/flashnext_attn.cu b/zig/kernels/cuda/flashnext_attn.cu index 3d9f7bb7f79..4a30c946a89 100644 --- a/zig/kernels/cuda/flashnext_attn.cu +++ b/zig/kernels/cuda/flashnext_attn.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Flash Next's attention glue and its sparse indexer's pooling and scores: each row's own fixed-order sums. // glue.py and attention.py's arithmetic and bf16 rounding points; the attention dots on mma tiles, K ascending. @@ -365,14 +366,14 @@ __device__ __forceinline__ void attn_chunks(const __nv_bfloat16* __restrict__ Q, if (t == 0) red_m[warp][g + 8 * h] = tile_m[h]; } __syncthreads(); - float next_m[2], alpha[2], rows[2]; + float next_m[2], alpha[2], rows[2]; bool same[2]; #pragma unroll for (int h = 0; h < 2; ++h) { const int row = g + 8 * h; const float tm = fmaxf(fmaxf(red_m[0][row], red_m[1][row]), fmaxf(red_m[2][row], red_m[3][row])); const bool active = tm != -INFINITY; next_m[h] = active ? fmaxf(m[h], tm) : m[h]; - alpha[h] = active ? (m[h] == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m[h], next_m[h]))) : 1.0f; + same[h] = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next_m[h]) && next_m[h] == m[h]; alpha[h] = same[h] ? 1.0f : (active ? (m[h] == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m[h], next_m[h]))) : 1.0f); rows[h] = 0.0f; } #pragma unroll @@ -396,13 +397,13 @@ __device__ __forceinline__ void attn_chunks(const __nv_bfloat16* __restrict__ Q, for (int h = 0; h < 2; ++h) { const int row = g + 8 * h; const float sum = __fadd_rn(__fadd_rn(__fadd_rn(red_l[0][row], red_l[1][row]), red_l[2][row]), red_l[3][row]); - l[h] = __fmaf_rn(l[h], alpha[h], sum); + l[h] = (same[h] && isfinite(__fadd_rn(l[h], sum))) ? __fadd_rn(l[h], sum) : __fmaf_rn(l[h], alpha[h], sum); m[h] = next_m[h]; } #pragma unroll for (int q = 0; q < 8; ++q) #pragma unroll - for (int e = 0; e < 4; ++e) o[q][e] = __fmul_rn(o[q][e], alpha[e >> 1]); + for (int e = 0; e < 4; ++e) if (!same[e >> 1] || !isfinite(o[q][e])) o[q][e] = __fmul_rn(o[q][e], alpha[e >> 1]); for (int ks = 0; ks < TK / 16; ++ks) { uint32_t a[4]; qmm_frag::ldmatrix4(a, &ps[lane % 16][ks * 16 + (lane / 16) * 8]); @@ -421,13 +422,13 @@ __device__ __forceinline__ void attn_chunks(const __nv_bfloat16* __restrict__ Q, for (int h = 0; h < 2; ++h) { const bool active = l[h] > 0.0f; const float next = active ? fmaxf(mm[h], m[h]) : mm[h]; - const float a = active ? (mm[h] == -INFINITY ? 0.0f : tf_exp(__fsub_rn(mm[h], next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == mm[h]; const float a = same ? 1.0f : (active ? (mm[h] == -INFINITY ? 0.0f : tf_exp(__fsub_rn(mm[h], next))) : 1.0f); const float bb = active ? tf_exp(__fsub_rn(m[h], next)) : 0.0f; #pragma unroll for (int q = 0; q < 8; ++q) #pragma unroll - for (int e = 0; e < 2; ++e) oo[FUSE ? q : 0][2 * h + e] = __fmaf_rn(o[q][2 * h + e], bb, __fmul_rn(oo[FUSE ? q : 0][2 * h + e], a)); - ll[h] = __fmaf_rn(l[h], bb, __fmul_rn(ll[h], a)); + for (int e = 0; e < 2; ++e) oo[FUSE ? q : 0][2 * h + e] = (same && isfinite(__fmaf_rn(o[q][2 * h + e], bb, oo[FUSE ? q : 0][2 * h + e]))) ? __fmaf_rn(o[q][2 * h + e], bb, oo[FUSE ? q : 0][2 * h + e]) : __fmaf_rn(o[q][2 * h + e], bb, __fmul_rn(oo[FUSE ? q : 0][2 * h + e], a)); + ll[h] = (same && isfinite(__fmaf_rn(l[h], bb, ll[h]))) ? __fmaf_rn(l[h], bb, ll[h]) : __fmaf_rn(l[h], bb, __fmul_rn(ll[h], a)); mm[h] = next; } continue; @@ -549,10 +550,10 @@ __device__ __forceinline__ void fn_attn_merge_body(const float* __restrict__ PO, const float cm = PM[base], cl = PL[base], co = PO[base * HD + d]; const bool active = cl > 0.0f; const float next = active ? fmaxf(m, cm) : m; - const float a = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); const float b = active ? tf_exp(__fsub_rn(cm, next)) : 0.0f; - o = __fmaf_rn(co, b, __fmul_rn(o, a)); - l = __fmaf_rn(cl, b, __fmul_rn(l, a)); + o = (same && isfinite(__fmaf_rn(co, b, o))) ? __fmaf_rn(co, b, o) : __fmaf_rn(co, b, __fmul_rn(o, a)); + l = (same && isfinite(__fmaf_rn(cl, b, l))) ? __fmaf_rn(cl, b, l) : __fmaf_rn(cl, b, __fmul_rn(l, a)); m = next; } OUT[(static_cast(r) * H + head) * HD + d] = __float2bfloat16_rn(__fdiv_rn(o, l)); diff --git a/zig/kernels/cuda/glm_dflash.cu b/zig/kernels/cuda/glm_dflash.cu index 3d06def9e28..7f2f208e2c4 100644 --- a/zig/kernels/cuda/glm_dflash.cu +++ b/zig/kernels/cuda/glm_dflash.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // DFlash2 drafter kernels (ours, after z-lab/dflash, MIT): taps, norms+rope, convs, SwiGLU, ring and block attention. #include @@ -169,8 +170,8 @@ extern "C" __global__ void __launch_bounds__(256) df_attn(const __nv_bfloat16* q float d = qv[h][0] * kf[0] + qv[h][1] * kf[1] + qv[h][2] * kf[2] + qv[h][3] * kf[3]; for (int off = 16; off > 0; off >>= 1) d += __shfl_xor_sync(0xffffffffu, d, off); const float mn = fmaxf(m[h], d); - const float corr = __expf(m[h] - mn), pe = __expf(d - mn); - l[h] = l[h] * corr + pe; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m[h]; const float corr = same ? 1.0f : __expf(m[h] - mn), pe = __expf(d - mn); + l[h] = (same && isfinite(l[h] + pe)) ? l[h] + pe : l[h] * corr + pe; for (int i = 0; i < 4; ++i) acc[h][i] = acc[h][i] * corr + pe * vf[i]; m[h] = mn; } @@ -228,8 +229,8 @@ extern "C" __global__ void __launch_bounds__(256) df_attn_part(const __nv_bfloat float d = qv[h][0] * kf[0] + qv[h][1] * kf[1] + qv[h][2] * kf[2] + qv[h][3] * kf[3]; for (int off = 16; off > 0; off >>= 1) d += __shfl_xor_sync(0xffffffffu, d, off); const float mn = fmaxf(m[h], d); - const float corr = __expf(m[h] - mn), pe = __expf(d - mn); - l[h] = l[h] * corr + pe; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m[h]; const float corr = same ? 1.0f : __expf(m[h] - mn), pe = __expf(d - mn); + l[h] = (same && isfinite(l[h] + pe)) ? l[h] + pe : l[h] * corr + pe; for (int i = 0; i < 4; ++i) acc[h][i] = acc[h][i] * corr + pe * vf[i]; m[h] = mn; } @@ -255,9 +256,9 @@ extern "C" __global__ void df_attn_merge(const float* __restrict__ pm, const flo for (int c = 0; c < CH; ++c) m = fmaxf(m, pm[base + c]); float l = 0.f, a = 0.f; for (int c = 0; c < CH; ++c) { - const float w = __expf(pm[base + c] - m); - l += pl[base + c] * w; - a += pacc[(base + c) * HD + d] * w; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(m) && m == pm[base + c]; const float w = same ? 1.0f : __expf(pm[base + c] - m); + l = (same && isfinite(l + pl[base + c])) ? l + pl[base + c] : l + pl[base + c] * w; + a = (same && isfinite(a + pacc[(base + c) * HD + d])) ? a + pacc[(base + c) * HD + d] : a + pacc[(base + c) * HD + d] * w; } o[(long long)r * QH * HD + h * HD + d] = tobf(a / l); } diff --git a/zig/kernels/cuda/glm_glue_attn.cuh b/zig/kernels/cuda/glm_glue_attn.cuh index 48433be8a41..ddfefe72998 100644 --- a/zig/kernels/cuda/glm_glue_attn.cuh +++ b/zig/kernels/cuda/glm_glue_attn.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // latent.py's MLA attention and sparse.py's index scores by hand: the chunk kernels' online softmax, the chunk merge. #pragma once @@ -63,9 +64,9 @@ extern "C" __global__ void __launch_bounds__(128) for (int j = 0; j < 4; ++j) o[j] = __fmaf_rn(b, po[base * LW + k0 + j], 0.0f); l = __fmaf_rn(b, cl, 0.0f); } else { - const float a = active ? (m == -INFINITY ? 0.0f : glm_triton::exp_approx(m - nm)) : 1.0f; - for (int j = 0; j < 4; ++j) o[j] = __fmaf_rn(o[j], a, __fmul_rn(b, po[base * LW + k0 + j])); - l = __fmaf_rn(l, a, __fmul_rn(b, cl)); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(nm) && nm == m; const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : glm_triton::exp_approx(m - nm)) : 1.0f); + for (int j = 0; j < 4; ++j) o[j] = (same && isfinite(__fadd_rn(o[j], __fmul_rn(b, po[base * LW + k0 + j])))) ? __fadd_rn(o[j], __fmul_rn(b, po[base * LW + k0 + j])) : __fmaf_rn(o[j], a, __fmul_rn(b, po[base * LW + k0 + j])); + l = (same && isfinite(__fadd_rn(l, __fmul_rn(b, cl)))) ? __fadd_rn(l, __fmul_rn(b, cl)) : __fmaf_rn(l, a, __fmul_rn(b, cl)); } m = nm; } diff --git a/zig/kernels/cuda/h3_attention.cuh b/zig/kernels/cuda/h3_attention.cuh index 6a9466917c4..7f92e52d2f6 100644 --- a/zig/kernels/cuda/h3_attention.cuh +++ b/zig/kernels/cuda/h3_attention.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // MiniMax H3's tile-routed attention in bf16 on mma.sync m16n8k16: fp32 scores, an fp32 online softmax, fp32 sums. #pragma once #include @@ -112,7 +113,7 @@ __device__ __forceinline__ void attention_body( m1 = fmaxf(m1, __shfl_xor_sync(0xffffffffu, m1, 1)); m1 = fmaxf(m1, __shfl_xor_sync(0xffffffffu, m1, 2)); const float n0 = fmaxf(top0, m0), n1 = fmaxf(top1, m1); - const float f0 = exp2f(top0 - n0), f1 = exp2f(top1 - n1); + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == top0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == top1; const float f0 = same0 ? 1.0f : exp2f(top0 - n0), f1 = same1 ? 1.0f : exp2f(top1 - n1); // the weights in fp32 for the softmax's mass, rounded to bf16 as the value product's A operand float l0 = 0.0f, l1 = 0.0f; uint32_t pa[4][4]; @@ -129,16 +130,16 @@ __device__ __forceinline__ void attention_body( l0 += __shfl_xor_sync(0xffffffffu, l0, 2); l1 += __shfl_xor_sync(0xffffffffu, l1, 1); l1 += __shfl_xor_sync(0xffffffffu, l1, 2); - mass0 = mass0 * f0 + l0; - mass1 = mass1 * f1 + l1; + mass0 = (same0 && isfinite(mass0 + l0)) ? mass0 + l0 : mass0 * f0 + l0; + mass1 = (same1 && isfinite(mass1 + l1)) ? mass1 + l1 : mass1 * f1 + l1; top0 = n0; top1 = n1; #pragma unroll for (int j = 0; j < 16; ++j) { - out[j][0] *= f0; - out[j][1] *= f0; - out[j][2] *= f1; - out[j][3] *= f1; + if (!same0 || !isfinite(out[j][0])) out[j][0] *= f0; + if (!same0 || !isfinite(out[j][1])) out[j][1] *= f0; + if (!same1 || !isfinite(out[j][2])) out[j][2] *= f1; + if (!same1 || !isfinite(out[j][3])) out[j][3] *= f1; } wait<1>(); __syncthreads(); diff --git a/zig/kernels/cuda/hy4_flash/attention_sink.cu b/zig/kernels/cuda/hy4_flash/attention_sink.cu index 2b8d1d106b1..cbb0bc0821c 100644 --- a/zig/kernels/cuda/hy4_flash/attention_sink.cu +++ b/zig/kernels/cuda/hy4_flash/attention_sink.cu @@ -1,3 +1,4 @@ +#include "../common/softmax_identity.cuh" // Finish a head's online softmax with its learned, zero-value sink. extern "C" __global__ void tf_hy4_finish_attention( const float *maxima, @@ -14,8 +15,8 @@ extern "C" __global__ void tf_hy4_finish_attention( const float sink = sinks[row_head % heads]; const float top = fmaxf(maxima[row_head], sink); - const float prior = expf(maxima[row_head] - top); - const float denominator = mass[row_head] * prior + expf(sink - top); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(top) && top == maxima[row_head]; const float prior = same ? 1.0f : expf(maxima[row_head] - top); + const float denominator = (same && isfinite(mass[row_head] + expf(sink - top))) ? mass[row_head] + expf(sink - top) : mass[row_head] * prior + expf(sink - top); const unsigned long long offset = static_cast(row_head) * width + column; - output[offset] = numerator[offset] * prior / denominator; + output[offset] = ((same && isfinite(numerator[offset])) ? numerator[offset] : numerator[offset] * prior) / denominator; } diff --git a/zig/kernels/cuda/idol_attention.cuh b/zig/kernels/cuda/idol_attention.cuh index 48965457360..a3da2e60c1e 100644 --- a/zig/kernels/cuda/idol_attention.cuh +++ b/zig/kernels/cuda/idol_attention.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Idol's attention: vision_kernel's row arithmetic over fp16 q, k, v and P (fp32 scores, softmax, sums), its own copy. #pragma once @@ -135,8 +136,9 @@ __device__ __forceinline__ void full(const __half* __restrict__ qkv, __half* __r } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0[NT], c1[NT]; #pragma unroll for (int n = 0; n < NT; ++n) { @@ -148,16 +150,17 @@ __device__ __forceinline__ void full(const __half* __restrict__ qkv, __half* __r c0[n] = __fadd_rn(sc[n][0], sc[n][1]); c1[n] = __fadd_rn(sc[n][2], sc[n][3]); } - l0 = __fmaf_rn(l0, a0, rowsum(c0)); - l1 = __fmaf_rn(l1, a1, rowsum(c1)); + const float sum0 = rowsum(c0), sum1 = rowsum(c1); + l0 = (same0 && isfinite(__fadd_rn(l0, sum0))) ? __fadd_rn(l0, sum0) : __fmaf_rn(l0, a0, sum0); + l1 = (same1 && isfinite(__fadd_rn(l1, sum1))) ? __fadd_rn(l1, sum1) : __fmaf_rn(l1, a1, sum1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < C; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } #pragma unroll for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile diff --git a/zig/kernels/cuda/idol_decoder_attention.cuh b/zig/kernels/cuda/idol_decoder_attention.cuh index 68ddf8de2da..812bbff995b 100644 --- a/zig/kernels/cuda/idol_decoder_attention.cuh +++ b/zig/kernels/cuda/idol_decoder_attention.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // The decoders' tiled attention: full's row arithmetic (P to nearest fp16 for P V), queries to other keys. #pragma once @@ -94,8 +95,9 @@ __device__ __forceinline__ void rows(const __half* __restrict__ qp, int qs, cons } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0[NT], c1[NT]; #pragma unroll for (int n = 0; n < NT; ++n) { @@ -107,16 +109,17 @@ __device__ __forceinline__ void rows(const __half* __restrict__ qp, int qs, cons c0[n] = __fadd_rn(sc[n][0], sc[n][1]); c1[n] = __fadd_rn(sc[n][2], sc[n][3]); } - l0 = __fmaf_rn(l0, a0, rowsum(c0)); - l1 = __fmaf_rn(l1, a1, rowsum(c1)); + const float sum0 = rowsum(c0), sum1 = rowsum(c1); + l0 = (same0 && isfinite(__fadd_rn(l0, sum0))) ? __fadd_rn(l0, sum0) : __fmaf_rn(l0, a0, sum0); + l1 = (same1 && isfinite(__fadd_rn(l1, sum1))) ? __fadd_rn(l1, sum1) : __fmaf_rn(l1, a1, sum1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < C; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } #pragma unroll for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile diff --git a/zig/kernels/cuda/inkling2/attention.cu b/zig/kernels/cuda/inkling2/attention.cu index 7ad9a174790..5606766b2dc 100644 --- a/zig/kernels/cuda/inkling2/attention.cu +++ b/zig/kernels/cuda/inkling2/attention.cu @@ -1,3 +1,4 @@ +#include "../common/softmax_identity.cuh" // Inkling 2 attention: q/k/v/rel preparation, the relative-bias table, chunked tensor-core attention and the merge. #include #include @@ -129,9 +130,9 @@ constexpr int kSub = 1024; // A part (m, l) into a running (mm, ll); a, b scale old and new sums (explicit roundings: both kernels fold alike). __device__ __forceinline__ void fold(float& mm, float& ll, float m, float l, float& a, float& b) { const float mn = fmaxf(mm, m); - a = exp2f(mm - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mm; a = same ? 1.0f : exp2f(mm - mn); b = exp2f(m - mn); - ll = __fadd_rn(__fmul_rn(ll, a), __fmul_rn(l, b)); + ll = (same && isfinite(__fadd_rn(ll, __fmul_rn(l, b)))) ? __fadd_rn(ll, __fmul_rn(l, b)) : __fadd_rn(__fmul_rn(ll, a), __fmul_rn(l, b)); mm = mn; } @@ -241,15 +242,15 @@ __device__ __forceinline__ void attnTile(const uint16_t* __restrict__ q, const u mx[i] = fmaxf(mx[i], sc[j][e]); } } - float alpha[2], mu[2]; + float alpha[2], mu[2]; bool same[2]; for (int i = 0; i < 2; ++i) { mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffffu, mx[i], 1)); mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffffu, mx[i], 2)); const float mn = fmaxf(m[i], mx[i]); mu[i] = mn == -INFINITY ? 0.0f : mn; - alpha[i] = exp2f(m[i] - mu[i]); + same[i] = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mu[i]) && mu[i] == m[i]; alpha[i] = same[i] ? 1.0f : exp2f(m[i] - mu[i]); m[i] = mn; - l[i] *= alpha[i]; + if (!same[i] || !isfinite(l[i])) l[i] *= alpha[i]; } uint16_t p[8][4]; for (int j = 0; j < 8; ++j) { @@ -260,10 +261,10 @@ __device__ __forceinline__ void attnTile(const uint16_t* __restrict__ q, const u } } for (int n = 0; n < 16; ++n) { - acc[n][0] *= alpha[0]; - acc[n][1] *= alpha[0]; - acc[n][2] *= alpha[1]; - acc[n][3] *= alpha[1]; + if (!same[0] || !isfinite(acc[n][0])) acc[n][0] *= alpha[0]; + if (!same[0] || !isfinite(acc[n][1])) acc[n][1] *= alpha[0]; + if (!same[1] || !isfinite(acc[n][2])) acc[n][2] *= alpha[1]; + if (!same[1] || !isfinite(acc[n][3])) acc[n][3] *= alpha[1]; } for (int u = 0; u < 4; ++u) { const uint32_t a0 = pack(p[2 * u][0], p[2 * u][1]), a1 = pack(p[2 * u][2], p[2 * u][3]); @@ -286,10 +287,10 @@ __device__ __forceinline__ void attnTile(const uint16_t* __restrict__ q, const u for (int i = 0; i < 2; ++i) { if (!ok[i] || s_lo > pos[i]) continue; // the merge folds a row's sub-chunks up to its own float a, b; - fold(M[i], L[i], m[i], l[i], a, b); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(fmaxf(M[i], m[i])) && fmaxf(M[i], m[i]) == M[i]; fold(M[i], L[i], m[i], l[i], a, b); for (int n = 0; n < 16; ++n) { - O[n][2 * i] = scaled(O[n][2 * i], a, acc[n][2 * i], b); - O[n][2 * i + 1] = scaled(O[n][2 * i + 1], a, acc[n][2 * i + 1], b); + O[n][2 * i] = (same && isfinite(__fadd_rn(O[n][2 * i], __fmul_rn(acc[n][2 * i], b)))) ? __fadd_rn(O[n][2 * i], __fmul_rn(acc[n][2 * i], b)) : scaled(O[n][2 * i], a, acc[n][2 * i], b); + O[n][2 * i + 1] = (same && isfinite(__fadd_rn(O[n][2 * i + 1], __fmul_rn(acc[n][2 * i + 1], b)))) ? __fadd_rn(O[n][2 * i + 1], __fmul_rn(acc[n][2 * i + 1], b)) : scaled(O[n][2 * i + 1], a, acc[n][2 * i + 1], b); } } } @@ -358,8 +359,8 @@ extern "C" __global__ void tf_ink2_merge(const float* __restrict__ part_o, const const size_t at = rh * chunks + (c - c0) * subs + u; const float2 sm = part_ml[at]; float a, b; - fold(M, L, sm.x, sm.y, a, b); - O = scaled(O, a, part_o[at * kDim + d], b); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(fmaxf(M, sm.x)) && fmaxf(M, sm.x) == M; fold(M, L, sm.x, sm.y, a, b); + O = (same && isfinite(__fadd_rn(O, __fmul_rn(part_o[at * kDim + d], b)))) ? __fadd_rn(O, __fmul_rn(part_o[at * kDim + d], b)) : scaled(O, a, part_o[at * kDim + d], b); } ml = make_float2(M, L); po = O; @@ -369,15 +370,15 @@ extern "C" __global__ void tf_ink2_merge(const float* __restrict__ part_o, const po = part_o[at * kDim + d]; } const float mn = fmaxf(mm, ml.x); - const float a = exp2f(mm - mn), b = exp2f(ml.x - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mm; const float a = same ? 1.0f : exp2f(mm - mn), b = exp2f(ml.x - mn); ll = ll * a + ml.y * b; o = o * a + po * b; mm = mn; } const float sk = bf(sink[rh]) * kLog2e; const float mf = fmaxf(mm, sk); - const float a = exp2f(mm - mf); - const float y = o * a / (ll * a + exp2f(sk - mf)); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mf) && mf == mm; const float a = same ? 1.0f : exp2f(mm - mf); + const float y = ((same && isfinite(o)) ? o : o * a) / ((same && isfinite(ll + exp2f(sk - mf))) ? ll + exp2f(sk - mf) : ll * a + exp2f(sk - mf)); const float gv = bf(gate[rh * kDim + d]); out[rh * kDim + d] = tobf(y * (1.0f / (1.0f + expf(-gv)))); } diff --git a/zig/kernels/cuda/inkling2/prompt_attention.cu b/zig/kernels/cuda/inkling2/prompt_attention.cu index 97a03657dad..4a2a373364d 100644 --- a/zig/kernels/cuda/inkling2/prompt_attention.cu +++ b/zig/kernels/cuda/inkling2/prompt_attention.cu @@ -1,3 +1,4 @@ +#include "../common/softmax_identity.cuh" // Inkling 2 global-layer prompt attention: 128 (row, head) pairs share each K/V tile, with the split path's bits. #include #include @@ -36,9 +37,9 @@ __device__ __forceinline__ uint32_t pack(uint16_t lo, uint16_t hi) { __device__ __forceinline__ void fold(float& mm, float& ll, float m, float l, float& a, float& b) { const float mn = fmaxf(mm, m); - a = exp2f(mm - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mm; a = same ? 1.0f : exp2f(mm - mn); b = exp2f(m - mn); - ll = __fadd_rn(__fmul_rn(ll, a), __fmul_rn(l, b)); + ll = (same && isfinite(__fadd_rn(ll, __fmul_rn(l, b)))) ? __fadd_rn(ll, __fmul_rn(l, b)) : __fadd_rn(__fmul_rn(ll, a), __fmul_rn(l, b)); mm = mn; } @@ -174,15 +175,15 @@ __device__ __forceinline__ void promptTile(const uint16_t* __restrict__ q, const } } } - float alpha[2], mu[2]; + float alpha[2], mu[2]; bool same[2]; for (int i = 0; i < 2; ++i) { mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffffu, mx[i], 1)); mx[i] = fmaxf(mx[i], __shfl_xor_sync(0xffffffffu, mx[i], 2)); const float mn = fmaxf(m[i], mx[i]); mu[i] = mn == -INFINITY ? 0.0f : mn; - alpha[i] = exp2f(m[i] - mu[i]); + same[i] = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mu[i]) && mu[i] == m[i]; alpha[i] = same[i] ? 1.0f : exp2f(m[i] - mu[i]); m[i] = mn; - l[i] *= alpha[i]; + if (!same[i] || !isfinite(l[i])) l[i] *= alpha[i]; } uint32_t pk[8][2]; // P as the A fragments: pk[j][i] packs keys 8j+2t, +1 of row g + 8i for (int j = 0; j < 8; ++j) { @@ -196,10 +197,10 @@ __device__ __forceinline__ void promptTile(const uint16_t* __restrict__ q, const pk[j][1] = pack(p[2], p[3]); } for (int n = 0; n < 16; ++n) { - acc[n][0] *= alpha[0]; - acc[n][1] *= alpha[0]; - acc[n][2] *= alpha[1]; - acc[n][3] *= alpha[1]; + if (!same[0] || !isfinite(acc[n][0])) acc[n][0] *= alpha[0]; + if (!same[0] || !isfinite(acc[n][1])) acc[n][1] *= alpha[0]; + if (!same[1] || !isfinite(acc[n][2])) acc[n][2] *= alpha[1]; + if (!same[1] || !isfinite(acc[n][3])) acc[n][3] *= alpha[1]; } for (int u = 0; u < 4; ++u) { const uint32_t a0 = pk[2 * u][0], a1 = pk[2 * u][1], a2 = pk[2 * u + 1][0], a3 = pk[2 * u + 1][1]; @@ -219,10 +220,10 @@ __device__ __forceinline__ void promptTile(const uint16_t* __restrict__ q, const for (int i = 0; i < 2; ++i) { if (!ok[i] || s_lo > pos[i]) continue; // the merge folds a row's sub-chunks up to its own float a, b; - fold(M[i], L[i], m[i], l[i], a, b); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(fmaxf(M[i], m[i])) && fmaxf(M[i], m[i]) == M[i]; fold(M[i], L[i], m[i], l[i], a, b); for (int n = 0; n < 16; ++n) { - O[n][2 * i] = scaled(O[n][2 * i], a, acc[n][2 * i], b); - O[n][2 * i + 1] = scaled(O[n][2 * i + 1], a, acc[n][2 * i + 1], b); + O[n][2 * i] = (same && isfinite(__fadd_rn(O[n][2 * i], __fmul_rn(acc[n][2 * i], b)))) ? __fadd_rn(O[n][2 * i], __fmul_rn(acc[n][2 * i], b)) : scaled(O[n][2 * i], a, acc[n][2 * i], b); + O[n][2 * i + 1] = (same && isfinite(__fadd_rn(O[n][2 * i + 1], __fmul_rn(acc[n][2 * i + 1], b)))) ? __fadd_rn(O[n][2 * i + 1], __fmul_rn(acc[n][2 * i + 1], b)) : scaled(O[n][2 * i + 1], a, acc[n][2 * i + 1], b); } } } diff --git a/zig/kernels/cuda/minimax_m3_attn.cu b/zig/kernels/cuda/minimax_m3_attn.cu index 2b8e4e047c5..41cb2377dcc 100644 --- a/zig/kernels/cuda/minimax_m3_attn.cu +++ b/zig/kernels/cuda/minimax_m3_attn.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // MiniMax-M3.1-Flash's block-sparse attention on CUDA: the lightning indexer's scores and picks, decode and prompts. #include "minimax_m3.cuh" @@ -157,6 +158,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_mm3_attn_prompt_tc( mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffffu, mx1, off)); } // masked keys add 0 and an unmoved max rescales by 1 (no -inf - -inf); a NaN score still gives NaN + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mx0) && m0 == mx0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mx1) && m1 == mx1; const float f0 = m0 == mx0 ? 1.f : exp2f(m0 - mx0), f1 = m1 == mx1 ? 1.f : exp2f(m1 - mx1); m0 = mx0; m1 = mx1; @@ -170,14 +172,14 @@ extern "C" __global__ void __launch_bounds__(256) tf_mm3_attn_prompt_tc( s0 += sc[j][e]; s1 += sc[j][2 + e]; } - l0 = l0 * f0 + s0; - l1 = l1 * f1 + s1; + l0 = (same0 && isfinite(l0 + s0)) ? l0 + s0 : l0 * f0 + s0; + l1 = (same1 && isfinite(l1 + s1)) ? l1 + s1 : l1 * f1 + s1; #pragma unroll for (int n = 0; n < 16; ++n) { - o[n][0] *= f0; - o[n][1] *= f0; - o[n][2] *= f1; - o[n][3] *= f1; + if (!same0 || !isfinite(o[n][0])) o[n][0] *= f0; + if (!same0 || !isfinite(o[n][1])) o[n][1] *= f0; + if (!same1 || !isfinite(o[n][2])) o[n][2] *= f1; + if (!same1 || !isfinite(o[n][3])) o[n][3] *= f1; } #pragma unroll for (int s = 0; s < 4; ++s) { diff --git a/zig/kernels/cuda/moss_image_encoder.cu b/zig/kernels/cuda/moss_image_encoder.cu index 30a9343efa7..475223906e5 100644 --- a/zig/kernels/cuda/moss_image_encoder.cu +++ b/zig/kernels/cuda/moss_image_encoder.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // MOSS-Image's prompt encoder (Qwen3.5's text model) on CUDA: moss_image_encoder.metal's kernels op for op. #include #include @@ -86,9 +87,9 @@ extern "C" __global__ void __launch_bounds__(256) tf_me_attention(const bf16* __ const size_t at = ((size_t)kvh * rows + j) * 256 + d; const float s = tf_common::block_sum_tree(q * ld(K + at), part, 8) * scale; const float top = fmaxf(m, s); - const float old = expf(m - top), e = expf(s - top); - l = l * old + e; - acc = acc * old + e * ld(V + at); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(top) && top == m; const float old = same ? 1.0f : expf(m - top), e = expf(s - top); + l = (same && isfinite(l + e)) ? l + e : l * old + e; + acc = (same && isfinite(acc + e * ld(V + at))) ? acc + e * ld(V + at) : acc * old + e * ld(V + at); m = top; } O[((size_t)t * heads + h) * 256 + d] = __float2bfloat16_rn(__fdiv_rn(acc, l)); diff --git a/zig/kernels/cuda/muse_spark/attention.cu b/zig/kernels/cuda/muse_spark/attention.cu index 3acc5dbc0bd..f54ec98dea2 100644 --- a/zig/kernels/cuda/muse_spark/attention.cu +++ b/zig/kernels/cuda/muse_spark/attention.cu @@ -1,3 +1,4 @@ +#include "../common/softmax_identity.cuh" // Muse Spark's decode attention, head_dim 64, GQA 8:1: QK prep and cache write, chunked rows, merge and gate. #include @@ -132,11 +133,13 @@ extern "C" __global__ void __launch_bounds__(256) } const float mt = warp_max(s); const float mn = fmaxf(m, mt); - const float corr = expf(m - mn); // m = -inf on the first tile: 0 + // m = -inf on the first tile: 0 + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m; const float corr = same ? 1.0f : expf(m - mn); const float pj = lane < nk ? expf(s - mn) : 0.f; - l = l * corr + warp_sum(pj); - o0 *= corr; - o1 *= corr; + const float mass = warp_sum(pj); + l = (same && isfinite(l + mass)) ? l + mass : l * corr + mass; + if (!same || !isfinite(o0)) o0 *= corr; + if (!same || !isfinite(o1)) o1 *= corr; for (int j = 0; j < nk; ++j) { const float pb = __shfl_sync(0xffffffffu, pj, j); const float2 vf = __half22float2(vs[j * 32 + lane]); @@ -165,10 +168,10 @@ extern "C" __global__ void muse_attn_merge(const float* __restrict__ po, const f for (int c = 0; c < NCH; ++c) { const float l = pl[b + c]; if (l == 0.f) continue; - const float f = expf(pm[b + c] - M); - L += l * f; - o0 += po[(b + c) * HD + 2 * lane] * f; - o1 += po[(b + c) * HD + 2 * lane + 1] * f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(M) && M == pm[b + c]; const float f = same ? 1.0f : expf(pm[b + c] - M); + L = (same && isfinite(L + l)) ? L + l : L + l * f; + o0 = (same && isfinite(o0 + po[(b + c) * HD + 2 * lane])) ? o0 + po[(b + c) * HD + 2 * lane] : o0 + po[(b + c) * HD + 2 * lane] * f; + o1 = (same && isfinite(o1 + po[(b + c) * HD + 2 * lane + 1])) ? o1 + po[(b + c) * HD + 2 * lane + 1] : o1 + po[(b + c) * HD + 2 * lane + 1] * f; } const float a0 = __half2float(__float2half_rn(o0 / L)), a1 = __half2float(__float2half_rn(o1 / L)); const float rs = rsqrtf(warp_sum(a0 * a0 + a1 * a1) / (float)HD + eps); diff --git a/zig/kernels/cuda/muse_spark/dflash.cu b/zig/kernels/cuda/muse_spark/dflash.cu index 3df257345fd..7e11eefe703 100644 --- a/zig/kernels/cuda/muse_spark/dflash.cu +++ b/zig/kernels/cuda/muse_spark/dflash.cu @@ -1,3 +1,4 @@ +#include "../common/softmax_identity.cuh" // Muse Spark's DFlash2 drafter glue in fp32 (block embed, taps, q/k norm + RoPE, context rows, attention, argmax). #include @@ -122,13 +123,13 @@ extern "C" __global__ void __launch_bounds__(256) dr_attn(const float* __restric for (int k = 16; k > 0; k >>= 1) tm = fmaxf(tm, __shfl_xor_sync(0xffffffff, tm, k)); if (tm == -INFINITY) continue; // nothing visible in this tile for this query const float mn = fmaxf(m, tm); - const float corr = m == -INFINITY ? 0.0f : expf(m - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m; const float corr = same ? 1.0f : (m == -INFINITY ? 0.0f : expf(m - mn)); const float p = sc == -INFINITY ? 0.0f : expf(sc - mn); float ps = p; for (int k = 16; k > 0; k >>= 1) ps += __shfl_xor_sync(0xffffffff, ps, k); - l = l * corr + ps; + l = (same && isfinite(l + ps)) ? l + ps : l * corr + ps; #pragma unroll - for (int e = 0; e < 4; ++e) o[e] *= corr; + for (int e = 0; e < 4; ++e) if (!same || !isfinite(o[e])) o[e] *= corr; for (int j = 0; j < DR_TILE; ++j) { const float pj = __shfl_sync(0xffffffff, p, j); if (pj != 0.0f) { @@ -142,10 +143,10 @@ extern "C" __global__ void __launch_bounds__(256) dr_attn(const float* __restric if (sinks) { const float sk = sinks[h]; const float mn = fmaxf(m, sk); - const float corr = m == -INFINITY ? 0.0f : expf(m - mn); - l = l * corr + expf(sk - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m; const float corr = same ? 1.0f : (m == -INFINITY ? 0.0f : expf(m - mn)); + l = (same && isfinite(l + expf(sk - mn))) ? l + expf(sk - mn) : l * corr + expf(sk - mn); #pragma unroll - for (int e = 0; e < 4; ++e) o[e] *= corr; + for (int e = 0; e < 4; ++e) if (!same || !isfinite(o[e])) o[e] *= corr; } #pragma unroll for (int e = 0; e < 4; ++e) out[((int64_t)r * H + h) * 128 + lane * 4 + e] = __float2half_rn(o[e] / l); diff --git a/zig/kernels/cuda/nemotron_attention.cu b/zig/kernels/cuda/nemotron_attention.cu index 6c66d567048..f22cd913045 100644 --- a/zig/kernels/cuda/nemotron_attention.cu +++ b/zig/kernels/cuda/nemotron_attention.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Merge absolute 512-key attention chunks in order, so a row's bits ignore its window. #include @@ -84,7 +85,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_nemo_attn_chunk(const __nv_ const float tile_m = half_max(fmaxf(fmaxf(sc[0], sc[1]), fmaxf(sc[2], sc[3]))); const bool active = tile_m != -INFINITY; const float next = active ? fmaxf(m, tile_m) : m; - const float alpha = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float alpha = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); float local = 0.0f; #pragma unroll for (int u = 0; u < 4; ++u) { @@ -92,7 +93,8 @@ extern "C" __global__ void __launch_bounds__(256) tf_nemo_attn_chunk(const __nv_ ps[g][jj + 16 * u] = p; local = __fadd_rn(local, p); } - den = __fmaf_rn(den, alpha, half_sum(local)); + const float sum = half_sum(local); + den = (same && isfinite(__fadd_rn(den, sum))) ? __fadd_rn(den, sum) : __fmaf_rn(den, alpha, sum); m = next; __syncthreads(); float pv[8]; @@ -109,7 +111,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_nemo_attn_chunk(const __nv_ } } #pragma unroll - for (int e = 0; e < 8; ++e) o[e] = __fmaf_rn(o[e], alpha, pv[e]); + for (int e = 0; e < 8; ++e) o[e] = (same && isfinite(__fadd_rn(o[e], pv[e]))) ? __fadd_rn(o[e], pv[e]) : __fmaf_rn(o[e], alpha, pv[e]); } if (g >= G) continue; const int64_t base = (static_cast(r) * NCH + c) * H + hk * G + g; @@ -140,14 +142,14 @@ extern "C" __global__ void __launch_bounds__(256) tf_nemo_attn_merge(const float const float cm = PM[base], cl = PL[base]; const bool active = cl > 0.0f; const float next = active ? fmaxf(m, cm) : m; - const float a = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); const float b = active ? tf_exp(__fsub_rn(cm, next)) : 0.0f; const float4* po = reinterpret_cast(PO + base * HD + 8 * jj); const float4 p0 = po[0], p1 = po[1]; const float co[8] = {p0.x, p0.y, p0.z, p0.w, p1.x, p1.y, p1.z, p1.w}; #pragma unroll - for (int e = 0; e < 8; ++e) o[e] = __fmaf_rn(o[e], a, __fmul_rn(co[e], b)); - den = __fmaf_rn(den, a, __fmul_rn(cl, b)); + for (int e = 0; e < 8; ++e) o[e] = (same && isfinite(__fadd_rn(o[e], __fmul_rn(co[e], b)))) ? __fadd_rn(o[e], __fmul_rn(co[e], b)) : __fmaf_rn(o[e], a, __fmul_rn(co[e], b)); + den = (same && isfinite(__fadd_rn(den, __fmul_rn(cl, b)))) ? __fadd_rn(den, __fmul_rn(cl, b)) : __fmaf_rn(den, a, __fmul_rn(cl, b)); m = next; } #pragma unroll @@ -262,7 +264,7 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_nemo_attn_chunk_pf(const const float tile_m = half_max(fmaxf(fmaxf(sc[0], sc[1]), fmaxf(sc[2], sc[3]))); const bool active = tile_m != -INFINITY; const float next = active ? fmaxf(m, tile_m) : m; - const float alpha = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float alpha = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); float local = 0.0f; #pragma unroll for (int u = 0; u < 4; ++u) { @@ -270,7 +272,8 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_nemo_attn_chunk_pf(const ps[g][jj + 16 * u] = p; local = __fadd_rn(local, p); } - den = __fmaf_rn(den, alpha, half_sum(local)); + const float sum = half_sum(local); + den = (same && isfinite(__fadd_rn(den, sum))) ? __fadd_rn(den, sum) : __fmaf_rn(den, alpha, sum); m = next; __syncthreads(); float pv[8]; @@ -287,7 +290,7 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_nemo_attn_chunk_pf(const } } #pragma unroll - for (int e = 0; e < 8; ++e) o[e] = __fmaf_rn(o[e], alpha, pv[e]); + for (int e = 0; e < 8; ++e) o[e] = (same && isfinite(__fadd_rn(o[e], pv[e]))) ? __fadd_rn(o[e], pv[e]) : __fmaf_rn(o[e], alpha, pv[e]); } if (g >= G) continue; const int64_t base = (static_cast(r) * NCH + c) * H + hk * G + g; diff --git a/zig/kernels/cuda/paged_attn_segs.cuh b/zig/kernels/cuda/paged_attn_segs.cuh index 6ff3f1919c7..d0c367a2cda 100644 --- a/zig/kernels/cuda/paged_attn_segs.cuh +++ b/zig/kernels/cuda/paged_attn_segs.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Paged shared-window chunk/merge bodies shared by families (Nemotron head 128, LFM2 head 64); SEG_* set the form. #define SEG_E (SEG_WIDE ? 8 : 4) @@ -62,7 +63,7 @@ extern "C" __global__ void __launch_bounds__(256) SEG_CHUNK(const AttnSegs sg, c const float tile_m = half_max(fmaxf(fmaxf(sc[0], sc[1]), fmaxf(sc[2], sc[3]))); const bool active = tile_m != -INFINITY; const float next = active ? fmaxf(m, tile_m) : m; - const float alpha = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float alpha = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); float local = 0.0f; #pragma unroll for (int u = 0; u < 4; ++u) { @@ -70,7 +71,8 @@ extern "C" __global__ void __launch_bounds__(256) SEG_CHUNK(const AttnSegs sg, c ps[g][jj + 16 * u] = p; local = __fadd_rn(local, p); } - den = __fmaf_rn(den, alpha, half_sum(local)); + const float sum = half_sum(local); + den = (same && isfinite(__fadd_rn(den, sum))) ? __fadd_rn(den, sum) : __fmaf_rn(den, alpha, sum); m = next; __syncthreads(); float pv[SEG_E]; @@ -94,7 +96,7 @@ extern "C" __global__ void __launch_bounds__(256) SEG_CHUNK(const AttnSegs sg, c } } #pragma unroll - for (int e = 0; e < SEG_E; ++e) o[e] = __fmaf_rn(o[e], alpha, pv[e]); + for (int e = 0; e < SEG_E; ++e) o[e] = (same && isfinite(__fadd_rn(o[e], pv[e]))) ? __fadd_rn(o[e], pv[e]) : __fmaf_rn(o[e], alpha, pv[e]); } if (g >= G) continue; const int64_t base = (static_cast(rq) * NCH + c) * H + hk * G + g; @@ -127,7 +129,7 @@ extern "C" __global__ void __launch_bounds__(256) SEG_MERGE(const AttnSegs sg, c const float cm = PM[base], cl = PL[base]; const bool active = cl > 0.0f; const float next = active ? fmaxf(m, cm) : m; - const float a = active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : tf_exp(__fsub_rn(m, next))) : 1.0f); const float b = active ? tf_exp(__fsub_rn(cm, next)) : 0.0f; const float4* po = reinterpret_cast(PO + base * SEG_HD + SEG_E * jj); #if SEG_WIDE @@ -138,8 +140,8 @@ extern "C" __global__ void __launch_bounds__(256) SEG_MERGE(const AttnSegs sg, c const float co[4] = {p0.x, p0.y, p0.z, p0.w}; #endif #pragma unroll - for (int e = 0; e < SEG_E; ++e) o[e] = __fmaf_rn(o[e], a, __fmul_rn(co[e], b)); - den = __fmaf_rn(den, a, __fmul_rn(cl, b)); + for (int e = 0; e < SEG_E; ++e) o[e] = (same && isfinite(__fadd_rn(o[e], __fmul_rn(co[e], b)))) ? __fadd_rn(o[e], __fmul_rn(co[e], b)) : __fmaf_rn(o[e], a, __fmul_rn(co[e], b)); + den = (same && isfinite(__fadd_rn(den, __fmul_rn(cl, b)))) ? __fadd_rn(den, __fmul_rn(cl, b)) : __fmaf_rn(den, a, __fmul_rn(cl, b)); m = next; } #pragma unroll diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index fe7488fe758..a0ae1059db0 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Device code of src/tensorfold/cuda/kernels/prefill_attention.cu (comments, ATen includes dropped), paged keys added. #include "prefill_attention.cuh" @@ -259,8 +260,9 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0[NT], c1[NT]; #pragma unroll for (int n = 0; n < NT; ++n) { @@ -272,16 +274,17 @@ vision_kernel(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ c0[n] = __fadd_rn(sc[n][0], sc[n][1]); c1[n] = __fadd_rn(sc[n][2], sc[n][3]); } - l0 = __fmaf_rn(l0, a0, rowsum(c0)); - l1 = __fmaf_rn(l1, a1, rowsum(c1)); + const float sum0 = rowsum(c0), sum1 = rowsum(c1); + l0 = (same0 && isfinite(__fadd_rn(l0, sum0))) ? __fadd_rn(l0, sum0) : __fmaf_rn(l0, a0, sum0); + l1 = (same1 && isfinite(__fadd_rn(l1, sum1))) ? __fadd_rn(l1, sum1) : __fmaf_rn(l1, a1, sum1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < C; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } #pragma unroll for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile diff --git a/zig/kernels/cuda/prefill_attention_rows.cuh b/zig/kernels/cuda/prefill_attention_rows.cuh index 41b185ef0bd..e4edccdb1ac 100644 --- a/zig/kernels/cuda/prefill_attention_rows.cuh +++ b/zig/kernels/cuda/prefill_attention_rows.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Row attention body; caller supplies tensors, geometry, layout constants, and first_row. constexpr int C = D / 8, K16 = (D + 15) / 16, NB = 2 * K16; // the head's 16-byte chunks, 16-dim steps, 8-dim tiles constexpr int CS = (NB + 7) / 8 * 8, RB = WARPS / HPC, THREADS = 32 * WARPS; // CS: a staged key row's chunks @@ -227,8 +228,9 @@ } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0[8], c1[8]; #pragma unroll for (int n = 0; n < 8; ++n) { @@ -240,16 +242,17 @@ c0[n] = __fadd_rn(sc[n][0], sc[n][1]); c1[n] = __fadd_rn(sc[n][2], sc[n][3]); } - l0 = __fmaf_rn(l0, a0, rowsum(c0)); - l1 = __fmaf_rn(l1, a1, rowsum(c1)); + const float sum0 = rowsum(c0), sum1 = rowsum(c1); + l0 = (same0 && isfinite(__fadd_rn(l0, sum0))) ? __fadd_rn(l0, sum0) : __fmaf_rn(l0, a0, sum0); + l1 = (same1 && isfinite(__fadd_rn(l1, sum1))) ? __fadd_rn(l1, sum1) : __fmaf_rn(l1, a1, sum1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < NB; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } #pragma unroll for (int j = 0; j < 4; ++j) { diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index e309a302fdd..ad59e9d6dd6 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Qwen3.5's hybrids (2B, 27B) on CUDA: the Metal kernels' arithmetic and rounding; a segment is one stream's window. #include "qwen35.cuh" @@ -503,10 +504,10 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35_attn_merge(Geo geo, cons for (int i = 0; i < DPL; i++) acc[i] = 0.0f; for (int c = 0; c < nch; c++) { if (!(PL[base + c] > 0.0f)) continue; - const float e = __expf(PM[base + c] - mx); - lsum = fmaf(PL[base + c], e, lsum); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mx) && mx == PM[base + c]; const float e = same ? 1.0f : __expf(PM[base + c] - mx); + lsum = (same && isfinite(__fadd_rn(PL[base + c], lsum))) ? __fadd_rn(PL[base + c], lsum) : fmaf(PL[base + c], e, lsum); #pragma unroll - for (int i = 0; i < DPL; i++) acc[i] = fmaf(PO[(base + c) * HD + lane * DPL + i], e, acc[i]); + for (int i = 0; i < DPL; i++) acc[i] = (same && isfinite(__fadd_rn(PO[(base + c) * HD + lane * DPL + i], acc[i]))) ? __fadd_rn(PO[(base + c) * HD + lane * DPL + i], acc[i]) : fmaf(PO[(base + c) * HD + lane * DPL + i], e, acc[i]); } #pragma unroll for (int i = 0; i < DPL; i++) OUT[(m * QH + qh) * HD + lane * DPL + i] = __float2bfloat16_rn(acc[i] / lsum); diff --git a/zig/kernels/cuda/qwen35_attn.cuh b/zig/kernels/cuda/qwen35_attn.cuh index e9e094bda5d..ce6019d5921 100644 --- a/zig/kernels/cuda/qwen35_attn.cuh +++ b/zig/kernels/cuda/qwen35_attn.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Contiguous attention retains the pre-paging body; the general entry also serves mixed cache layouts. #pragma once #include "qwen35_page_run.h" @@ -44,12 +45,12 @@ extern "C" __global__ void tf_q35_attn_partial_contiguous(Geo geo, const __nv_bf for (int i = 0; i < DPL; i++) dot = fmaf(q[i], bf(kb[i]), dot); const float s = warp_sum(dot) * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; const uint4 vw = *reinterpret_cast(V + ((size_t)h * sg.cap + pos) * HD + lane * DPL); const __nv_bfloat16* vb = reinterpret_cast(&vw); #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(vb[i]), o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(b, bf(vb[i]), o[i]))) ? fmaf(b, bf(vb[i]), o[i]) : fmaf(b, bf(vb[i]), o[i] * a); mx = mn; } if (lane == 0) { @@ -103,12 +104,12 @@ extern "C" __global__ void tf_q35_attn_partial_legacy(Geo geo, const __nv_bfloat for (int i = 0; i < DPL; i++) dot = fmaf(q[i], bf(kb[i]), dot); const float s = warp_sum(dot) * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; const uint4 vw = *reinterpret_cast(row(1, pos) + lane * DPL); const __nv_bfloat16* vb = reinterpret_cast(&vw); #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(vb[i]), o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(b, bf(vb[i]), o[i]))) ? fmaf(b, bf(vb[i]), o[i]) : fmaf(b, bf(vb[i]), o[i] * a); mx = mn; } }; @@ -171,12 +172,12 @@ extern "C" __global__ void tf_q35_attn_partial_paged(Geo geo, const __nv_bfloat1 for (int i = 0; i < DPL; i++) dot = fmaf(q[i], bf(kb[i]), dot); const float s = warp_sum(dot) * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; const uint4 vw = *reinterpret_cast(row(1, pos) + lane * DPL); const __nv_bfloat16* vb = reinterpret_cast(&vw); #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(vb[i]), o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(b, bf(vb[i]), o[i]))) ? fmaf(b, bf(vb[i]), o[i]) : fmaf(b, bf(vb[i]), o[i] * a); mx = mn; } }; diff --git a/zig/kernels/cuda/qwen35_attn_tc.cuh b/zig/kernels/cuda/qwen35_attn_tc.cuh index ca3c5995438..c8a583f75c2 100644 --- a/zig/kernels/cuda/qwen35_attn_tc.cuh +++ b/zig/kernels/cuda/qwen35_attn_tc.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Ours: decode attention on tensor cores for the Qwen3.5 hybrids, over bf16 (qwen35.cu) or e4m3 (qwen35_kv8.cu) caches. #pragma once @@ -145,7 +146,8 @@ __device__ __forceinline__ void attn_one(TileStore store, Geo geo, const __nv_bf for (int x = 1; x < 8; x *= 2) tm = fmaxf(tm, __shfl_xor_sync(0xffffffffu, tm, x)); const bool act = tm != -INFINITY; const float nm = act ? fmaxf(mx, tm) : mx; - const float a = act ? (mx == -INFINITY ? 0.0f : texp(mx - nm)) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && act && isfinite(nm) && nm == mx; + const float a = same ? 1.0f : (act ? (mx == -INFINITY ? 0.0f : texp(mx - nm)) : 1.0f); float ps = 0.0f; #pragma unroll for (int j = 0; j < 4; j++) { @@ -156,7 +158,7 @@ __device__ __forceinline__ void attn_one(TileStore store, Geo geo, const __nv_bf } #pragma unroll for (int x = 1; x < 8; x *= 2) ps += __shfl_xor_sync(0xffffffffu, ps, x); - l = fmaf(l, a, ps); + l = (same && isfinite(__fadd_rn(l, ps))) ? __fadd_rn(l, ps) : fmaf(l, a, ps); mx = nm; if (part8 == 0) alpha[line] = a; } @@ -418,8 +420,9 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b tmb = fmaxf(red[0][lb], red[1][lb]); const bool acta = tma != -INFINITY, actb = tmb != -INFINITY; const float na = acta ? fmaxf(mxa, tma) : mxa, nb = actb ? fmaxf(mxb, tmb) : mxb; - const float aa = acta ? (mxa == -INFINITY ? 0.0f : texp(mxa - na)) : 1.0f; - const float ab = actb ? (mxb == -INFINITY ? 0.0f : texp(mxb - nb)) : 1.0f; + const bool samea = TF_CUDA_SOFTMAX_IDENTITY_GUARD && acta && isfinite(na) && na == mxa, sameb = TF_CUDA_SOFTMAX_IDENTITY_GUARD && actb && isfinite(nb) && nb == mxb; + const float aa = samea ? 1.0f : (acta ? (mxa == -INFINITY ? 0.0f : texp(mxa - na)) : 1.0f); + const float ab = sameb ? 1.0f : (actb ? (mxb == -INFINITY ? 0.0f : texp(mxb - nb)) : 1.0f); float pa = 0.0f, pb = 0.0f; #pragma unroll for (int n = 0; n < 2; n++) @@ -444,8 +447,8 @@ __device__ __forceinline__ void attn_rows(TileStore store, Geo geo, const __nv_b } } __syncthreads(); - sa = fmaf(sa, aa, red[0][la] + red[1][la]); - sb = fmaf(sb, ab, red[0][lb] + red[1][lb]); + sa = (samea && isfinite(__fadd_rn(sa, __fadd_rn(red[0][la], red[1][la])))) ? __fadd_rn(sa, __fadd_rn(red[0][la], red[1][la])) : fmaf(sa, aa, __fadd_rn(red[0][la], red[1][la])); + sb = (sameb && isfinite(__fadd_rn(sb, __fadd_rn(red[0][lb], red[1][lb])))) ? __fadd_rn(sb, __fadd_rn(red[0][lb], red[1][lb])) : fmaf(sb, ab, __fadd_rn(red[0][lb], red[1][lb])); mxa = na; mxb = nb; // the values: rescale every line once, then each tile of values (a window tile's, row by row) diff --git a/zig/kernels/cuda/qwen35_draft.cu b/zig/kernels/cuda/qwen35_draft.cu index d4dcfeba870..91c97885168 100644 --- a/zig/kernels/cuda/qwen35_draft.cu +++ b/zig/kernels/cuda/qwen35_draft.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // DFlash2 drafter glue on CUDA (cuda_draft.zig): a block of rows over the target's taps, draft_ops.metal's rounding. #include @@ -135,11 +136,11 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35d_attn(const __nv_bfloat1 for (int i = 0; i < DPL; i++) dot = fmaf(q[i], bf(k[i]), dot); const float s = warp_sum(dot) * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; const __nv_bfloat16* v = RV + (size_t)(pos % W) * width + kvh * HD + lane * DPL; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(v[i]), o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(b, bf(v[i]), o[i]))) ? fmaf(b, bf(v[i]), o[i]) : fmaf(b, bf(v[i]), o[i] * a); mx = mn; } for (int r = 0; r < rows; r++) { @@ -149,11 +150,11 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35d_attn(const __nv_bfloat1 for (int i = 0; i < DPL; i++) dot = fmaf(q[i], bf(k[i]), dot); const float s = warp_sum(dot) * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; const __nv_bfloat16* v = VB + ((size_t)r * kv_heads + kvh) * HD + lane * DPL; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(v[i]), o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(b, bf(v[i]), o[i]))) ? fmaf(b, bf(v[i]), o[i]) : fmaf(b, bf(v[i]), o[i] * a); mx = mn; } #pragma unroll diff --git a/zig/kernels/cuda/qwen35_draft_frame.cuh b/zig/kernels/cuda/qwen35_draft_frame.cuh index 63779c62135..25a411cb769 100644 --- a/zig/kernels/cuda/qwen35_draft_frame.cuh +++ b/zig/kernels/cuda/qwen35_draft_frame.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Batched DFlash glue: stream-local convolution and rotary positions, then 256-key attention chunks. #pragma once struct DraftSegment { unsigned long long ring; long long begin, position; }; @@ -163,10 +164,10 @@ extern "C" __global__ void __launch_bounds__(128) tf_q35d_attn_partial(const __n #pragma unroll for (int w = 0; w < WARPS; ++w) { if (wl[w] == 0.0f) continue; - const float scale = __expf(wm[w] - top); - total = fmaf(wl[w], scale, total); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(top) && top == wm[w]; const float scale = same ? 1.0f : __expf(wm[w] - top); + total = (same && isfinite(__fadd_rn(wl[w], total))) ? __fadd_rn(wl[w], total) : fmaf(wl[w], scale, total); #pragma unroll - for (int i = 0; i < DPL; ++i) out[i] = fmaf(wo[w][lane * DPL + i], scale, out[i]); + for (int i = 0; i < DPL; ++i) out[i] = (same && isfinite(__fadd_rn(wo[w][lane * DPL + i], out[i]))) ? __fadd_rn(wo[w][lane * DPL + i], out[i]) : fmaf(wo[w][lane * DPL + i], scale, out[i]); } if (lane == 0) { PM[slot] = total > 0.0f ? top : -INFINITY; PL[slot] = total; } #pragma unroll @@ -184,10 +185,10 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35d_attn_merge(const float* for (int chunk = 0; chunk < chunks; ++chunk) { const size_t slot = base + chunk; if (PL[slot] == 0.0f) continue; - const float next = fmaxf(mx, PM[slot]), a = __expf(mx - next), b = __expf(PM[slot] - next); + const float next = fmaxf(mx, PM[slot]); const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == mx; const float a = same ? 1.0f : __expf(mx - next), b = __expf(PM[slot] - next); sum = sum * a + PL[slot] * b; #pragma unroll - for (int i = 0; i < DPL; ++i) out[i] = fmaf(b, PO[slot * HD + lane * DPL + i], out[i] * a); + for (int i = 0; i < DPL; ++i) out[i] = (same && isfinite(fmaf(b, PO[slot * HD + lane * DPL + i], out[i]))) ? fmaf(b, PO[slot * HD + lane * DPL + i], out[i]) : fmaf(b, PO[slot * HD + lane * DPL + i], out[i] * a); mx = next; } #pragma unroll diff --git a/zig/kernels/cuda/qwen35_kv8.cu b/zig/kernels/cuda/qwen35_kv8.cu index cf6fbc5a68b..7944708c847 100644 --- a/zig/kernels/cuda/qwen35_kv8.cu +++ b/zig/kernels/cuda/qwen35_kv8.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Ours: --kv-cache fp8 for Qwen3.5: key and value rows as e4m3, an fp32 scale (amax / 448) each, as qwen27 keeps them. #include @@ -118,12 +119,12 @@ extern "C" __global__ void tf_q35_attn_partial8_contiguous(Geo geo, const __nv_b for (int i = 0; i < DPL; i++) dot = fmaf(q[i], kf[i], dot); const float s = warp_sum(dot) * KS[row] * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; widen8(*reinterpret_cast(V + row * HD + lane * DPL), vf); const float bv = b * VS[row]; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(bv, vf[i], o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(bv, vf[i], o[i]))) ? fmaf(bv, vf[i], o[i]) : fmaf(bv, vf[i], o[i] * a); mx = mn; } if (lane == 0) { @@ -177,12 +178,12 @@ extern "C" __global__ void tf_q35_attn_partial8_legacy(Geo geo, const __nv_bfloa for (int i = 0; i < DPL; i++) dot = fmaf(q[i], kf[i], dot); const float s = warp_sum(dot) * *r.ks * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; widen8(*reinterpret_cast(r.v + lane * DPL), vf); const float bv = b * *r.vs; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(bv, vf[i], o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(bv, vf[i], o[i]))) ? fmaf(bv, vf[i], o[i]) : fmaf(bv, vf[i], o[i] * a); mx = mn; } }; @@ -242,12 +243,12 @@ extern "C" __global__ void tf_q35_attn_partial8_paged(Geo geo, const __nv_bfloat for (int i = 0; i < DPL; i++) dot = fmaf(q[i], kf[i], dot); const float s = warp_sum(dot) * *r.ks * scale; const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; widen8(*reinterpret_cast(r.v + lane * DPL), vf); const float bv = b * *r.vs; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(bv, vf[i], o[i] * a); + for (int i = 0; i < DPL; i++) o[i] = (same && isfinite(fmaf(bv, vf[i], o[i]))) ? fmaf(bv, vf[i], o[i]) : fmaf(bv, vf[i], o[i] * a); mx = mn; } }; diff --git a/zig/kernels/cuda/qwen36_mtp.cu b/zig/kernels/cuda/qwen36_mtp.cu index 83f86bfd84b..8173d577dde 100644 --- a/zig/kernels/cuda/qwen36_mtp.cu +++ b/zig/kernels/cuda/qwen36_mtp.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // The Qwen3.6 MTP drafter's glue on CUDA (cuda_mtp.zig): its attention at the target's head width over a ring. #include @@ -28,10 +29,10 @@ __device__ __forceinline__ float score(const float (&q)[DPL], const __nv_bfloat1 // One key folded into the running softmax (mx, l) and the lane's weighted values o. __device__ __forceinline__ void fold(float s, const __nv_bfloat16* v, float& mx, float& l, float (&o)[DPL]) { const float mn = fmaxf(mx, s); - const float a = __expf(mx - mn), b = __expf(s - mn); - l = l * a + b; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == mx; const float a = same ? 1.0f : __expf(mx - mn), b = __expf(s - mn); + l = (same && isfinite(l + b)) ? l + b : l * a + b; #pragma unroll - for (int i = 0; i < DPL; i++) o[i] = fmaf(b, bf(v[i]), o[i] * a); + for (int i = 0; i < DPL; ++i) o[i] = (same && isfinite(fmaf(b, bf(v[i]), o[i]))) ? fmaf(b, bf(v[i]), o[i]) : fmaf(b, bf(v[i]), o[i] * a); mx = mn; } diff --git a/zig/kernels/cuda/qwen_vision.cu b/zig/kernels/cuda/qwen_vision.cu index 391c9526027..337e2cdd0dc 100644 --- a/zig/kernels/cuda/qwen_vision.cu +++ b/zig/kernels/cuda/qwen_vision.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Qwen3.5 vision tower kernels (0.6.6's --vision in bf16); epilogues add the bias to cuBLASLt's fp32, round once. #include #include @@ -134,11 +135,11 @@ __device__ void qv_attention(const __nv_bfloat16* __restrict__ q, const __nv_bfl #pragma unroll for (int d = 0; d < HD; ++d) s += qr[d] * ks[r][d]; const float mn = fmaxf(m, s); - const float corr = __expf(m - mn); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mn) && mn == m; const float corr = same ? 1.0f : __expf(m - mn); const float p = __expf(s - mn); - l = l * corr + p; + l = (same && isfinite(l + p)) ? l + p : l * corr + p; #pragma unroll - for (int d = 0; d < HD; ++d) acc[d] = acc[d] * corr + p * vs[r][d]; + for (int d = 0; d < HD; ++d) acc[d] = (same && isfinite(acc[d] + p * vs[r][d])) ? acc[d] + p * vs[r][d] : acc[d] * corr + p * vs[r][d]; m = mn; } } diff --git a/zig/kernels/cuda/tree_attention.cu b/zig/kernels/cuda/tree_attention.cu index 612e545468c..5c771da8c85 100644 --- a/zig/kernels/cuda/tree_attention.cu +++ b/zig/kernels/cuda/tree_attention.cu @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Tree attention (float64 references: core/attention_ref.zig): committed keys, then the row's path, groups in order. #include @@ -210,8 +211,9 @@ __device__ __forceinline__ bool tree_group( } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; // each row's own: a NaN head moves only its row const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0 = 0.0f, c1 = 0.0f; #pragma unroll for (int n = 0; n < NT8; ++n) { @@ -226,16 +228,16 @@ __device__ __forceinline__ bool tree_group( c0 = __fadd_rn(c0, __shfl_xor_sync(0xffffffffu, c0, x)); c1 = __fadd_rn(c1, __shfl_xor_sync(0xffffffffu, c1, x)); } - l0 = __fmaf_rn(l0, a0, c0); - l1 = __fmaf_rn(l1, a1, c1); + l0 = (same0 && isfinite(__fadd_rn(l0, c0))) ? __fadd_rn(l0, c0) : __fmaf_rn(l0, a0, c0); + l1 = (same1 && isfinite(__fadd_rn(l1, c1))) ? __fadd_rn(l1, c1) : __fmaf_rn(l1, a1, c1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < NB; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } uint32_t pa[PK][4]; #pragma unroll @@ -327,9 +329,9 @@ __device__ __forceinline__ bool tree_group( for (int w = 0; w < 4; ++w) { const float mw = ms[w * 16 + hd]; if (mw == -INFINITY) continue; - const float a = texp(__fsub_rn(mw, mm)); - acc = __fmaf_rn(a, os[(w * 16 + hd) * D + e], acc); - l = __fmaf_rn(a, ls[w * 16 + hd], l); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mm) && mm == mw; const float a = same ? 1.0f : texp(__fsub_rn(mw, mm)); + acc = (same && isfinite(__fadd_rn(os[(w * 16 + hd) * D + e], acc))) ? __fadd_rn(os[(w * 16 + hd) * D + e], acc) : __fmaf_rn(a, os[(w * 16 + hd) * D + e], acc); + l = (same && isfinite(__fadd_rn(ls[w * 16 + hd], l))) ? __fadd_rn(ls[w * 16 + hd], l) : __fmaf_rn(a, ls[w * 16 + hd], l); } if (acc != acc) { // NaN: a replayed infinity (weighed in float64) may have met a weight of 0; again, kept acc = 0.0f; @@ -489,17 +491,19 @@ extern "C" __global__ void __launch_bounds__(256) tf_tree_merge( for (int w = 0; w < 4; ++w) { const float mw = cm_[i + w]; if (mw == -INFINITY) continue; - const float aw = texp(__fsub_rn(mw, cm)); - co = __fmaf_rn(aw, co_[i + w], co); - cl = __fmaf_rn(aw, cl_[i + w], cl); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(cm) && cm == mw; + const float aw = same ? 1.0f : texp(__fsub_rn(mw, cm)); + co = (same && isfinite(__fadd_rn(co, co_[i + w]))) ? __fadd_rn(co, co_[i + w]) : __fmaf_rn(aw, co_[i + w], co); + cl = (same && isfinite(__fadd_rn(cl, cl_[i + w]))) ? __fadd_rn(cl, cl_[i + w]) : __fmaf_rn(aw, cl_[i + w], cl); } } const bool active = cl > 0.0f; const float next = active ? fmaxf(m, cm) : m; - const float a = active ? (m == -INFINITY ? 0.0f : texp(__fsub_rn(m, next))) : 1.0f; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == m; + const float a = same ? 1.0f : (active ? (m == -INFINITY ? 0.0f : texp(__fsub_rn(m, next))) : 1.0f); const float b = active ? texp(__fsub_rn(cm, next)) : 0.0f; - acc = __fmaf_rn(acc, a, __fmul_rn(co, b)); - l = __fmaf_rn(l, a, __fmul_rn(cl, b)); + acc = (same && isfinite(__fadd_rn(acc, __fmul_rn(co, b)))) ? __fadd_rn(acc, __fmul_rn(co, b)) : __fmaf_rn(acc, a, __fmul_rn(co, b)); + l = (same && isfinite(__fadd_rn(l, __fmul_rn(cl, b)))) ? __fadd_rn(l, __fmul_rn(cl, b)) : __fmaf_rn(l, a, __fmul_rn(cl, b)); m = next; } } @@ -512,14 +516,16 @@ extern "C" __global__ void __launch_bounds__(256) tf_tree_merge( for (int w = 0; w < per; ++w) { const int64_t q = (base + s0 + w) * G + hd; if (pm[q] == -INFINITY) continue; - const float aw = texp(__fsub_rn(pm[q], cm)); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(cm) && cm == pm[q]; + const float aw = same ? 1.0f : texp(__fsub_rn(pm[q], cm)); co = attn_odd::fold(po[q * d + e], aw, co); - cl = __fmaf_rn(aw, pl[q], cl); + cl = (same && isfinite(__fadd_rn(cl, pl[q]))) ? __fadd_rn(cl, pl[q]) : __fmaf_rn(aw, pl[q], cl); } if (!(cl > 0.0f)) continue; const float next = fmaxf(mm, cm); - acc = attn_odd::fold(acc, mm == -INFINITY ? 0.0f : texp(__fsub_rn(mm, next)), - attn_odd::keep(co, texp(__fsub_rn(cm, next)))); + const bool same_new = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == cm; + const float cw = same_new && co == co ? co : attn_odd::keep(co, same_new ? 1.0f : texp(__fsub_rn(cm, next))); + acc = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(next) && next == mm && isfinite(__fadd_rn(acc, cw)) ? __fadd_rn(acc, cw) : attn_odd::fold(acc, mm == -INFINITY ? 0.0f : texp(__fsub_rn(mm, next)), cw); mm = next; } } diff --git a/zig/kernels/cuda/window_attention.cu b/zig/kernels/cuda/window_attention.cu index 95764803eb9..cb70414b1eb 100644 --- a/zig/kernels/cuda/window_attention.cu +++ b/zig/kernels/cuda/window_attention.cu @@ -1,16 +1,14 @@ +#include "common/softmax_identity.cuh" // Sliding-window attention for every CUDA family (float64 references: core/attention_ref.zig): decode and prompt rows. - #include #include #include #include - #include "attn_odd.cuh" #include "common/kv_pages.cuh" #include "common/qmm_frag.cuh" #include "common/cp_async.cuh" #include "window_split.cuh" - // Prompt rows: prefill_attention.cu's tensor-core kernel with a window (keys (pos - win, pos]) and a ring of keys. namespace tf_window_prompt { @@ -202,8 +200,9 @@ __device__ __forceinline__ bool wattn_rows(const __nv_bfloat16* __restrict__ q, } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f); float c0[8], c1[8]; #pragma unroll for (int n = 0; n < 8; ++n) { @@ -215,16 +214,17 @@ __device__ __forceinline__ bool wattn_rows(const __nv_bfloat16* __restrict__ q, c0[n] = __fadd_rn(sc[n][0], sc[n][1]); c1[n] = __fadd_rn(sc[n][2], sc[n][3]); } - l0 = __fmaf_rn(l0, a0, rowsum(c0)); - l1 = __fmaf_rn(l1, a1, rowsum(c1)); + const float sum0 = rowsum(c0), sum1 = rowsum(c1); + l0 = (same0 && isfinite(__fadd_rn(l0, sum0))) ? __fadd_rn(l0, sum0) : __fmaf_rn(l0, a0, sum0); + l1 = (same1 && isfinite(__fadd_rn(l1, sum1))) ? __fadd_rn(l1, sum1) : __fmaf_rn(l1, a1, sum1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < NB; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } #pragma unroll for (int j = 0; j < 4; ++j) { @@ -404,8 +404,9 @@ __device__ __forceinline__ bool decode_tc_rows( } // each head's own max (no key for it: m stays, exp2(+0) is exactly 1), so a NaN head moves only its row const float n0 = fmaxf(m0, tm0), n1 = fmaxf(m1, tm1); - const float a0 = m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0)); - const float a1 = m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1)); + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; + const float a0 = same0 ? 1.0f : (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))); + const float a1 = same1 ? 1.0f : (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))); float c0 = 0.0f, c1 = 0.0f; #pragma unroll for (int n = 0; n < 4; ++n) { @@ -420,16 +421,16 @@ __device__ __forceinline__ bool decode_tc_rows( c0 = __fadd_rn(c0, __shfl_xor_sync(0xffffffffu, c0, x)); c1 = __fadd_rn(c1, __shfl_xor_sync(0xffffffffu, c1, x)); } - l0 = __fmaf_rn(l0, a0, c0); - l1 = __fmaf_rn(l1, a1, c1); + l0 = (same0 && isfinite(__fadd_rn(l0, c0))) ? __fadd_rn(l0, c0) : __fmaf_rn(l0, a0, c0); + l1 = (same1 && isfinite(__fadd_rn(l1, c1))) ? __fadd_rn(l1, c1) : __fmaf_rn(l1, a1, c1); m0 = n0; m1 = n1; #pragma unroll for (int i = 0; i < NB; ++i) { - o[i][0] = __fmul_rn(o[i][0], a0); - o[i][1] = __fmul_rn(o[i][1], a0); - o[i][2] = __fmul_rn(o[i][2], a1); - o[i][3] = __fmul_rn(o[i][3], a1); + if (!same0 || !isfinite(o[i][0])) o[i][0] = __fmul_rn(o[i][0], a0); + if (!same0 || !isfinite(o[i][1])) o[i][1] = __fmul_rn(o[i][1], a0); + if (!same1 || !isfinite(o[i][2])) o[i][2] = __fmul_rn(o[i][2], a1); + if (!same1 || !isfinite(o[i][3])) o[i][3] = __fmul_rn(o[i][3], a1); } cp_wait<1>(); // tile t's V (the next K may still be in flight) if constexpr (ODD) attn_odd::clean_rows(vs, lane, 32); // the chunks this lane copied @@ -513,9 +514,10 @@ __device__ __forceinline__ bool decode_tc_rows( float l = 0.0f; for (int w = 0; w < 4; ++w) { const float mw = ms[w * 16 + hd]; - const float a = mw == -INFINITY ? 0.0f : texp(__fsub_rn(mw, mm)); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mm) && mm == mw; + const float a = same ? 1.0f : (mw == -INFINITY ? 0.0f : texp(__fsub_rn(mw, mm))); as[w * 16 + hd] = a; - if (mw != -INFINITY) l = __fmaf_rn(a, ls[w * 16 + hd], l); + if (mw != -INFINITY) l = (same && isfinite(__fadd_rn(l, ls[w * 16 + hd]))) ? __fadd_rn(l, ls[w * 16 + hd]) : __fmaf_rn(a, ls[w * 16 + hd], l); } il[hd] = l; } @@ -523,14 +525,16 @@ __device__ __forceinline__ bool decode_tc_rows( bool nan = false; for (int idx = threadIdx.x; idx < G * D / 2; idx += 128) { const int hd = idx / (D / 2), e = 2 * (idx % (D / 2)); - float acc0 = 0.0f, acc1 = 0.0f; + float acc0 = 0.0f, acc1 = 0.0f, mm = -INFINITY; + for (int w = 0; w < 4; ++w) mm = fmaxf(mm, ms[w * 16 + hd]); #pragma unroll for (int w = 0; w < 4; ++w) { if (ms[w * 16 + hd] == -INFINITY) continue; + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(mm) && mm == ms[w * 16 + hd]; const float a = as[w * 16 + hd]; const float2 v = *reinterpret_cast(os + (w * 16 + hd) * D + e); - acc0 = __fmaf_rn(a, v.x, acc0); - acc1 = __fmaf_rn(a, v.y, acc1); + acc0 = (same && isfinite(__fadd_rn(acc0, v.x))) ? __fadd_rn(acc0, v.x) : __fmaf_rn(a, v.x, acc0); + acc1 = (same && isfinite(__fadd_rn(acc1, v.y))) ? __fadd_rn(acc1, v.y) : __fmaf_rn(a, v.y, acc1); } if (ODD && (acc0 != acc0 || acc1 != acc1)) { // NaN: a replayed infinity (float64's) met a factor of 0; kept acc0 = acc1 = 0.0f; diff --git a/zig/kernels/cuda/window_rows.cuh b/zig/kernels/cuda/window_rows.cuh index f75daa11812..8fb5e85b79b 100644 --- a/zig/kernels/cuda/window_rows.cuh +++ b/zig/kernels/cuda/window_rows.cuh @@ -1,14 +1,12 @@ +#include "common/softmax_identity.cuh" // window_attention at head dims 256 and 512: decode by 256-key chunks and a merge, prompt tiles (attention_range.zig). #pragma once - #include #include #include -#include #include "common/kv_pages.cuh" #include "common/qmm_frag.cuh" -#include "common/cp_async.cuh" #include "window_fallback.h" namespace tf_wrows { @@ -273,9 +271,9 @@ __device__ __forceinline__ void merge(const float* __restrict__ po, const float* for (int c = 0; c < chunks; ++c) { const float mc = pm[(part0 + c) * G + hd]; if (mc == -INFINITY) continue; - const float a = FAULT == RESCALE ? 1.0f : expf(__fsub_rn(mc, m)); - acc = __fmaf_rn(a, po[((part0 + c) * G + hd) * D + e], acc); - l = __fmaf_rn(a, pl[(part0 + c) * G + hd], l); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && FAULT != RESCALE && isfinite(m) && m == mc; const float a = same ? 1.0f : (FAULT == RESCALE ? 1.0f : expf(__fsub_rn(mc, m))); + acc = (same && isfinite(__fadd_rn(acc, po[((part0 + c) * G + hd) * D + e]))) ? __fadd_rn(acc, po[((part0 + c) * G + hd) * D + e]) : __fmaf_rn(a, po[((part0 + c) * G + hd) * D + e], acc); + l = (same && isfinite(__fadd_rn(l, pl[(part0 + c) * G + hd]))) ? __fadd_rn(l, pl[(part0 + c) * G + hd]) : __fmaf_rn(a, pl[(part0 + c) * G + hd], l); } const float x = __fdiv_rn(acc, l); __nv_bfloat16* oh = out + (r * h + kh * G + hd) * D; @@ -472,8 +470,8 @@ __device__ __forceinline__ bool rows(const __nv_bfloat16* __restrict__ q, const } const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; - const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : __expf(__fsub_rn(m0, n0))) : 1.0f; - const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : __expf(__fsub_rn(m1, n1))) : 1.0f; + const bool same0 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n0) && n0 == m0, same1 = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(n1) && n1 == m1; const float a0 = same0 ? 1.0f : (act0 ? (m0 == -INFINITY ? 0.0f : __expf(__fsub_rn(m0, n0))) : 1.0f); + const float a1 = same1 ? 1.0f : (act1 ? (m1 == -INFINITY ? 0.0f : __expf(__fsub_rn(m1, n1))) : 1.0f); float w0[4], w1[4]; #pragma unroll for (int n = 0; n < 4; ++n) { @@ -486,8 +484,8 @@ __device__ __forceinline__ bool rows(const __nv_bfloat16* __restrict__ q, const w0[n] = __fadd_rn(y0, __shfl_xor_sync(FULL, y0, 1)); w1[n] = __fadd_rn(y1, __shfl_xor_sync(FULL, y1, 1)); } - l0 = __fmaf_rn(l0, a0, __fadd_rn(__fadd_rn(w0[0], w0[2]), __fadd_rn(w0[1], w0[3]))); - l1 = __fmaf_rn(l1, a1, __fadd_rn(__fadd_rn(w1[0], w1[2]), __fadd_rn(w1[1], w1[3]))); + l0 = (same0 && isfinite(__fadd_rn(l0, __fadd_rn(__fadd_rn(w0[0], w0[2]), __fadd_rn(w0[1], w0[3]))))) ? __fadd_rn(l0, __fadd_rn(__fadd_rn(w0[0], w0[2]), __fadd_rn(w0[1], w0[3]))) : __fmaf_rn(l0, a0, __fadd_rn(__fadd_rn(w0[0], w0[2]), __fadd_rn(w0[1], w0[3]))); + l1 = (same1 && isfinite(__fadd_rn(l1, __fadd_rn(__fadd_rn(w1[0], w1[2]), __fadd_rn(w1[1], w1[3]))))) ? __fadd_rn(l1, __fadd_rn(__fadd_rn(w1[0], w1[2]), __fadd_rn(w1[1], w1[3]))) : __fmaf_rn(l1, a1, __fadd_rn(__fadd_rn(w1[0], w1[2]), __fadd_rn(w1[1], w1[3]))); m0 = n0; m1 = n1; uint32_t ph[2][4], pr[2][4]; // P's bf16 fragments, and (P32) the rest P - bf16(P) @@ -532,10 +530,10 @@ __device__ __forceinline__ bool rows(const __nv_bfloat16* __restrict__ q, const #pragma unroll for (int i = 0; i < 8; ++i) { float* x = o[8 * hf + i]; - x[0] = __fmaf_rn(x[0], a0, tv[i][0]); - x[1] = __fmaf_rn(x[1], a0, tv[i][1]); - x[2] = __fmaf_rn(x[2], a1, tv[i][2]); - x[3] = __fmaf_rn(x[3], a1, tv[i][3]); + x[0] = (same0 && isfinite(__fadd_rn(x[0], tv[i][0]))) ? __fadd_rn(x[0], tv[i][0]) : __fmaf_rn(x[0], a0, tv[i][0]); + x[1] = (same0 && isfinite(__fadd_rn(x[1], tv[i][1]))) ? __fadd_rn(x[1], tv[i][1]) : __fmaf_rn(x[1], a0, tv[i][1]); + x[2] = (same1 && isfinite(__fadd_rn(x[2], tv[i][2]))) ? __fadd_rn(x[2], tv[i][2]) : __fmaf_rn(x[2], a1, tv[i][2]); + x[3] = (same1 && isfinite(__fadd_rn(x[3], tv[i][3]))) ? __fadd_rn(x[3], tv[i][3]) : __fmaf_rn(x[3], a1, tv[i][3]); } } done(2 * t + 1); diff --git a/zig/kernels/cuda/window_split.cuh b/zig/kernels/cuda/window_split.cuh index 0c7cd8c0dbc..62bbabea70b 100644 --- a/zig/kernels/cuda/window_split.cuh +++ b/zig/kernels/cuda/window_split.cuh @@ -1,3 +1,4 @@ +#include "common/softmax_identity.cuh" // Sliding-window decode split by key tile (float64 references: core/attention_ref.zig), and its merge. #pragma once @@ -148,9 +149,9 @@ extern "C" __global__ void __launch_bounds__(NT) tf_window_merge(const float* __ for (int j = 0; j < tiles; ++j) { const float mj = pm[(part0 + j) * g + hd]; if (mj == -INFINITY) continue; - const float a = expf(__fsub_rn(mj, m)); - acc = __fmaf_rn(a, po[(part0 + j) * g * d + o], acc); - l = __fmaf_rn(a, pl[(part0 + j) * g + hd], l); + const bool same = TF_CUDA_SOFTMAX_IDENTITY_GUARD && isfinite(m) && m == mj; const float a = same ? 1.0f : expf(__fsub_rn(mj, m)); + acc = (same && isfinite(__fadd_rn(acc, po[(part0 + j) * g * d + o]))) ? __fadd_rn(acc, po[(part0 + j) * g * d + o]) : __fmaf_rn(a, po[(part0 + j) * g * d + o], acc); + l = (same && isfinite(__fadd_rn(l, pl[(part0 + j) * g + hd]))) ? __fadd_rn(l, pl[(part0 + j) * g + hd]) : __fmaf_rn(a, pl[(part0 + j) * g + hd], l); } if (acc != acc) { // NaN: a replayed infinity (weighed in float64) may have met a factor of 0; again, kept acc = 0.f; diff --git a/zig/tests/contract/cuda_softmax_identity.zig b/zig/tests/contract/cuda_softmax_identity.zig new file mode 100644 index 00000000000..0f3263ba836 --- /dev/null +++ b/zig/tests/contract/cuda_softmax_identity.zig @@ -0,0 +1,248 @@ +//! Host bit-reference for CUDA's finite stable-max old-state rescale guard. +const std = @import("std"); + +const Style = enum { plain, plain_exp2, legacy_equal_exp2, fused, two_products, two_products_exp2 }; +const State = struct { m: f32, l: f32, o: f32 }; +const Case = struct { + old: State, + new_m: f32, + part_m: f32, + new_l: f32, + new_o: f32, +}; +const Site = struct { name: []const u8, style: Style }; + +const sites = [_]Site{ + .{ .name = "block and sparse decode", .style = .fused }, + .{ .name = "idol decode and prompt", .style = .two_products }, + .{ .name = "prefill and row-prefill", .style = .two_products }, + .{ .name = "tree tiles with masks", .style = .two_products }, + .{ .name = "window decode and verify", .style = .two_products }, + .{ .name = "window rows and split merge", .style = .two_products }, + .{ .name = "common MLA tiles", .style = .fused }, + .{ .name = "FlashNext tile/chunk/chart", .style = .two_products }, + .{ .name = "Nemotron chunk and prefetch", .style = .fused }, + .{ .name = "paged segmented attention", .style = .fused }, + .{ .name = "Qwen scalar/KV8/draft/MTP", .style = .plain }, + .{ .name = "Qwen tensor decode/verify", .style = .fused }, + .{ .name = "Qwen chunk merges", .style = .fused }, + .{ .name = "Inkling decode/prompt folds", .style = .two_products_exp2 }, + .{ .name = "H3 exp2 verify", .style = .plain_exp2 }, + .{ .name = "MiniMax exp2 tile", .style = .legacy_equal_exp2 }, + .{ .name = "Drama attention/codec/merge", .style = .plain }, + .{ .name = "GLM DFlash folds/merge", .style = .plain }, + .{ .name = "Muse decode/DFlash/merge", .style = .plain }, + .{ .name = "Moss and Qwen vision", .style = .plain }, + .{ .name = "HY4 sink and MLA merge", .style = .plain }, +}; + +const controlled_sources = [_][]const u8{ + @embedFile("../../kernels/cuda/attn_fold.cuh"), + @embedFile("../../kernels/cuda/common/mla.cuh"), + @embedFile("../../kernels/cuda/drama3_attn.cuh"), + @embedFile("../../kernels/cuda/drama3_codec.cu"), + @embedFile("../../kernels/cuda/flashnext_attn.cu"), + @embedFile("../../kernels/cuda/glm_dflash.cu"), + @embedFile("../../kernels/cuda/glm_glue_attn.cuh"), + @embedFile("../../kernels/cuda/h3_attention.cuh"), + @embedFile("../../kernels/cuda/hy4_flash/attention_sink.cu"), + @embedFile("../../kernels/cuda/idol_attention.cuh"), + @embedFile("../../kernels/cuda/idol_decoder_attention.cuh"), + @embedFile("../../kernels/cuda/inkling2/attention.cu"), + @embedFile("../../kernels/cuda/inkling2/prompt_attention.cu"), + @embedFile("../../kernels/cuda/minimax_m3_attn.cu"), + @embedFile("../../kernels/cuda/moss_image_encoder.cu"), + @embedFile("../../kernels/cuda/muse_spark/attention.cu"), + @embedFile("../../kernels/cuda/muse_spark/dflash.cu"), + @embedFile("../../kernels/cuda/nemotron_attention.cu"), + @embedFile("../../kernels/cuda/paged_attn_segs.cuh"), + @embedFile("../../kernels/cuda/prefill_attention.cu"), + @embedFile("../../kernels/cuda/prefill_attention_rows.cuh"), + @embedFile("../../kernels/cuda/qwen35.cu"), + @embedFile("../../kernels/cuda/qwen35_attn.cuh"), + @embedFile("../../kernels/cuda/qwen35_attn_tc.cuh"), + @embedFile("../../kernels/cuda/qwen35_draft.cu"), + @embedFile("../../kernels/cuda/qwen35_draft_frame.cuh"), + @embedFile("../../kernels/cuda/qwen35_kv8.cu"), + @embedFile("../../kernels/cuda/qwen36_mtp.cu"), + @embedFile("../../kernels/cuda/qwen_vision.cu"), + @embedFile("../../kernels/cuda/tree_attention.cu"), + @embedFile("../../kernels/cuda/window_attention.cu"), + @embedFile("../../kernels/cuda/window_rows.cuh"), + @embedFile("../../kernels/cuda/window_split.cuh"), +}; + +test "CUDA identity source inventory has default-on compile-time controls" { + const header = @embedFile("../../kernels/cuda/common/softmax_identity.cuh"); + try std.testing.expect(std.mem.indexOf(u8, header, "#define TF_CUDA_SOFTMAX_IDENTITY_GUARD 1") != null); + const flag = "TF_CUDA_SOFTMAX_IDENTITY_GUARD"; + inline for (controlled_sources) |text| { + try std.testing.expect(std.mem.indexOf(u8, text, "softmax_identity.cuh") != null); + try std.testing.expect(std.mem.indexOf(u8, text, flag ++ " && ") != null); + } +} + +fn bits(x: f32) u32 { + return @bitCast(x); +} + +fn fromBits(x: u32) f32 { + return @bitCast(x); +} + +fn sameBits(a: State, b: State) bool { + return bits(a.m) == bits(b.m) and bits(a.l) == bits(b.l) and bits(a.o) == bits(b.o); +} + +fn expFor(comptime style: Style, x: f32) f32 { + return switch (style) { + .plain_exp2, .legacy_equal_exp2, .two_products_exp2 => @exp2(x), + else => @exp(x), + }; +} + +fn reference(c: Case, comptime style: Style) State { + @setFloatMode(.strict); + const a = if (style == .legacy_equal_exp2 and c.old.m == c.new_m) 1.0 else expFor(style, c.old.m - c.new_m); + const b = expFor(style, c.part_m - c.new_m); + return switch (style) { + .plain, .plain_exp2, .legacy_equal_exp2 => .{ .m = c.new_m, .l = c.old.l * a + c.new_l, .o = c.old.o * a + c.new_o }, + .fused => .{ .m = c.new_m, .l = @mulAdd(f32, c.old.l, a, c.new_l), .o = @mulAdd(f32, c.old.o, a, c.new_o) }, + .two_products, .two_products_exp2 => .{ .m = c.new_m, .l = c.old.l * a + c.new_l * b, .o = c.old.o * a + c.new_o * b }, + }; +} + +fn optimized(c: Case, comptime style: Style) State { + @setFloatMode(.strict); + const same = std.math.isFinite(c.new_m) and c.new_m == c.old.m; + const a = if (same or (style == .legacy_equal_exp2 and c.old.m == c.new_m)) 1.0 else expFor(style, c.old.m - c.new_m); + const b = expFor(style, c.part_m - c.new_m); + const fast: State = switch (style) { + .plain, .plain_exp2, .legacy_equal_exp2, .fused => .{ .m = c.new_m, .l = c.old.l + c.new_l, .o = c.old.o + c.new_o }, + .two_products, .two_products_exp2 => .{ .m = c.new_m, .l = c.old.l + c.new_l * b, .o = c.old.o + c.new_o * b }, + }; + const legacy: State = switch (style) { + .plain, .plain_exp2, .legacy_equal_exp2 => .{ .m = c.new_m, .l = c.old.l * a + c.new_l, .o = c.old.o * a + c.new_o }, + .fused => .{ .m = c.new_m, .l = @mulAdd(f32, c.old.l, a, c.new_l), .o = @mulAdd(f32, c.old.o, a, c.new_o) }, + .two_products, .two_products_exp2 => .{ .m = c.new_m, .l = c.old.l * a + c.new_l * b, .o = c.old.o * a + c.new_o * b }, + }; + return .{ .m = c.new_m, .l = if (same and std.math.isFinite(fast.l)) fast.l else legacy.l, .o = if (same and std.math.isFinite(fast.o)) fast.o else legacy.o }; +} + +// Deliberately broken control: equal infinities take the shortcut and lose the original NaNs. +pub fn plantedControl(c: Case) State { + const same = c.new_m == c.old.m; + const a = if (same) 1.0 else @exp(c.old.m - c.new_m); + return if (same) + .{ .m = c.new_m, .l = c.old.l + c.new_l, .o = c.old.o + c.new_o } + else + .{ .m = c.new_m, .l = @mulAdd(f32, c.old.l, a, c.new_l), .o = @mulAdd(f32, c.old.o, a, c.new_o) }; +} + +const nan = fromBits(0x7fc12345); +const pos_inf = std.math.inf(f32); +const neg_inf = -std.math.inf(f32); +const subnormal = fromBits(1); +const largest_subnormal = fromBits(0x007fffff); +const smallest_normal = fromBits(0x00800000); + +const cases = [_]Case{ + .{ .old = .{ .m = 3.5, .l = subnormal, .o = -0.0 }, .new_m = 3.5, .part_m = 3.5, .new_l = largest_subnormal, .new_o = 0.0 }, + .{ .old = .{ .m = -0.0, .l = -0.0, .o = subnormal }, .new_m = 0.0, .part_m = -0.0, .new_l = 0.0, .new_o = smallest_normal }, + .{ .old = .{ .m = -17.25, .l = 0x1.921fb6p1, .o = -9.75 }, .new_m = -17.25, .part_m = -20.0, .new_l = 0x1p-120, .new_o = -0.0 }, + .{ .old = .{ .m = 1.0, .l = 2.5, .o = -7.0 }, .new_m = 2.0, .part_m = 2.0, .new_l = 1.0, .new_o = 11.0 }, + .{ .old = .{ .m = 2.0, .l = 2.5, .o = -7.0 }, .new_m = nan, .part_m = neg_inf, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = nan, .l = 2.5, .o = -7.0 }, .new_m = nan, .part_m = nan, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = pos_inf, .l = 2.5, .o = -7.0 }, .new_m = pos_inf, .part_m = pos_inf, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = neg_inf, .l = 0.0, .o = 0.0 }, .new_m = neg_inf, .part_m = neg_inf, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = 2.0, .l = 2.5, .o = -7.0 }, .new_m = pos_inf, .part_m = neg_inf, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = 2.0, .l = 2.5, .o = -7.0 }, .new_m = neg_inf, .part_m = neg_inf, .new_l = 0.0, .new_o = 0.0 }, + .{ .old = .{ .m = 2.0, .l = nan, .o = -0.0 }, .new_m = 2.0, .part_m = 2.0, .new_l = 1.0, .new_o = nan }, + .{ .old = .{ .m = 2.0, .l = 2.5, .o = pos_inf }, .new_m = 2.0, .part_m = 2.0, .new_l = nan, .new_o = neg_inf }, +}; + +fn checkStyle(comptime style: Style) !void { + for (cases) |c| { + const want = reference(c, style); + const got = optimized(c, style); + try std.testing.expect(sameBits(want, got)); + } +} + +test "CUDA identity guard is bit-equal for all arithmetic families" { + try checkStyle(.plain); + try checkStyle(.plain_exp2); + try checkStyle(.fused); + try checkStyle(.legacy_equal_exp2); + try checkStyle(.two_products); + try checkStyle(.two_products_exp2); +} + +test "CUDA served decode verify prompt tree split and merge variants" { + for (sites) |site| switch (site.style) { + .plain => for (cases) |c| try std.testing.expect(sameBits(reference(c, .plain), optimized(c, .plain))), + .plain_exp2 => for (cases) |c| try std.testing.expect(sameBits(reference(c, .plain_exp2), optimized(c, .plain_exp2))), + .legacy_equal_exp2 => for (cases) |c| try std.testing.expect(sameBits(reference(c, .legacy_equal_exp2), optimized(c, .legacy_equal_exp2))), + .fused => for (cases) |c| try std.testing.expect(sameBits(reference(c, .fused), optimized(c, .fused))), + .two_products => for (cases) |c| try std.testing.expect(sameBits(reference(c, .two_products), optimized(c, .two_products))), + .two_products_exp2 => for (cases) |c| try std.testing.expect(sameBits(reference(c, .two_products_exp2), optimized(c, .two_products_exp2))), + }; +} + +test "planted nonfinite-max control fails against the pre-guard arithmetic" { + const c = cases[6]; + try std.testing.expect(!sameBits(reference(c, .fused), plantedControl(c))); +} + +test "CUDA identity keeps incoming-product FMA and rejects separated rounding" { + const weight: f32 = fromBits(0x3f800001); + const value: f32 = fromBits(0x3f7ffffe); + const old: f32 = fromBits(0x33800001); + const legacy = @mulAdd(f32, weight, value, old * 1.0); + const skipped = @mulAdd(f32, weight, value, old); + const wrong = weight * value + old; + try std.testing.expectEqual(bits(legacy), bits(skipped)); + try std.testing.expect(bits(legacy) != bits(wrong)); + const source = @embedFile("../../kernels/cuda/qwen35_attn.cuh"); + try std.testing.expect(std.mem.indexOf(u8, source, "? fmaf(b, bf(vb[i]), o[i]) : fmaf(b, bf(vb[i]), o[i] * a)") != null); +} + +test "CUDA identity preserves MiniMax's legacy equal-nonfinite factor" { + const body = @embedFile("../../kernels/cuda/minimax_m3_attn.cu"); + try std.testing.expect(std.mem.indexOf(u8, body, "const float f0 = m0 == mx0 ? 1.f : exp2f(m0 - mx0)") != null); +} +fn unsafe(text: []const u8) bool { + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (std.mem.indexOf(u8, line, "same") != null and std.mem.indexOf(u8, line, "rowsum(") != null) return true; + } + return false; +} +test "CUDA identity full-mask row sums precede every row-dependent identity arm" { + const body = @embedFile("../../kernels/cuda/prefill_attention_rows.cuh"); + try std.testing.expect(!unsafe(body)); + const sum = std.mem.indexOf(u8, body, "const float sum0 = rowsum(c0), sum1 = rowsum(c1);") orelse return error.MissingUnconditionalSum; + const guard = std.mem.indexOf(u8, body, "l0 = (same0") orelse return error.MissingIdentityGuard; + try std.testing.expect(sum < guard); + try std.testing.expect(unsafe("l0 = (same0 && isfinite(rowsum(c0))) ? rowsum(c0) : 0;")); +} +test "CUDA identity pure rescale retains nonfinite accumulator operations" { + const body = @embedFile("../../kernels/cuda/attn_fold.cuh"); + try std.testing.expect(std.mem.indexOf(u8, body, "!same0 || !isfinite(o[i][0])") != null); + try std.testing.expect(std.mem.indexOf(u8, body, "!same1 || !isfinite(o[i][3])") != null); + try std.testing.expect(std.mem.indexOf(u8, body, "l0 = (same0 && isfinite(__fadd_rn(l0, c0)))") != null); + try std.testing.expect(std.mem.indexOf(u8, body, "l1 = (same1 && isfinite(__fadd_rn(l1, c1)))") != null); +} + +test "CUDA identity guards never contain warp or block collectives" { + for (controlled_sources) |source| { + var lines = std.mem.splitScalar(u8, source, '\n'); + while (lines.next()) |line| { + if (std.mem.indexOf(u8, line, "same") == null) continue; + if (std.mem.indexOf(u8, line, "?") == null and std.mem.indexOf(u8, line, "if (") == null) continue; + for ([_][]const u8{ "rowsum(", "warp_sum(", "warp_max(", "__shfl", "__syncwarp", "__syncthreads" }) |call| { + try std.testing.expect(std.mem.indexOf(u8, line, call) == null); + } + } + } +} diff --git a/zig/tests/cuda/contract_block_attn.zig b/zig/tests/cuda/contract_block_attn.zig index bc343b99382..3043f209da5 100644 --- a/zig/tests/cuda/contract_block_attn.zig +++ b/zig/tests/cuda/contract_block_attn.zig @@ -107,6 +107,7 @@ pub const Block = struct { .nonfinite => self.plant(), .stress => try self.stress(rng), } + if (fill == .random) self.identityPlant(); const table = try a.alloc(i64, 2 * self.ns); defer a.free(table); for (self.ctx.items, 0..) |x, j| { @@ -119,6 +120,40 @@ pub const Block = struct { return true; } + /// Reserved finite A/B: context-tile maxima rise 0, 1, 2 then tie, and the own tile raises theirs again. + fn identityPlant(self: *Block) void { + const L = self.len(); + const row = L - 1; + const s0 = self.ctxLen(0); + const lo = if (s0 + row > window) s0 + row - window else 0; + const k0 = self.ctx.items[0][0 .. hk * s0 * D]; + const v0 = self.ctx.items[0][hk * s0 * D ..]; + @memset(self.q.items[row * D ..][0..D], 0); + self.q.items[row * D] = c.toBf16(1); + for (lo..s0) |key| { + const t = key / 32 - lo / 32; + const score: f32 = @floatFromInt(@min(t, 2)); + k0[key * D] = c.toBf16(score); + const v = v0[key * D ..][0..D]; + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = c.toBf16(if (t % 2 == 0) @as(f32, 1) else -2); + v[5] = c.toBf16(if (key % 2 == 0) @as(f32, 3) else -3); + } + for (0..L) |col| { + self.kb.items[col * D] = c.toBf16(3); + const v = self.vb.items[col * D ..][0..D]; + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = c.toBf16(1); + v[5] = c.toBf16(if (col % 2 == 0) @as(f32, 3) else -3); + } + } + fn ctxLen(self: *const Block, j: usize) usize { return @intCast(self.lens.items[j]); } diff --git a/zig/tests/cuda/contract_drama3_attn.zig b/zig/tests/cuda/contract_drama3_attn.zig new file mode 100644 index 00000000000..65dbe792e0c --- /dev/null +++ b/zig/tests/cuda/contract_drama3_attn.zig @@ -0,0 +1,385 @@ +//! Drama 3 direct/split gated attention under the raw-output contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const aref = core.act_ref; +const attention_ref = core.attention_ref; + +const H = 16; +const D3_D = 256; +const D3_KV = 2; +const D3_PS = 9216; +const D3_SPLITS = 16; +const d3_scale = 0.0625; + +/// Both projection layouts and changed decode paths are covered; controls omit the newest key only during launch. +pub const D3Form = enum { + decode_backbone, + decode_tower, + split_backbone, + split_tower, + decode_control, + split_control, + + fn split(f: D3Form) bool { + return f == .split_backbone or f == .split_tower or f == .split_control; + } + + fn tower(f: D3Form) bool { + return f == .decode_tower or f == .split_tower; + } + + fn control(f: D3Form) bool { + return f == .decode_control or f == .split_control; + } +}; + +/// k sets pos0 = k - rows; decode is one row and split shapes exercise accepted causal rows up to max_split_rows. +const d3_served = [_]c.Shape{ + .{ .rows = 1, .n = H, .k = 511 }, + .{ .rows = 1, .n = H, .k = 1 }, + .{ .rows = 1, .n = H, .k = 9 }, + .{ .rows = 1, .n = H, .k = 128 }, + .{ .rows = 4, .n = H, .k = 132 }, + .{ .rows = 1, .n = H, .k = 4096 }, +}; + +fn d3Depth(s: c.Shape) usize { + return D3_D + s.k + s.k / 8 + D3_SPLITS + 16; +} + +fn d3Spec(f: D3Form) c.Spec { + const name = switch (f) { + .decode_backbone => "cuda drama3 d3_attn_decode, backbone gate layout", + .decode_tower => "cuda drama3 d3_attn_decode, tower gate layout", + .split_backbone => "cuda drama3 d3_attn_partial + d3_attn_merge, backbone gate layout", + .split_tower => "cuda drama3 d3_attn_partial + d3_attn_merge, tower gate layout", + .decode_control => "control: drama3 direct decode omits the newest key", + .split_control => "control: drama3 split decode omits the newest key", + }; + return .{ + .name = name, + .accum = .f32, + .depth = d3Depth, + .ops = 12, + .mids = 2, + .out = .bf16, + .served = &d3_served, + .sums = .{ .why = "bf16 Q/K/V, online softmax partials and their merge reduce in fp32" }, + }; +} + +fn bf(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); +} + +pub const D3Attention = struct { + rig: rig_.Rig, + form: D3Form, + decode_fn: cuda.Function, + partial_fn: cuda.Function, + merge_fn: cuda.Function, + ref: ?attn.Ref = null, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + pos0: usize = 0, + q: []u16 = &.{}, + keys: []u16 = &.{}, + values: []u16 = &.{}, + proj: []u16 = &.{}, + dev: [5]u64 = @splat(0), + pml: u64 = 0, + pacc: u64 = 0, + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn init(rig: rig_.Rig, form: D3Form, mod: cuda.Module) !D3Attention { + return .{ + .rig = rig, + .form = form, + .decode_fn = try mod.function("d3_attn_decode"), + .partial_fn = try mod.function("d3_attn_partial"), + .merge_fn = try mod.function("d3_attn_merge"), + }; + } + + pub fn deinit(self: *D3Attention) void { + self.clear(); + self.rig.deinit(); + } + + fn clear(self: *D3Attention) void { + if (self.ref) |*r| r.deinit(); + self.ref = null; + const a = self.rig.gpu.gpa; + inline for (.{ "q", "keys", "values", "proj" }) |name| { + a.free(@field(self, name)); + @field(self, name) = &.{}; + } + } + + pub fn kernel(self: *D3Attention) g.Kernel { + return .{ .spec = d3Spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control()) .shapes else null }; + } + + const vt = g.hooks(D3Attention); + + pub fn prepare(self: *D3Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != H or shape.rows == 0 or shape.k < shape.rows) return false; + if (self.form.split() and shape.rows > 8) return false; + self.clear(); + self.rig.reset(); + errdefer self.clear(); + self.shape = shape; + self.pos0 = shape.k - shape.rows; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.ref = try attn.Ref.init(a, D3_D, shape.k); + self.ref.?.out = .bf16; + self.q = try a.alloc(u16, shape.rows * H * D3_D); + self.keys = try a.alloc(u16, shape.k * D3_KV * D3_D); + self.values = try a.alloc(u16, shape.k * D3_KV * D3_D); + self.proj = try a.alloc(u16, shape.rows * D3_PS); + for (self.q) |*x| x.* = attn.normal(rng); + for (self.keys) |*x| x.* = attn.normal(rng); + for (self.values) |*x| x.* = attn.normal(rng); + for (self.proj) |*x| x.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.plantStress(rng), + } + if (fill == .random) self.plantAdversarial(); + self.dev[0] = try self.rig.input(std.mem.sliceAsBytes(self.q)); + self.dev[1] = try self.rig.input(std.mem.sliceAsBytes(self.keys)); + self.dev[2] = try self.rig.input(std.mem.sliceAsBytes(self.values)); + self.dev[3] = try self.rig.input(std.mem.sliceAsBytes(self.proj)); + const launch_pos: i32 = if (self.form.control() and self.pos0 == 0) -1 else @intCast(self.pos0 - @intFromBool(self.form.control())); + const pos = [1]i32{launch_pos}; + self.dev[4] = try self.rig.input(std.mem.sliceAsBytes(&pos)); + if (self.form.split()) { + const slots = shape.rows * H * D3_SPLITS; + self.pml = try self.rig.scratch(slots * 2 * @sizeOf(f32)); + self.pacc = try self.rig.scratch(slots * D3_D * @sizeOf(f32)); + } + self.out = try self.rig.output(self.count() * @sizeOf(u16)); + return true; + } + + fn gateIndex(self: *const D3Attention, row: usize, head: usize, e: usize) usize { + return row * D3_PS + (if (self.form.tower()) D3_D * H + head * D3_D else D3_D + head * 2 * D3_D) + e; + } + + fn qAt(self: *D3Attention, row: usize, head: usize) []u16 { + return self.q[(row * H + head) * D3_D ..][0..D3_D]; + } + + fn cacheAt(self: *D3Attention, values: bool, pos: usize, head: usize) []u16 { + const x = if (values) self.values else self.keys; + return x[(pos * D3_KV + head) * D3_D ..][0..D3_D]; + } + + /// NaN in one query, cancelling infinities in one value column and a positive infinity in another. + fn plantNonfinite(self: *D3Attention) void { + self.qAt(0, 0)[3] = 0x7fc0; + const second = @min(1, self.shape.k - 1); + self.cacheAt(true, 0, 0)[7] = 0x7f80; + self.cacheAt(true, second, 0)[7] = 0xff80; + self.cacheAt(true, self.shape.k - 1, 1)[9] = 0x7f80; + self.proj[self.gateIndex(0, H - 1, 11)] = 0x7fc0; + } + + /// Equal scores make weights one; mirrored values fill the live prefix and later keys zero for exact fp32 sums. + fn plantStress(self: *D3Attention, rng: std.Random) !void { + @memset(self.q, 0); + @memset(self.keys, 0); + @memset(self.proj, 0); + const a = self.rig.gpu.gpa; + const col = try a.alloc(f32, self.shape.k); + defer a.free(col); + @memset(col, 0); + const live = @min(self.shape.k, 2048); + for (0..D3_KV) |h| for (0..D3_D) |e| { + attn.mirrored(rng, col[0..live]); + for (0..self.shape.k) |p| self.cacheAt(true, p, h)[e] = c.toBf16(col[p]); + }; + } + + /// The last row ties two maxima then two larger maxima in direct and split merges; special BF16 bits reach Q/K/V. + fn plantAdversarial(self: *D3Attention) void { + const row = self.shape.rows - 1; + const q = self.qAt(row, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.shape.k) |p| @memset(self.cacheAt(false, p, 0), 0); + const chunk = (self.shape.k + D3_SPLITS - 1) / D3_SPLITS; + const p0 = 0; + const p1 = @min(if (self.form.split()) chunk else 1, self.shape.k - 1); + const p2 = @min(if (self.form.split()) 2 * chunk else 8, self.shape.k - 1); + const p3 = @min(if (self.form.split()) 3 * chunk else 9, self.shape.k - 1); + var previous = p0; + for ([4]usize{ p0, p1, p2, p3 }, 0..) |p, i| { + if (i > 0 and p == previous) continue; + previous = p; + const changed = i >= 2; + const k = self.cacheAt(false, p, 0); + k[0] = c.toBf16(if (changed) 32 else 16); + k[1] = 0x8000; + k[2] = 0x0001; + k[3] = 0x8001; + k[4] = 0x007f; + k[5] = 0x807f; + const v = self.cacheAt(true, p, 0); + v[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + self.proj[self.gateIndex(row, 0, 0)] = 0; + } + + pub fn run(self: *D3Attention) !void { + if (self.form.split()) { + var a: cuda.Args = .{}; + for (self.dev[0..3]) |x| a.add(x); + a.add(self.dev[4]); + a.add(self.pml); + a.add(self.pacc); + try cuda.launch.launch(self.partial_fn, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = H, .z = D3_SPLITS }, .block = .{ .x = 256 } }, self.rig.s, &a); + var b: cuda.Args = .{}; + b.add(self.pml); + b.add(self.pacc); + b.add(@as(c_int, D3_SPLITS)); + b.add(self.dev[3]); + b.add(@as(c_int, D3_PS)); + b.add(@as(c_int, if (self.form.tower()) H * D3_D else D3_D)); + b.add(@as(c_int, if (self.form.tower()) D3_D else 2 * D3_D)); + b.add(self.out); + try cuda.launch.launch(self.merge_fn, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = H, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &b); + } else { + var a: cuda.Args = .{}; + for (self.dev[0..3]) |x| a.add(x); + a.add(self.dev[4]); + a.add(self.dev[3]); + a.add(@as(c_int, D3_PS)); + a.add(@as(c_int, if (self.form.tower()) H * D3_D else D3_D)); + a.add(@as(c_int, if (self.form.tower()) D3_D else 2 * D3_D)); + a.add(self.out); + try cuda.launch.launch(self.decode_fn, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = H, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + try self.rig.s.synchronize(); + } + + pub fn count(self: *D3Attention) usize { + return self.shape.rows * H * D3_D; + } + + fn heads(self: *D3Attention) usize { + return self.shape.rows * H; + } + + /// output head i: row i / H, head i % H, causal keys zero through pos0 + row. + pub fn load(self: *D3Attention, i: usize, h: *attn.Head) !void { + const row = i / H; + const head = i % H; + const kh = head / 8; + const src = self.q[(row * H + head) * D3_D ..][0..D3_D]; + for (h.q, src) |*dst, x| dst.* = c.fromBf16(x); + h.n = self.pos0 + row + 1; + for (0..h.n) |p| for (0..D3_D) |e| { + h.k[p * D3_D + e] = c.fromBf16(self.keys[(p * D3_KV + kh) * D3_D + e]); + h.v[p * D3_D + e] = c.fromBf16(self.values[(p * D3_KV + kh) * D3_D + e]); + }; + } + + fn gate(self: *const D3Attention, output: usize, e: usize) f64 { + const row = output / H; + const head = output % H; + return c.fromBf16(self.proj[self.gateIndex(row, head, e)]); + } + + fn applyGate(self: *const D3Attention, out: []f64, mag: ?[]f64) void { + for (out, 0..) |*x, i| { + const sg = bf(aref.sigmoid(self.gate(i / D3_D, i % D3_D))); + x.* = bf(bf(x.*) * sg); + if (mag) |m| m[i] = bf(m[i] * @abs(sg)); + } + } + + /// The float64 attention endpoints, then the kernel's BF16 attention, BF16 sigmoid and BF16 output. + pub fn check(self: *D3Attention, at: g.Gate) !?[]const u8 { + const r = &self.ref.?; + const out = try self.rig.outputBytes(); + var planted: usize = 0; + for (0..self.heads()) |i| { + try self.load(i, &r.head); + attention_ref.head(r.head.q, r.head.k, r.head.v, r.keys[0..r.head.n], D3_D, d3_scale, r.want, r.tol); + for (0..D3_D) |e| { + const sg = bf(aref.sigmoid(self.gate(i, e))); + const want = bf(bf(r.want[e]) * sg); + const got = c.fromBf16(std.mem.readInt(u16, out[2 * (i * D3_D + e) ..][0..2], .little)); + if (c.classOf(want) != .finite) planted += 1; + if (c.classOf(got) != c.classOf(want)) return try std.fmt.bufPrint(&self.msg, "head {d} element {d}: {t} where float64 gives {t}", .{ i, e, c.classOf(got), c.classOf(want) }); + if (at != .nonfinite and std.math.isFinite(want)) { + const allow = @abs(sg) * r.tol[e] + aref.tolerance(want); + if (!(@abs(got - want) <= allow)) return try std.fmt.bufPrint(&self.msg, "head {d} element {d} is {e:.6} where float64 gives {e:.6}: {d:.2} of its bound", .{ i, e, got, want, @abs(got - want) / allow }); + } + } + } + if (at == .nonfinite and (planted == 0 or planted == self.count())) return try std.fmt.bufPrint(&self.msg, "the planted values make {d} of {d} outputs non-finite: no proof", .{ planted, self.count() }); + return null; + } + + pub fn reference(self: *D3Attention, want: []f64, mag: []f64) !void { + try self.ref.?.reference(self, self.heads(), d3_scale, want, mag); + self.applyGate(want, mag); + } + + pub fn simulate(self: *D3Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.ref.?.simulate(self, self.heads(), d3_scale, acc, order, out); + self.applyGate(out, null); + } +}; + +const d3_forms = [_]D3Form{ .decode_backbone, .decode_tower, .split_backbone, .split_tower, .decode_control, .split_control }; + +/// The real CUDA symbols and every registration, at stable addresses owned for the whole gate/raw run. +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + items: [d3_forms.len]D3Attention = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.drama3); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&self.items, d3_forms) |*x, form| { + x.* = try D3Attention.init(rig, form, self.mod.?); + self.made += 1; + try kernels.append(a, x.kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*x| x.deinit(); + if (self.mod) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_drama3_codec_attn.zig b/zig/tests/cuda/contract_drama3_codec_attn.zig new file mode 100644 index 00000000000..02d6b0877e3 --- /dev/null +++ b/zig/tests/cuda/contract_drama3_codec_attn.zig @@ -0,0 +1,302 @@ +//! Drama 3 codec causal/windowed attention under the raw-output contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; + +const H = 16; +const CODEC_D = 64; +const CODEC_WIDTH = H * CODEC_D; +const CODEC_QKV = 3 * CODEC_WIDTH; +const codec_scale = 0.125; + +/// Encoder uses 512-wide history, decoder prefill/ring use 128; stream k = pos0 + rows, otherwise k = rows. +pub const CodecForm = enum { + encoder512, + decoder_prefill128, + decoder_stream128, + stream_control, + + fn window(f: CodecForm) usize { + return if (f == .encoder512) 512 else 128; + } + + fn stream(f: CodecForm) bool { + return f == .decoder_stream128 or f == .stream_control; + } + + fn control(f: CodecForm) bool { + return f == .stream_control; + } +}; + +const codec_encoder = [_]c.Shape{ + .{ .rows = 8, .n = H, .k = 8 }, + .{ .rows = 1, .n = H, .k = 1 }, + .{ .rows = 17, .n = H, .k = 17 }, + .{ .rows = 128, .n = H, .k = 128 }, + .{ .rows = 512, .n = H, .k = 512 }, +}; +const codec_prefill = [_]c.Shape{ + .{ .rows = 8, .n = H, .k = 8 }, + .{ .rows = 1, .n = H, .k = 1 }, + .{ .rows = 128, .n = H, .k = 128 }, + .{ .rows = 129, .n = H, .k = 129 }, + .{ .rows = 257, .n = H, .k = 257 }, +}; +const codec_stream = [_]c.Shape{ + .{ .rows = 8, .n = H, .k = 520 }, + .{ .rows = 1, .n = H, .k = 1 }, + .{ .rows = 4, .n = H, .k = 130 }, + .{ .rows = 4, .n = H, .k = 514 }, + .{ .rows = 8, .n = H, .k = 1540 }, +}; + +fn codecDepth(s: c.Shape) usize { + return CODEC_D + @min(s.k, 512) + 16; +} + +fn codecSpec(f: CodecForm) c.Spec { + return .{ + .name = switch (f) { + .encoder512 => "cuda drama3 codec c_attn, encoder full causal 512", + .decoder_prefill128 => "cuda drama3 codec c_attn, decoder prefill causal 128", + .decoder_stream128 => "cuda drama3 codec c_attn, decoder windowed 512-row ring", + .stream_control => "control: drama3 codec c_attn starts its window one key late", + }, + .accum = .f32, + .depth = codecDepth, + .ops = 8, + .out = .f32, + .served = switch (f) { + .encoder512 => &codec_encoder, + .decoder_prefill128 => &codec_prefill, + .decoder_stream128, .stream_control => &codec_stream, + }, + .sums = .{ .why = "fp32 Q/K/V and one-warp online softmax reductions" }, + }; +} + +pub const CodecAttention = struct { + rig: rig_.Rig, + form: CodecForm, + f: cuda.Function, + ref: ?attn.Ref = null, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + pos0: usize = 0, + ring: usize = 0, + qkv: []f32 = &.{}, + keys: []f32 = &.{}, + values: []f32 = &.{}, + dev: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn init(rig: rig_.Rig, form: CodecForm, mod: cuda.Module) !CodecAttention { + return .{ .rig = rig, .form = form, .f = try mod.function("c_attn") }; + } + + pub fn deinit(self: *CodecAttention) void { + self.clear(); + self.rig.deinit(); + } + + fn clear(self: *CodecAttention) void { + if (self.ref) |*r| r.deinit(); + self.ref = null; + const a = self.rig.gpu.gpa; + inline for (.{ "qkv", "keys", "values" }) |name| { + a.free(@field(self, name)); + @field(self, name) = &.{}; + } + } + + pub fn kernel(self: *CodecAttention) g.Kernel { + return .{ .spec = codecSpec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control()) .shapes else null }; + } + + const vt = g.hooks(CodecAttention); + + pub fn prepare(self: *CodecAttention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != H or shape.rows == 0 or shape.k < shape.rows) return false; + self.clear(); + self.rig.reset(); + errdefer self.clear(); + self.shape = shape; + self.pos0 = shape.k - shape.rows; + self.ring = if (self.form.stream()) 512 else shape.k; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.ref = try attn.Ref.init(a, CODEC_D, @min(shape.k, self.form.window())); + self.ref.?.out = .f32; + self.qkv = try a.alloc(f32, shape.rows * CODEC_QKV); + self.keys = try a.alloc(f32, self.ring * CODEC_WIDTH); + self.values = try a.alloc(f32, self.ring * CODEC_WIDTH); + for (self.qkv) |*x| x.* = rng.floatNorm(f32); + for (self.keys) |*x| x.* = rng.floatNorm(f32); + for (self.values) |*x| x.* = rng.floatNorm(f32); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.plantStress(rng), + } + if (fill == .random) self.plantAdversarial(); + self.dev[0] = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.dev[1] = try self.rig.input(std.mem.sliceAsBytes(self.keys)); + self.dev[2] = try self.rig.input(std.mem.sliceAsBytes(self.values)); + self.out = try self.rig.output(self.count() * @sizeOf(f32)); + return true; + } + + fn qAt(self: *CodecAttention, row: usize, head: usize) []f32 { + return self.qkv[row * CODEC_QKV + head * CODEC_D ..][0..CODEC_D]; + } + + fn cacheAt(self: *CodecAttention, values: bool, pos: usize, head: usize) []f32 { + const x = if (values) self.values else self.keys; + return x[(pos % self.ring) * CODEC_WIDTH + head * CODEC_D ..][0..CODEC_D]; + } + + fn plantNonfinite(self: *CodecAttention) void { + self.qAt(0, 0)[3] = std.math.nan(f32); + const p = self.pos0 + self.shape.rows - 1; + self.cacheAt(true, p, 8)[7] = std.math.inf(f32); + if (p > 0) self.cacheAt(true, p - 1, 8)[7] = -std.math.inf(f32); + self.cacheAt(true, p, 15)[9] = std.math.inf(f32); + } + + fn plantStress(self: *CodecAttention, rng: std.Random) !void { + for (0..self.shape.rows) |row| for (0..H) |h| @memset(self.qAt(row, h), 0); + @memset(self.keys, 0); + const a = self.rig.gpu.gpa; + const col = try a.alloc(f32, self.ring); + defer a.free(col); + for (0..H) |h| for (0..CODEC_D) |e| { + attn.mirrored(rng, col); + for (0..self.ring) |p| self.values[p * CODEC_WIDTH + h * CODEC_D + e] = col[p]; + }; + } + + /// The last row ties one-warp scores then changes the maximum; special values reach Q/K/V at wrapped ring rows. + fn plantAdversarial(self: *CodecAttention) void { + const row = self.shape.rows - 1; + const q = self.qAt(row, 0); + @memset(q, 0); + q[0] = 1; + q[1] = -0.0; + q[2] = @bitCast(@as(u32, 1)); + q[3] = @bitCast(@as(u32, 0x80000001)); + q[4] = @bitCast(@as(u32, 0x007fffff)); + q[5] = @bitCast(@as(u32, 0x807fffff)); + for (0..self.ring) |p| @memset(self.keys[p * CODEC_WIDTH ..][0..CODEC_D], 0); + const pos = self.pos0 + row; + const n = @min(pos + 1, self.form.window()); + const first = pos + 1 - n; + const p0 = first; + const p1 = first + @min(8, n - 1); + const p2 = first + @min(16, n - 1); + for ([3]usize{ p0, p1, p2 }, 0..) |p, i| { + if (i > 0 and p == @as(usize, if (i == 1) p0 else p1)) continue; + const changed = if (p2 != p1) i == 2 else i == 1; + const k = self.cacheAt(false, p, 0); + k[0] = if (changed) 16 else 8; + k[1] = -0.0; + k[2] = @bitCast(@as(u32, 1)); + k[3] = @bitCast(@as(u32, 0x80000001)); + k[4] = @bitCast(@as(u32, 0x007fffff)); + k[5] = @bitCast(@as(u32, 0x807fffff)); + const v = self.cacheAt(true, p, 0); + v[0] = if (i == 0) 1 else if (changed) 5 else 3; + v[1] = if (i == 0) -0.0 else 0.0; + v[2] = @bitCast(if (i == 0) @as(u32, 1) else @as(u32, 0x80000001)); + v[3] = @bitCast(if (i == 0) @as(u32, 0x80000001) else @as(u32, 0x007fffff)); + v[4] = @bitCast(if (i == 0) @as(u32, 0x007fffff) else @as(u32, 0x807fffff)); + } + } + + pub fn run(self: *CodecAttention) !void { + var a: cuda.Args = .{}; + for (self.dev) |x| a.add(x); + a.add(self.out); + a.add(@as(c_int, @intCast(self.pos0))); + a.add(@as(c_int, @intCast(self.form.window() - @intFromBool(self.form.control())))); + a.add(@as(c_int, @intCast(self.ring))); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = 2, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *CodecAttention) usize { + return self.shape.rows * CODEC_WIDTH; + } + + fn heads(self: *CodecAttention) usize { + return self.shape.rows * H; + } + + pub fn load(self: *CodecAttention, i: usize, h: *attn.Head) !void { + const row = i / H; + const head = i % H; + const src = self.qkv[row * CODEC_QKV + head * CODEC_D ..][0..CODEC_D]; + for (h.q, src) |*dst, x| dst.* = x; + const pos = self.pos0 + row; + const n = @min(pos + 1, self.form.window()); + const first = pos + 1 - n; + h.n = n; + for (0..n) |j| { + const p = first + j; + const at = (p % self.ring) * CODEC_WIDTH + head * CODEC_D; + for (0..CODEC_D) |e| { + h.k[j * CODEC_D + e] = self.keys[at + e]; + h.v[j * CODEC_D + e] = self.values[at + e]; + } + } + } + + pub fn check(self: *CodecAttention, at: g.Gate) !?[]const u8 { + return self.ref.?.check(self, self.heads(), codec_scale, try self.rig.outputBytes(), at); + } + + pub fn reference(self: *CodecAttention, want: []f64, mag: []f64) !void { + return self.ref.?.reference(self, self.heads(), codec_scale, want, mag); + } + + pub fn simulate(self: *CodecAttention, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.ref.?.simulate(self, self.heads(), codec_scale, acc, order, out); + } +}; + +const codec_forms = [_]CodecForm{ .encoder512, .decoder_prefill128, .decoder_stream128, .stream_control }; + +/// Codec module and registrations, owned at stable addresses for the whole gate/raw run. +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + items: [codec_forms.len]CodecAttention = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.drama3_codec); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&self.items, codec_forms) |*x, form| { + x.* = try CodecAttention.init(rig, form, self.mod.?); + self.made += 1; + try kernels.append(a, x.kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*x| x.deinit(); + if (self.mod) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_dump.zig b/zig/tests/cuda/contract_dump.zig index cd17ac02671..6d31299dce6 100644 --- a/zig/tests/cuda/contract_dump.zig +++ b/zig/tests/cuda/contract_dump.zig @@ -1,4 +1,4 @@ -//! One finite prepared launch per registered served form, separate from the unchanged contract verdicts. +//! Raw identities for finite, nonfinite and stress launches, separate from the contract verdicts. const std = @import("std"); const contract = @import("core").contract; const dump = @import("byte_dump.zig"); @@ -7,8 +7,8 @@ pub fn run(a: std.mem.Allocator, kernels: []const contract.gates.Kernel) !void { if (!dump.active()) return; for (kernels) |kernel| { if (kernel.control != null) continue; - for (kernel.spec.served, 0..) |shape, form| { - if (!try kernel.vt.prepare(kernel.ctx, shape, .random, 0x6b63)) return error.DumpShapeRefused; + for (kernel.spec.served, 0..) |shape, form| for ([_]contract.gates.Fill{ .random, .nonfinite, .stress }) |fill| { + if (!try kernel.vt.prepare(kernel.ctx, shape, fill, 0x6b63)) return error.DumpShapeRefused; try kernel.vt.run(kernel.ctx); if (!try kernel.vt.intact(kernel.ctx)) return error.DumpGuard; if (kernel.vt.overlap(kernel.ctx) and !kernel.spec.in_place) return error.DumpOverlap; @@ -20,7 +20,7 @@ pub fn run(a: std.mem.Allocator, kernels: []const contract.gates.Kernel) !void { .f32 => .f32, .raw => .raw, }; - try dump.output(a, "kernel-contract", kernel.spec.name, "outputs", &.{count}, dtype, .{ .form = form, .served = shape, .seed = @as(u64, 0x6b63) }, bytes); - } + try dump.output(a, "kernel-contract", kernel.spec.name, @tagName(fill), &.{if (fill == .nonfinite) bytes.len else count}, if (fill == .nonfinite) .raw else dtype, .{ .form = form, .served = shape, .fill = @tagName(fill), .output_type = @tagName(dtype), .seed = @as(u64, 0x6b63) }, bytes); + }; } } diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 85bbdb62f36..6b14a70edea 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -39,6 +39,19 @@ pub const Sets = struct { topk_rows: *@import("contract_topk_rows.zig").Set, sparse_index: *@import("contract_sparse_index.zig").Set, sparse_attn: *@import("contract_sparse_attn.zig").Set, + drama3_attn: *@import("contract_drama3_attn.zig").Group, + drama3_codec_attn: *@import("contract_drama3_codec_attn.zig").Group, + qwen35_draft_attn: *@import("contract_qwen35_draft_attn.zig").Group, + glm_dflash_attn: *@import("contract_glm_dflash_attn.zig").Group, + glm_chunks_fp8: *@import("contract_glm_chunks_fp8.zig").Group, + hy4_chunks: *@import("contract_hy4_chunks.zig").Group, + prefill_full_ab: *@import("contract_prefill_full_ab.zig").Group, + qwen_prompt_ab: *@import("contract_qwen_prompt_ab.zig").Group, + flashnext_attn_ab: *@import("contract_flashnext_attn_ab.zig").Group, + nemo_direct_attn: *@import("contract_nemo_direct_attn.zig").Group, + qwen_pages_ab: *@import("contract_qwen_pages_ab.zig").Group, + qwen_tc_ab: *@import("contract_qwen_tc_ab.zig").Group, + qwen_tree_ab: *@import("contract_qwen_tree_ab.zig").Group, /// Each set's kernels appended to `list`, in this order. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel), affine4: *cuda.qlinear.Affine4Kernels, cap: u32) !Sets { @@ -99,7 +112,9 @@ pub const Sets = struct { const idol = try @import("contract_idol.zig").Set.init(gpu, s, a, list); errdefer idol.deinit(); const idol_decoder = try @import("contract_idol_decoder.zig").Set.init(gpu, s, a, list); + errdefer idol_decoder.deinit(); const glm_moe = try @import("contract_glm_moe_direct.zig").Set.init(gpu, s, a, list); + errdefer glm_moe.deinit(); const zonos3, const hy4_ihc_hc = try initPair( @import("contract_zonos3.zig").Set, @import("contract_hy4_hc.zig").Set, @@ -114,6 +129,33 @@ pub const Sets = struct { errdefer topk_rows.deinit(); errdefer sparse_index.deinit(); const sparse_attn = try @import("contract_sparse_attn.zig").Set.init(gpu, s, a, list); + errdefer sparse_attn.deinit(); + const drama3_attn = try @import("contract_drama3_attn.zig").Group.create(a, gpu, s, list); + errdefer drama3_attn.destroy(); + const drama3_codec_attn = try @import("contract_drama3_codec_attn.zig").Group.create(a, gpu, s, list); + errdefer drama3_codec_attn.destroy(); + const qwen35_draft_attn = try @import("contract_qwen35_draft_attn.zig").Group.create(a, .{ .gpu = gpu, .s = s }, list); + errdefer qwen35_draft_attn.destroy(); + const glm_dflash_attn = try @import("contract_glm_dflash_attn.zig").Group.create(a, .{ .gpu = gpu, .s = s }, list); + errdefer glm_dflash_attn.destroy(); + const glm_chunks_fp8 = try @import("contract_glm_chunks_fp8.zig").Group.create(a, gpu, s, list); + errdefer glm_chunks_fp8.destroy(); + const hy4_chunks = try @import("contract_hy4_chunks.zig").Group.create(a, gpu, s, list); + errdefer hy4_chunks.destroy(); + const prefill_full_ab = try @import("contract_prefill_full_ab.zig").Group.create(a, gpu, s, list); + errdefer prefill_full_ab.destroy(); + const qwen_prompt_ab = try @import("contract_qwen_prompt_ab.zig").Group.create(a, gpu, s, list); + errdefer qwen_prompt_ab.destroy(); + const flashnext_attn_ab = try @import("contract_flashnext_attn_ab.zig").Group.create(a, gpu, s, list); + errdefer flashnext_attn_ab.destroy(); + const nemo_direct_attn = try @import("contract_nemo_direct_attn.zig").Group.create(a, gpu, s, list); + errdefer nemo_direct_attn.destroy(); + const qwen_pages_ab = try @import("contract_qwen_pages_ab.zig").Group.create(a, gpu, s, list); + errdefer qwen_pages_ab.destroy(); + const qwen_tc_ab = try @import("contract_qwen_tc_ab.zig").Group.create(a, gpu, s, list); + errdefer qwen_tc_ab.destroy(); + const qwen_tree_ab = try @import("contract_qwen_tree_ab.zig").Group.create(a, gpu, s, list); + errdefer qwen_tree_ab.destroy(); return .{ .gpa = gpu.gpa, .bf16_experts = bf16_experts, @@ -144,6 +186,19 @@ pub const Sets = struct { .topk_rows = topk_rows, .sparse_index = sparse_index, .sparse_attn = sparse_attn, + .drama3_attn = drama3_attn, + .drama3_codec_attn = drama3_codec_attn, + .qwen35_draft_attn = qwen35_draft_attn, + .glm_dflash_attn = glm_dflash_attn, + .glm_chunks_fp8 = glm_chunks_fp8, + .hy4_chunks = hy4_chunks, + .prefill_full_ab = prefill_full_ab, + .qwen_prompt_ab = qwen_prompt_ab, + .flashnext_attn_ab = flashnext_attn_ab, + .nemo_direct_attn = nemo_direct_attn, + .qwen_pages_ab = qwen_pages_ab, + .qwen_tc_ab = qwen_tc_ab, + .qwen_tree_ab = qwen_tree_ab, }; } @@ -154,6 +209,19 @@ pub const Sets = struct { sets.hy4_ihc_hc.deinit(); sets.zonos3.deinit(); sets.glm_moe.deinit(); + sets.qwen_tree_ab.destroy(); + sets.qwen_tc_ab.destroy(); + sets.qwen_pages_ab.destroy(); + sets.nemo_direct_attn.destroy(); + sets.flashnext_attn_ab.destroy(); + sets.qwen_prompt_ab.destroy(); + sets.prefill_full_ab.destroy(); + sets.hy4_chunks.destroy(); + sets.glm_chunks_fp8.destroy(); + sets.glm_dflash_attn.destroy(); + sets.qwen35_draft_attn.destroy(); + sets.drama3_codec_attn.destroy(); + sets.drama3_attn.destroy(); sets.idol_decoder.deinit(); sets.idol.deinit(); sets.joint_schema.deinit(); diff --git a/zig/tests/cuda/contract_flashnext_attn_ab.zig b/zig/tests/cuda/contract_flashnext_attn_ab.zig new file mode 100644 index 00000000000..bea2c0f4a43 --- /dev/null +++ b/zig/tests/cuda/contract_flashnext_attn_ab.zig @@ -0,0 +1,530 @@ +//! Raw identity A/B coverage for FlashNext's direct attention programs and their PO/PM/PL state. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const flash = @import("flashnext"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const G = 12; +const HD = 256; +const DI = 128; +const CH = 512; +const IDW = 2052; +const DENSE_KEYS = 2051; +const SCALE: f32 = 0.0625; +const NCH_SPARSE = 5; +const NCH_DENSE = 3; + +const Mode = enum { chunks, one, ahead, fused, fused_paged, one_paged, ahead_paged }; +const modes = [_]Mode{ .chunks, .ahead, .fused, .fused_paged, .one_paged, .ahead_paged }; + +fn sparse(shape: c.Shape) bool { + return shape.n == 2 or shape.n == 4; +} + +fn qsa(shape: c.Shape) bool { + return shape.n != 1; +} + +fn ptok(shape: c.Shape) usize { + return if (shape.n >= 3) 512 else 48; +} + +fn paged(mode: Mode) bool { + return switch (mode) { + .fused_paged, .one_paged, .ahead_paged => true, + else => false, + }; +} + +fn fused(mode: Mode) bool { + return mode == .fused or mode == .fused_paged; +} + +fn ahead(mode: Mode) bool { + return mode == .ahead or mode == .ahead_paged; +} + +fn baseline(mode: Mode) ?Mode { + return switch (mode) { + .chunks, .one => null, + .ahead => .chunks, + .fused => .one, + .fused_paged => .fused, + .one_paged => .one, + .ahead_paged => .ahead, + }; +} + +fn replacement(mode: Mode) ?[]const u8 { + return switch (mode) { + .chunks, .one => null, + .ahead => "fn_attn_chunks", + .fused => "fn_attn_chunks_one then fn_attn_merge", + .fused_paged => "fn_attn_fused", + .one_paged => "fn_attn_chunks_one", + .ahead_paged => "fn_attn_chunks_ahead", + }; +} + +fn depth(_: c.Shape) usize { + return 0; +} + +const short = [_]c.Shape{ + .{ .rows = 4, .n = 1, .k = 33 }, + .{ .rows = 1, .n = 1, .k = 1 }, + .{ .rows = 16, .n = 1, .k = 512 }, + .{ .rows = 16, .n = 1, .k = 511 }, + .{ .rows = 4, .n = 2, .k = 0 }, + .{ .rows = 1, .n = 2, .k = 33 }, + .{ .rows = 16, .n = 2, .k = 511 }, + .{ .rows = 16, .n = 2, .k = 1025 }, +}; +const wide = short ++ [_]c.Shape{ + .{ .rows = 17, .n = 1, .k = 31 }, + .{ .rows = 256, .n = 1, .k = 32 }, + .{ .rows = 17, .n = 2, .k = 513 }, + .{ .rows = 256, .n = 2, .k = 2049 }, +}; +const fused_shapes = wide ++ [_]c.Shape{ + .{ .rows = 257, .n = 1, .k = 33 }, + .{ .rows = 1024, .n = 1, .k = 32 }, + .{ .rows = 257, .n = 2, .k = 1025 }, + .{ .rows = 1024, .n = 2, .k = 65 }, +}; +const paged_short = short ++ [_]c.Shape{ + .{ .rows = 4, .n = 3, .k = 513 }, + .{ .rows = 4, .n = 4, .k = 0 }, + .{ .rows = 16, .n = 4, .k = 1025 }, +}; +const paged_wide = paged_short ++ wide[short.len..] ++ [_]c.Shape{ + .{ .rows = 256, .n = 3, .k = 32 }, + .{ .rows = 256, .n = 4, .k = 513 }, +}; +const paged_fused = fused_shapes ++ [_]c.Shape{ + .{ .rows = 4, .n = 3, .k = 513 }, + .{ .rows = 4, .n = 4, .k = 0 }, + .{ .rows = 16, .n = 4, .k = 1025 }, + .{ .rows = 1024, .n = 4, .k = 65 }, +}; +const control_shapes = [_]c.Shape{ + .{ .rows = 4, .n = 1, .k = 97 }, + .{ .rows = 4, .n = 2, .k = 1025 }, +}; + +fn served(mode: Mode) []const c.Shape { + return switch (mode) { + .chunks, .one => &wide, + .ahead => &short, + .fused => &fused_shapes, + .fused_paged => &paged_fused, + .one_paged => &paged_wide, + .ahead_paged => &paged_short, + }; +} + +const Bind = struct { + q: u64 = 0, + kc: u64 = 0, + vc: u64 = 0, + pos: u64 = 0, + po: u64 = 0, + pm: u64 = 0, + pl: u64 = 0, + out: u64 = 0, + ids: u64 = 0, + nk: u64 = 0, + spr: u64 = 0, + pg: flash.Pg = .{}, +}; + +const Host = struct { + q: []u16, + key: []u16, + value: []u16, + ids: []i32, + nk: []i32, + spr: []i32, + pos: [4]i32, + pages: []u16, + table: []i32, + bad_table: []i32, +}; + +const Fns = struct { + chunks: cuda.Function, + one: cuda.Function, + ahead: cuda.Function, + fused: cuda.Function, + fused_paged: cuda.Function, + one_paged: cuda.Function, + ahead_paged: cuda.Function, + merge: cuda.Function, +}; + +const Runner = struct { + rig: rig_.Rig, + base: rig_.Rig, + fns: *const Fns, + mode: Mode, + half: bool = false, + control: bool = false, + shape: c.Shape = undefined, + label: [160]u8 = undefined, + arena: ?std.heap.ArenaAllocator = null, + dev: Bind = .{}, + base_dev: Bind = .{}, + host: Host = undefined, + output_len: usize = 0, + + fn deinit(self: *Runner) void { + self.rig.deinit(); + self.base.deinit(); + if (self.arena) |*a| a.deinit(); + } + + fn qh(self: *const Runner) usize { + return if (self.half) 12 else 24; + } + + fn kh(self: *const Runner) usize { + return if (self.half) 1 else 2; + } + + fn kernel(self: *Runner) g.Kernel { + const base = if (self.control) + "control: cuda fn_attn_chunks_ahead_paged with a rotated page table" + else switch (self.mode) { + .chunks => "cuda FlashNext fn_attn_chunks raw PO PM PL", + .one => unreachable, + .ahead => "cuda FlashNext fn_attn_chunks_ahead raw PO PM PL", + .fused => "cuda FlashNext fn_attn_fused raw output", + .fused_paged => "cuda FlashNext fn_attn_fused_paged raw output", + .one_paged => "cuda FlashNext fn_attn_chunks_one_paged raw PO PM PL", + .ahead_paged => "cuda FlashNext fn_attn_chunks_ahead_paged raw PO PM PL", + }; + const name = if (self.control) base else std.fmt.bufPrint(&self.label, "{s}, {d}/{d} heads", .{ base, self.qh(), self.kh() }) catch unreachable; + return .{ + .ctx = self, + .vt = &vt, + .control = if (self.control) .shapes else null, + .spec = .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = replacement(self.mode), + .nan = .{ .stated = "raw outputs and every unwritten partial-state byte, including NaN and infinities" }, + .served = if (self.control) &control_shapes else served(self.mode), + }, + }; + } + + const vt = g.hooks(Runner); + + fn valid(self: *const Runner, shape: c.Shape) bool { + if (shape.rows == 0 or shape.k > IDW or shape.n == 0 or shape.n > (if (paged(self.mode)) 4 else 2)) return false; + if (!sparse(shape) and shape.k == 0) return false; + const rows = if (fused(self.mode)) 1024 else if (ahead(self.mode)) 16 else 256; + return shape.rows <= rows; + } + + fn live(self: *const Runner, shape: c.Shape) usize { + _ = self; + return if (sparse(shape)) 2048 + shape.rows else shape.k - 1 + shape.rows; + } + + fn prepare(self: *Runner, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!self.valid(shape)) return false; + self.rig.reset(); + self.base.reset(); + if (self.arena) |*a| a.deinit(); + self.arena = .init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + self.shape = shape; + const cap = self.live(shape) + 4; + self.host = try self.makeHost(a, cap, fill, seed); + self.dev = try self.bind(&self.rig, self.mode, self.host, false); + const need_base = baseline(self.mode) != null; + self.base_dev = if (need_base) try self.bind(&self.base, baseline(self.mode).?, self.host, self.mode == .fused) else .{}; + self.output_len = if (fused(self.mode)) + shape.rows * self.qh() * HD * 2 + else + shape.rows * self.nch() * self.qh() * (HD + 2) * 4; + return true; + } + + fn makeHost(self: *Runner, a: std.mem.Allocator, cap: usize, fill: g.Fill, seed: u64) !Host { + const rows = self.shape.rows; + var random = std.Random.DefaultPrng.init(seed); + const rng = random.random(); + const q = try a.alloc(u16, rows * self.qh() * HD); + const key = try a.alloc(u16, cap * self.kh() * HD); + const value = try a.alloc(u16, key.len); + for (q) |*v| v.* = c.toBf16(if (fill == .stress) 0 else rng.float(f32) * 2 - 1); + for (key) |*v| v.* = c.toBf16(if (fill == .stress) 0 else rng.float(f32) * 2 - 1); + for (value, 0..) |*v, i| { + const token = i / (self.kh() * HD); + const d = i % HD; + const half = cap / 2; + const positive: f32 = if (token % 2 == 0) 127 else 16256; + const residual: f32 = if (token < 8 and token % 2 == 0) 1 else 0; + const stress_value = if (token < half) positive else residual - positive; + v.* = c.toBf16(if (fill == .stress) stress_value else rng.float(f32) * 2 - 1); + if (fill == .nonfinite and token == 0 and d < 3) v.* = ([_]u16{ 0x7fc0, 0x7f80, 0xff80 })[d]; + } + const ids = try a.alloc(i32, rows * IDW); + @memset(ids, -1); + const nk = try a.alloc(i32, rows); + const spr = try a.alloc(i32, rows); + for (0..rows) |r| { + nk[r] = @intCast(self.shape.k); + const dense_row = !sparse(self.shape) or (self.shape.k != 0 and rows > 1 and rows <= 256 and r % 3 == 1); + spr[r] = @intFromBool(qsa(self.shape) and sparse(self.shape) and !dense_row); + if (spr[r] != 0) { + for (0..self.shape.k) |j| ids[r * IDW + j] = @intCast(2048 + rows - 1 - j); + } + } + if (fill == .nonfinite) q[0] = 0x7fc1; + if (fill == .random) plant(self.shape, self.kh(), q, key, value, ids, nk, spr, cap); + const pos: [4]i32 = .{ @intCast(if (sparse(self.shape)) 2048 else self.shape.k - 1), 0, 0, 0 }; + const per = ptok(self.shape); + const np = @max(1, (cap + per - 1) / per); + const page_elems = per * (2 * self.kh() * HD + DI) + per / 4 * DI; + const pages = try a.alloc(u16, (np + 2) * page_elems); + @memset(pages, 0); + const table = try a.alloc(i32, np); + const bad = try a.alloc(i32, np); + for (0..np) |p| { + table[p] = @intCast(np - 1 - p); + bad[p] = @intCast((np - p) % np); + } + for (0..cap) |token| for (0..self.kh() * HD) |d| { + const physical: usize = @intCast(table[token / per]); + const at = physical * page_elems + token % per * self.kh() * HD + d; + pages[at] = key[token * self.kh() * HD + d]; + pages[at + per * self.kh() * HD] = value[token * self.kh() * HD + d]; + }; + return .{ .q = q, .key = key, .value = value, .ids = ids, .nk = nk, .spr = spr, .pos = pos, .pages = pages, .table = table, .bad_table = bad }; + } + + fn bind(self: *Runner, rig: *rig_.Rig, variant: Mode, host: Host, for_merge: bool) !Bind { + var b: Bind = .{}; + b.q = try rig.input(std.mem.sliceAsBytes(host.q)); + if (paged(variant)) { + b.kc = try rig.input(std.mem.sliceAsBytes(host.pages)); + b.vc = b.kc + ptok(self.shape) * self.kh() * HD * 2; + const table = if (self.control and variant == self.mode) host.bad_table else host.table; + b.pg = .{ .pt = try rig.input(std.mem.sliceAsBytes(table)), .ps = @intCast(host.pages.len / (host.table.len + 2)), .ptok = @intCast(ptok(self.shape)) }; + } else { + b.kc = try rig.input(std.mem.sliceAsBytes(host.key)); + b.vc = try rig.input(std.mem.sliceAsBytes(host.value)); + } + b.pos = try rig.input(std.mem.asBytes(&host.pos)); + b.ids = try rig.input(std.mem.sliceAsBytes(host.ids)); + b.nk = try rig.input(std.mem.sliceAsBytes(host.nk)); + b.spr = try rig.input(std.mem.sliceAsBytes(host.spr)); + const chunks = self.nch(); + if (fused(variant) or for_merge) b.out = try rig.output(self.shape.rows * self.qh() * HD * 2); + if (for_merge) { + b.po = try rig.scratch(self.shape.rows * chunks * self.qh() * HD * 4); + b.pm = try rig.scratch(self.shape.rows * chunks * self.qh() * 4); + b.pl = try rig.scratch(self.shape.rows * chunks * self.qh() * 4); + } else if (!fused(variant)) { + b.po = try rig.output(self.shape.rows * chunks * self.qh() * HD * 4); + b.pm = try rig.output(self.shape.rows * chunks * self.qh() * 4); + b.pl = try rig.output(self.shape.rows * chunks * self.qh() * 4); + } + return b; + } + + fn nch(self: *const Runner) usize { + return if (qsa(self.shape) or fused(self.mode)) NCH_SPARSE else NCH_DENSE; + } + + fn function(self: *const Runner, mode: Mode) cuda.Function { + return switch (mode) { + .chunks => self.fns.chunks, + .one => self.fns.one, + .ahead => self.fns.ahead, + .fused => self.fns.fused, + .fused_paged => self.fns.fused_paged, + .one_paged => self.fns.one_paged, + .ahead_paged => self.fns.ahead_paged, + }; + } + + fn launch(self: *Runner, rig: *rig_.Rig, b: Bind, variant: Mode) !void { + var args: cuda.Args = .{}; + for ([_]u64{ b.q, b.kc, b.vc, b.pos }) |p| args.add(p); + if (fused(variant)) { + args.add(b.out); + } else for ([_]u64{ b.po, b.pm, b.pl }) |p| args.add(p); + for ([_]u64{ b.ids, b.nk, b.spr }) |p| args.add(p); + args.add(@as(c_int, @intCast(self.qh()))); + args.add(@as(c_int, @intCast(self.kh()))); + args.add(@as(c_int, G)); + args.add(@as(c_int, CH)); + if (!fused(variant)) args.add(@as(c_int, @intCast(self.nch()))); + args.add(SCALE); + args.add(@as(c_int, IDW)); + args.add(@as(c_int, @intFromBool(qsa(self.shape) or fused(self.mode)))); + if (paged(variant)) args.add(b.pg); + const chunks = (@min(self.live(self.shape), DENSE_KEYS) + CH - 1) / CH; + const shared: usize = switch (variant) { + .chunks => 43520, + .ahead, .ahead_paged => 77312, + else => 26624, + }; + try cuda.launch.launch(self.function(variant), .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast(self.kh()), .z = @intCast(if (fused(variant)) 1 else chunks) }, .block = .{ .x = 128 }, .shared = @intCast(shared) }, rig.s, &args); + if (variant == .one and fused(self.mode)) { + args = .{}; + for ([_]u64{ b.po, b.pm, b.pl, b.pos, b.out, b.nk, b.spr }) |p| args.add(p); + for ([_]c_int{ @intCast(self.qh()), @intCast(self.kh()), G, CH, @intCast(self.nch()), 1 }) |v| args.add(v); + try cuda.launch.launch(self.fns.merge, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast(self.qh()) }, .block = .{ .x = HD } }, rig.s, &args); + } + try rig.s.synchronize(); + } + + fn run(self: *Runner) !void { + try self.launch(&self.rig, self.dev, self.mode); + } + + fn replaced(self: *Runner) ![]const u8 { + const mode = baseline(self.mode) orelse return error.NoReplacement; + try self.launch(&self.base, self.base_dev, mode); + if (!try self.base.intact() or self.base.overlap()) return error.ReplacementGuard; + return self.base.outputBytes(); + } + + fn count(self: *const Runner) usize { + return self.output_len; + } + + fn reference(_: *Runner, _: []f64, _: []f64) !void { + return error.RawIdentityUsesReplacementOrBytes; + } + + fn tally(value: f64, finite: *usize, exceptional: *usize) void { + if (c.classOf(value) == .finite) finite.* += 1 else exceptional.* += 1; + } + + fn f32At(bytes: []const u8, bias: usize, index: usize) f32 { + return @bitCast(std.mem.readInt(u32, bytes[bias + 4 * index ..][0..4], .little)); + } + + fn check(self: *Runner, at: g.Gate) !?[]const u8 { + if (at != .nonfinite) return null; + const bytes = try self.rig.outputBytes(); + var finite: usize = 0; + var exceptional: usize = 0; + if (fused(self.mode)) { + for (0..self.output_len / 2) |i| { + const bits = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + tally(c.fromBf16(bits), &finite, &exceptional); + } + } else { + const po_values = self.shape.rows * self.nch() * self.qh() * HD; + const state_values = self.shape.rows * self.nch() * self.qh(); + for (0..self.shape.rows) |r| { + const keys: usize = if (self.host.spr[r] != 0) + @intCast(self.host.nk[r]) + else + @intCast(self.host.pos[0] + @as(i32, @intCast(r)) + 1); + for (0..(keys + CH - 1) / CH) |chunk| for (0..self.qh()) |head| { + const base = (r * self.nch() + chunk) * self.qh() + head; + for (0..HD) |d| tally(f32At(bytes, 0, base * HD + d), &finite, &exceptional); + tally(f32At(bytes, po_values * 4, base), &finite, &exceptional); + tally(f32At(bytes, (po_values + state_values) * 4, base), &finite, &exceptional); + }; + } + } + if (finite == 0 or exceptional == 0) return "nonfinite plants must leave both finite and exceptional written outputs"; + return null; + } +}; + +fn plant(shape: c.Shape, kv: usize, q: []u16, key: []u16, value: []u16, ids: []i32, nk: []const i32, spr: []const i32, cap: usize) void { + @memset(q[0..HD], 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + @memset(key, 0); + const points = [_]usize{ 31, 32, 63, 64, 65, 511, 512 }; + for (points, 0..) |j, i| { + if (j >= nk[0] and spr[0] != 0) continue; + if (j >= shape.k and spr[0] == 0) continue; + const source: usize = if (spr[0] != 0) @intCast(ids[j]) else j; + if (source >= cap) continue; + const k = key[source * kv * HD ..][0..HD]; + @memset(k, 0); + k[0] = c.toBf16(if (j == 65) 32 else 16); + k[1] = if (i % 2 == 0) 0x8000 else 0; + k[2] = if (i % 2 == 0) 0x0001 else 0x8001; + k[3] = 0x807f; + const v = value[source * kv * HD ..][0..HD]; + v[0] = c.toBf16(@floatFromInt(1 + 2 * i)); + v[1] = 0x8000; + v[2] = 0x0001; + v[3] = 0x8001; + v[4] = 0x007f; + v[5] = 0x807f; + } +} + +/// Both served head geometries for six primary symbols, plus a real rotated-page control. +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + fns: Fns = undefined, + items: [2 * modes.len + 1]Runner = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.flashnext_attn); + const m = self.mod.?; + self.fns = .{ + .chunks = try m.function("fn_attn_chunks"), + .one = try m.function("fn_attn_chunks_one"), + .ahead = try m.function("fn_attn_chunks_ahead"), + .fused = try m.function("fn_attn_fused"), + .fused_paged = try m.function("fn_attn_fused_paged"), + .one_paged = try m.function("fn_attn_chunks_one_paged"), + .ahead_paged = try m.function("fn_attn_chunks_ahead_paged"), + .merge = try m.function("fn_attn_merge"), + }; + try self.fns.chunks.allowDynamicShared(43520); + try self.fns.one.allowDynamicShared(26624); + try self.fns.ahead.allowDynamicShared(77312); + try self.fns.fused.allowDynamicShared(26624); + try self.fns.fused_paged.allowDynamicShared(26624); + try self.fns.one_paged.allowDynamicShared(26624); + try self.fns.ahead_paged.allowDynamicShared(77312); + for (modes) |mode| for ([_]bool{ false, true }) |half| try self.add(gpu, s, mode, half, false, kernels); + try self.add(gpu, s, .ahead_paged, false, true, kernels); + return self; + } + + fn add(self: *Group, gpu: check.Gpu, s: cuda.Stream, mode: Mode, half: bool, control: bool, kernels: *std.ArrayList(g.Kernel)) !void { + self.items[self.made] = .{ .rig = .{ .gpu = gpu, .s = s }, .base = .{ .gpu = gpu, .s = s }, .fns = &self.fns, .mode = mode, .half = half, .control = control }; + self.made += 1; + try kernels.append(self.a, self.items[self.made - 1].kernel()); + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + if (self.mod) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_glm_attn.zig b/zig/tests/cuda/contract_glm_attn.zig index b468b72ed54..16cdaf8ef75 100644 --- a/zig/tests/cuda/contract_glm_attn.zig +++ b/zig/tests/cuda/contract_glm_attn.zig @@ -122,6 +122,7 @@ pub const Chunks = struct { }; if (fill == .nonfinite and shape.rows > 1) self.cache[self.keys[shape.k] * lw + 9] = c.toBf16(std.math.inf(f32)); } + if (fill == .random) self.adversarial(); const n_pages = (span + pages.rows_a_page - 1) / pages.rows_a_page; self.ids = try pages.shuffled(a, rng, n_pages); const arena = try a.alloc(u8, (n_pages + 3) * pages.page_bytes); @@ -158,6 +159,33 @@ pub const Chunks = struct { return true; } + /// The fullest row has tied maxima in adjacent chunks, then a changed maximum, plus special bf16 bits in Q/K/V. + fn adversarial(self: *Chunks) void { + const r = self.shape.rows - 1; + const n = self.seen(r); + const q = self.q[(r * heads) * lw ..][0..lw]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..n) |i| @memset(self.cache[self.key(r, i) * lw ..][0..lw], 0); + const tile = @min(512, (n - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, n - 1) }; + for (spots, 0..) |i, which| { + const kv = self.cache[self.key(r, i) * lw ..][0..lw]; + kv[0] = c.toBf16(if (which < 2) 16 else 32); + kv[1] = 0x8000; + kv[2] = 0x0001; + kv[3] = 0x8001; + kv[4] = 0x007f; + kv[5] = 0x807f; + } + } + pub fn run(self: *Chunks) !void { const rows: i64 = @intCast(self.shape.rows); const w: i64 = if (self.form.sparse) @intCast(self.shape.k) else 0; diff --git a/zig/tests/cuda/contract_glm_chunks_fp8.zig b/zig/tests/cuda/contract_glm_chunks_fp8.zig new file mode 100644 index 00000000000..648888ef34f --- /dev/null +++ b/zig/tests/cuda/contract_glm_chunks_fp8.zig @@ -0,0 +1,301 @@ +//! GLM's real E4M3 chunk kernels: raw partials and their served merge under the identity A/B contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const glm = @import("glm_cuda"); +const rig_ = @import("contract_rig.zig"); +const pages = @import("contract_glm_pages.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lw = 512; +const heads = 32; +const chunk = 512; +const scale: f32 = 0.0625; +const e4m3 = core.quant.fp8.e4m3; + +pub const Form = struct { hb: u32, sparse: bool, control: bool = false }; +pub const forms = [_]Form{ + .{ .hb = 16, .sparse = false }, .{ .hb = 32, .sparse = false }, + .{ .hb = 16, .sparse = true }, .{ .hb = 32, .sparse = true }, + .{ .hb = 16, .sparse = false, .control = true }, +}; + +fn served(f: Form) []const c.Shape { + return if (f.hb == 16) (if (f.sparse) &.{.{ .rows = 8, .n = heads * lw, .k = glm.sparse.width }} else &.{.{ .rows = 8, .n = heads * lw, .k = 2 * chunk }}) else (if (f.sparse) &.{.{ .rows = 64, .n = heads * lw, .k = 300 }} else &.{.{ .rows = 64, .n = heads * lw, .k = chunk }}); +} + +fn depth(s: c.Shape) usize { + return lw + chunk + s.k / chunk + 1; +} + +fn noDepth(_: c.Shape) usize { + return 0; +} + +pub const Entry = struct { + rig: rig_.Rig, + f: cuda.Function, + merge: cuda.Function, + form: Form, + shape: c.Shape = undefined, + q: []u16 = &.{}, + codes: []u8 = &.{}, + scales: []f32 = &.{}, + tokens: []i32 = &.{}, + counts: []i32 = &.{}, + at: usize = 0, + nch: usize = 0, + dev: [6]u64 = @splat(0), // q, codes, scales, tokens, counts, position + parts: [3]u64 = @splat(0), + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn kernel(self: *Entry) g.Kernel { + const name = if (self.form.control) + "control: GLM FP8 chunks-16 scales multiplied by 1.5" + else if (self.form.sparse) + std.fmt.comptimePrint("cuda glm tf_glm_chunks_{d}_fp8 sparse raw numerator/maxima/mass + tf_glm_merge", .{self.form.hb}) + else + std.fmt.comptimePrint("cuda glm tf_glm_chunks_{d}_fp8 dense raw numerator/maxima/mass + tf_glm_merge", .{self.form.hb}); + return .{ .spec = .{ .name = name, .accum = .none, .depth = if (self.form.control) noDepth else depth, .out = .raw, .nan = .{ .stated = "raw FP8 partial bits are compared directly; merged BF16 classes match float64 and finite values meet the MLA bound, count-zero rows retain poison" }, .served = served(self.form) }, .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Entry); + + fn free(self: *Entry) void { + const a = self.rig.gpu.gpa; + inline for (.{ &self.q, &self.codes, &self.scales, &self.tokens, &self.counts }) |p| { + a.free(p.*); + p.* = &.{}; + } + } + pub fn deinit(self: *Entry) void { + self.free(); + self.rig.deinit(); + } + fn span(self: *const Entry) usize { + return if (self.form.sparse) glm.sparse.width else self.at + self.shape.rows; + } + fn seen(self: *const Entry, r: usize) usize { + return if (self.form.sparse) @intCast(self.counts[r]) else self.at + r + 1; + } + fn key(self: *const Entry, r: usize, i: usize) usize { + return if (self.form.sparse) @intCast(self.tokens[r * self.shape.k + i]) else i; + } + fn partialHeads(self: *const Entry) usize { + return self.nch * self.shape.rows * heads; + } + fn semanticCount(self: *const Entry) usize { + return self.shape.rows * heads * lw; + } + pub fn count(self: *Entry) usize { + return self.partialHeads() * (lw + 2) * 4 + self.semanticCount() * 2; + } + + fn putCode(v: f32) u8 { + var code: u8 = 0; + while (code < 0x7f) : (code += 1) if (e4m3(code) == @abs(v)) break; + return code | @as(u8, if (std.math.signbit(v)) 0x80 else 0); + } + + pub fn prepare(self: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != heads * lw or shape.k == 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.at = if (self.form.sparse) 0 else shape.k - @min(shape.k, shape.rows / 2); + self.nch = ((if (self.form.sparse) shape.k else self.at + shape.rows) + chunk - 1) / chunk; + self.q = try a.alloc(u16, shape.rows * heads * lw); + self.codes = try a.alloc(u8, self.span() * lw); + self.scales = try a.alloc(f32, self.span()); + self.tokens = try a.alloc(i32, shape.rows * shape.k); + self.counts = try a.alloc(i32, shape.rows); + for (self.q) |*x| x.* = c.toBf16(rng.float(f32) * 2 - 1); + for (self.codes) |*x| { + x.* = rng.int(u8); + if (x.* & 0x7f == 0x7f) x.* ^= 1; + } + for (self.scales) |*x| x.* = std.math.ldexp(@as(f32, 1), -@as(i32, @intCast(5 + rng.uintLessThan(u32, 4)))); + for (self.counts, 0..) |*x, r| x.* = if (self.form.sparse and r == 1 and shape.rows > 1) 0 else @intCast(shape.k); + for (self.tokens, 0..) |*x, i| x.* = @intCast((i * 4096 / shape.k + rng.uintLessThan(usize, 4096 / shape.k)) % self.span()); + if (fill == .nonfinite) { + self.q[3] = c.toBf16(std.math.nan(f32)); + if (self.form.sparse) { + // Keep key rows finite in every list: plants differ by query row and all other rows stay finite. + if (shape.rows > 2) self.q[2 * heads * lw + 4] = c.toBf16(std.math.inf(f32)); + if (shape.rows > 3) self.q[3 * heads * lw + 5] = c.toBf16(-std.math.inf(f32)); + } else { + // Only the fullest causal row sees the final key; earlier rows stay finite. + const last = self.span() - 1; + self.codes[last * lw + 9] = 0x7f; + self.scales[last] = std.math.inf(f32); + } + } + if (fill == .stress) { + for (self.codes, 0..) |*x, i| x.* = ([_]u8{ 0, 0x80, 1, 0x81, 2, 0x82, 0x7e, 0xfe })[i % 8]; + } + if (fill == .random) self.adversarial(); + const launch_scales = if (self.form.control) blk: { + const changed = try a.dupe(f32, self.scales); + for (changed) |*x| x.* *= 1.5; + break :blk changed; + } else self.scales; + defer if (self.form.control) a.free(launch_scales); + const p: i32 = @intCast(self.at); + self.dev = .{ + try self.rig.input(std.mem.sliceAsBytes(self.q)), try self.rig.input(self.codes), + try self.rig.input(std.mem.sliceAsBytes(launch_scales)), try self.rig.input(std.mem.sliceAsBytes(self.tokens)), + try self.rig.input(std.mem.sliceAsBytes(self.counts)), try self.rig.input(std.mem.asBytes(&p)), + }; + const n = self.partialHeads(); + self.parts = .{ try self.rig.output(n * lw * 4), try self.rig.output(n * 4), try self.rig.output(n * 4) }; + self.out = try self.rig.output(self.semanticCount() * 2); + return true; + } + + fn adversarial(self: *Entry) void { + const r = self.shape.rows - 1; + const n = self.seen(r); + const q = self.q[(r * heads) * lw ..][0..lw]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + const tile = @min(chunk, (n - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, n - 1) }; + for (0..n) |i| { + const row = self.key(r, i); + @memset(self.codes[row * lw ..][0..lw], 0); + self.scales[row] = 1; + } + for (spots, 0..) |i, which| { + const row = self.key(r, i); + const kv = self.codes[row * lw ..][0..lw]; + kv[0] = putCode(if (which < 2) 16 else 32); + kv[1] = 0x80; + kv[2] = 1; + kv[3] = 0x81; + } + } + + pub fn run(self: *Entry) !void { + const rows64: i64 = @intCast(self.shape.rows); + const w: i64 = if (self.form.sparse) @intCast(self.shape.k) else 0; + var args: cuda.Args = .{}; + inline for (.{ self.dev[0], self.dev[1], self.dev[2], self.dev[5], self.dev[3], self.dev[4], self.parts[0], self.parts[1], self.parts[2], rows64, @as(i64, heads), w, scale, @as(c_int, @intFromBool(self.form.sparse)) }) |x| args.add(x); + const shared = if (self.form.hb == 32) glm.glue.chunksSmem(32) else glm.glue.chunksSmem(16); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = (heads + self.form.hb - 1) / self.form.hb, .z = @intCast(self.nch) }, .block = .{ .x = 256 }, .shared = shared }, self.rig.s, &args); + var merge: cuda.Args = .{}; + inline for (.{ self.parts[0], self.parts[1], self.parts[2], self.out, self.dev[4], rows64, @as(i64, heads), @as(c_int, @intCast(self.nch)), @as(c_int, @intFromBool(self.form.sparse)) }) |x| merge.add(x); + try cuda.launch.launch(self.merge, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = heads }, .block = .{ .x = 128 } }, self.rig.s, &merge); + try self.rig.s.synchronize(); + } + + fn value(self: *const Entry, r: usize, i: usize, d: usize) f64 { + const row = self.key(r, i); + return c.fromBf16(c.toBf16(@floatCast(e4m3(self.codes[row * lw + d]) * self.scales[row]))); + } + fn attend(self: *const Entry, r: usize, h: usize, out: []f64, tol: []f64) !void { + const a = self.rig.gpu.gpa; + const n = self.seen(r); + const terms = try a.alloc(f64, 4 * n + lw); + defer a.free(terms); + const scores = terms[0..n]; + const ds = terms[n .. 2 * n]; + const p = terms[2 * n .. 3 * n]; + const col = terms[3 * n .. 4 * n]; + const products = terms[4 * n ..]; + var most = -std.math.inf(f64); + for (0..n) |i| { + var abs: f64 = 0; + for (products, 0..) |*x, d| { + x.* = c.fromBf16(self.q[(r * heads + h) * lw + d]) * self.value(r, i, d); + abs += @abs(x.*); + } + scores[i] = pages.sumIn(.none, .sequential, products) * scale; + ds[i] = abs * scale * 520 * 0x1p-24; + most = pages.maxNan(most, scores[i]); + } + for (p, scores) |*x, score| x.* = @exp(score - most); + const mass = pages.sumIn(.none, .sequential, p); + for (out, tol, 0..) |*o, *t, d| { + var spread: f64 = 0; + for (col, p, 0..) |*x, weight, i| { + const v = self.value(r, i, d); + x.* = weight * v; + spread += weight * @abs(v) * (0x1p-8 + ds[i]); + } + o.* = pages.sumIn(.none, .sequential, col) / mass; + t[d] = @abs(o.*) * 0x1p-8 + spread / mass + 1e-30; + } + } + + pub fn reference(_: *Entry, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + pub fn check(self: *Entry, gate: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const n = self.semanticCount(); + const want = try a.alloc(f64, 2 * n); + defer a.free(want); + const tol = want[n..]; + const raw = try self.rig.outputBytes(); + const merged = raw[self.partialHeads() * (lw + 2) * 4 ..]; + var planted: usize = 0; + var considered: usize = 0; + for (0..self.shape.rows) |r| { + if (self.form.sparse and self.counts[r] == 0) for (0..heads * lw) |i| { + const got = std.mem.readInt(u16, merged[(r * heads * lw + i) * 2 ..][0..2], .little); + if (got != 0xffff) return try std.fmt.bufPrint(&self.msg, "count-zero row {d} element {d} was not left alone", .{ r, i }); + } else for (0..heads) |h| { + const at = (r * heads + h) * lw; + try self.attend(r, h, want[at..][0..lw], tol[at..][0..lw]); + for (want[at..][0..lw], tol[at..][0..lw], 0..) |w, t, d| { + const got = c.read(.bf16, merged, at + d); + considered += 1; + if (c.classOf(w) != .finite) planted += 1; + if (c.classOf(got) != c.classOf(w)) return try std.fmt.bufPrint(&self.msg, "row {d} head {d} column {d}: {t} where float64 gives {t}", .{ r, h, d, c.classOf(got), c.classOf(w) }); + if (gate != .nonfinite and std.math.isFinite(w) and !(@abs(got - w) <= t)) return try std.fmt.bufPrint(&self.msg, "row {d} head {d} column {d}: error {e} exceeds {e}", .{ r, h, d, @abs(got - w), t }); + } + }; + } + if (gate == .nonfinite and (planted == 0 or planted == considered)) return try std.fmt.bufPrint(&self.msg, "planted non-finite values cover {d} of {d} outputs", .{ planted, considered }); + return null; + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + items: [forms.len]Entry = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.glm_glue); + const merge = try self.mod.?.function("tf_glm_merge"); + for (&self.items, forms) |*item, form| { + const f = try self.mod.?.function(if (form.hb == 16) "tf_glm_chunks_16_fp8" else "tf_glm_chunks_32_fp8"); + try f.allowDynamicShared(if (form.hb == 16) glm.glue.chunksSmem(16) else glm.glue.chunksSmem(32)); + item.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = f, .merge = merge, .form = form }; + self.made += 1; + try kernels.append(a, item.kernel()); + } + return self; + } + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + if (self.mod) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_glm_dflash_attn.zig b/zig/tests/cuda/contract_glm_dflash_attn.zig new file mode 100644 index 00000000000..193e47800ba --- /dev/null +++ b/zig/tests/cuda/contract_glm_dflash_attn.zig @@ -0,0 +1,322 @@ +//! GLM DFlash2 attention under the contract: the whole block kernel and the served 16-way split plus merge. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const hd = 128; +const heads = 32; +const kv_heads = 8; +const group = heads / kv_heads; +const width = kv_heads * hd; +const block = 8; +const window = 2048; +const chunks = 16; +const glm_scale: f32 = 0.08838834764831845; + +pub const Form = struct { split: bool, control: bool = false }; +pub const forms = [_]Form{ + .{ .split = false }, .{ .split = true }, + .{ .split = false, .control = true }, .{ .split = true, .control = true }, +}; + +/// rows is streams S (up to 16), n is query heads, k is stream 0's context; all begin 3 slots before the ring wrap. +const served = [_]c.Shape{ + .{ .rows = 8, .n = heads, .k = 257 }, .{ .rows = 1, .n = heads, .k = 0 }, + .{ .rows = 4, .n = heads, .k = 63 }, .{ .rows = 4, .n = heads, .k = 64 }, + .{ .rows = 4, .n = heads, .k = 65 }, .{ .rows = 4, .n = heads, .k = 255 }, + .{ .rows = 4, .n = heads, .k = 256 }, .{ .rows = 1, .n = heads, .k = 2047 }, + .{ .rows = 1, .n = heads, .k = 2048 }, .{ .rows = 16, .n = heads, .k = 300 }, + .{ .rows = 4, .n = heads, .k = 700 }, +}; + +fn depth(s: c.Shape) usize { + return @min(s.k + block - 1, window) + block + chunks; +} + +pub fn spec(f: Form) c.Spec { + const name = if (f.control) + (if (f.split) "control GLM DFlash2 split attention leaves its output unwritten" else "control GLM DFlash2 whole attention leaves its output unwritten") + else + (if (f.split) "cuda GLM DFlash2 served attention df_attn_part, df_attn_merge" else "cuda GLM DFlash2 whole-block attention df_attn"); + return .{ .name = name, .accum = .f32, .depth = depth, .ops = 3, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256 } }, .served = &served, .sums = .{ .why = attn.why } }; +} + +pub const Dflash = struct { + rig: rig_.Rig, + form: Form, + whole: cuda.Function, + part: cuda.Function, + merge: cuda.Function, + arena: std.heap.ArenaAllocator, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + q: []u16 = &.{}, + kb: []u16 = &.{}, + vb: []u16 = &.{}, + ring: []u16 = &.{}, + dq: u64 = 0, + dkb: u64 = 0, + dvb: u64 = 0, + dring: u64 = 0, + rings: u64 = 0, + starts: u64 = 0, + froms: u64 = 0, + partial: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn init(rig: rig_.Rig, form: Form, mod: cuda.Module) !Dflash { + return .{ .rig = rig, .form = form, .whole = try mod.function("df_attn"), .part = try mod.function("df_attn_part"), .merge = try mod.function("df_attn_merge"), .arena = .init(rig.gpu.gpa) }; + } + + pub fn deinit(self: *Dflash) void { + if (self.r) |*r| r.deinit(); + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Dflash) g.Kernel { + return .{ .spec = spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Dflash); + + fn rows(self: *const Dflash) usize { + return self.shape.rows * block; + } + fn context(self: *const Dflash, si: usize) usize { + return self.shape.k -| si * self.shape.k / self.shape.rows; + } + fn start(self: *const Dflash, si: usize) usize { + return window - 3 + self.context(si); + } + fn low(self: *const Dflash, m: usize) usize { + const si = m / block; + return @max(window - 3, self.start(si) + m % block -| (window - 1)); + } + fn ringTerms(self: *const Dflash, m: usize) usize { + return self.start(m / block) - self.low(m); + } + + fn term(self: *Dflash, m: usize, j: usize, kvh: usize, values: bool) []u16 { + const nr = self.ringTerms(m); + if (j < nr) { + const at = ((self.low(m) + j) % window) * width + kvh * hd; + return self.ring[at + @as(usize, if (values) window * width else 0) ..][0..hd]; + } + const r = m / block * block + j - nr; + const at = r * width + kvh * hd; + return (if (values) self.vb else self.kb)[at..][0..hd]; + } + + pub fn prepare(self: *Dflash, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + _ = self.arena.reset(.free_all); + if (shape.rows == 0 or shape.rows > 16 or shape.n != heads or shape.k > window) return false; + self.shape = shape; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(self.rig.gpu.gpa, hd, shape.k + 2 * block); + self.q = try a.alloc(u16, self.rows() * heads * hd); + self.kb = try a.alloc(u16, self.rows() * width); + self.vb = try a.alloc(u16, self.rows() * width); + self.ring = try a.alloc(u16, 2 * window * width); + for (self.q) |*x| x.* = attn.normal(rng); + for (self.kb) |*x| x.* = attn.normal(rng); + for (self.vb) |*x| x.* = attn.normal(rng); + for (self.ring) |*x| x.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + if (fill == .random) self.plantAdversarial(); + + self.dq = try self.rig.input(std.mem.sliceAsBytes(self.q)); + self.dkb = try self.rig.input(std.mem.sliceAsBytes(self.kb)); + self.dvb = try self.rig.input(std.mem.sliceAsBytes(self.vb)); + self.dring = try self.rig.input(std.mem.sliceAsBytes(self.ring)); + const rp = try a.alloc(u64, shape.rows); + const st = try a.alloc(i64, shape.rows); + const fr = try a.alloc(i64, shape.rows); + for (rp, st, fr, 0..) |*p, *s, *f, si| { + p.* = self.dring; + s.* = @intCast(self.start(si)); + f.* = @intCast(self.begin()); + } + self.rings = try self.rig.input(std.mem.sliceAsBytes(rp)); + self.starts = try self.rig.input(std.mem.sliceAsBytes(st)); + self.froms = try self.rig.input(std.mem.sliceAsBytes(fr)); + if (self.form.split) { + const slots = self.rows() * heads * chunks; + for (&self.partial, [_]usize{ 4, 4, 4 * hd }) |*p, w| p.* = try self.rig.scratch(slots * w); + } + self.out = try self.rig.output(self.rows() * heads * hd * 2); + return true; + } + + fn plantNonfinite(self: *Dflash) void { + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + self.q[3] = nan; + self.vb[7] = inf; + self.vb[hd + 9] = ninf; + self.vb[width + 11] = inf; + self.vb[2 * width + 11] = ninf; + self.kb[2 * width] = nan; + if (self.context(0) > 0) { + const last = self.start(0) - 1; + self.ring[(last % window) * width + hd + 5] = inf; + } + } + + /// Gate 4: zero scores everywhere, exact mirrored committed values and zero block values. + fn stress(self: *Dflash, rng: std.Random) !void { + const a = self.arena.allocator(); + @memset(self.q, 0); + @memset(self.kb, 0); + @memset(self.vb, 0); + @memset(self.ring, 0); + const col = try a.alloc(f32, self.shape.k); + defer a.free(col); + for (0..kv_heads) |kvh| for (0..hd) |e| { + attn.mirrored(rng, col); + for (0..self.shape.k) |j| { + const at = ((self.begin() + j) % window) * width + kvh * hd + e; + self.ring[window * width + at] = c.toBf16(col[j]); + } + }; + } + + /// Keys 0 and L = ceil(T / 16) tie across chunks; key 2L or the tail raises the maximum with special Q/K/V. + fn plantAdversarial(self: *Dflash) void { + const q = self.q[0..hd]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + const n = self.ringTerms(0) + block; + for (0..n) |j| self.term(0, j, 0, false)[0] = 0; + const l = (n + chunks - 1) / chunks; + const tie0 = 0; + const tie1 = @min(l, n - 1); + const changed = @min(2 * l, n - 1); + for ([2]usize{ tie0, tie1 }, 0..) |j, i| { + const k = self.term(0, j, 0, false); + const v = self.term(0, j, 0, true); + k[0] = c.toBf16(16); + k[1] = if (i == 0) 0x8000 else 0; + k[2] = if (i == 0) 0x0001 else 0x8001; + k[3] = if (i == 0) 0x807f else 0x007f; + v[0] = c.toBf16(if (i == 0) 1 else 3); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + const k = self.term(0, changed, 0, false); + const v = self.term(0, changed, 0, true); + k[0] = c.toBf16(32); + k[1] = 0x8000; + k[2] = 0x007f; + k[3] = 0x8001; + v[0] = c.toBf16(5); + v[1] = 0x8000; + v[2] = 0x0001; + v[3] = 0x807f; + } + + pub fn run(self: *Dflash) !void { + if (!self.form.control) { + var a: cuda.Args = .{}; + inline for (.{ self.dq, self.dkb, self.dvb, self.rings, self.starts, self.froms, @as(c_int, 0), glm_scale }) |v| a.add(v); + if (self.form.split) { + for (self.partial) |p| a.add(p); + try cuda.launch.launch(self.part, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = kv_heads, .z = chunks }, .block = .{ .x = 256 } }, self.rig.s, &a); + var m: cuda.Args = .{}; + inline for (.{ self.partial[0], self.partial[1], self.partial[2], self.out }) |v| m.add(v); + try cuda.launch.launch(self.merge, .{ .grid = .{ .x = @intCast(self.rows()), .y = heads }, .block = .{ .x = hd } }, self.rig.s, &m); + } else { + a.add(self.out); + try cuda.launch.launch(self.whole, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = kv_heads }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + } + try self.rig.s.synchronize(); + } + + pub fn count(self: *const Dflash) usize { + return self.rows() * heads * hd; + } + + /// Output head i: context in position order through start - 1, then all eight block keys. + pub fn load(self: *Dflash, i: usize, h: *attn.Head) !void { + const m = i / heads; + const head = i % heads; + const kvh = head / group; + for (h.q, 0..) |*x, e| x.* = c.fromBf16(self.q[(m * heads + head) * hd + e]); + const n = self.ringTerms(m) + block; + for (0..n) |j| { + const k = self.term(m, j, kvh, false); + const v = self.term(m, j, kvh, true); + for (0..hd) |e| { + h.k[j * hd + e] = c.fromBf16(k[e]); + h.v[j * hd + e] = c.fromBf16(v[e]); + } + } + h.n = n; + } + + fn scale() f64 { + return glm_scale; + } + pub fn check(self: *Dflash, at: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.rows() * heads, scale(), try self.rig.outputBytes(), at); + } + pub fn reference(self: *Dflash, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.rows() * heads, scale(), want, mag); + } + pub fn simulate(self: *Dflash, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.rows() * heads, scale(), acc, order, out); + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + mod: cuda.Module, + items: []Dflash, + + pub fn create(a: std.mem.Allocator, rig: rig_.Rig, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + const mod = try cuda.Module.load(rig.gpu.d, cuda.kernels.glm_dflash); + errdefer mod.unload(); + const items = try a.alloc(Dflash, forms.len); + errdefer a.free(items); + self.* = .{ .a = a, .mod = mod, .items = items }; + var initialized: usize = 0; + errdefer for (self.items[0..initialized]) |*item| item.deinit(); + for (forms) |form| { + self.items[initialized] = try Dflash.init(rig, form, self.mod); + initialized += 1; + try kernels.append(a, self.items[initialized - 1].kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items) |*item| item.deinit(); + self.a.free(self.items); + self.mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_h3.zig b/zig/tests/cuda/contract_h3.zig index 0240bebeff9..4a0c75598f3 100644 --- a/zig/tests/cuda/contract_h3.zig +++ b/zig/tests/cuda/contract_h3.zig @@ -158,7 +158,8 @@ pub const H3 = struct { self.fresh = &.{}; self.shape = shape; var prng = std.Random.DefaultPrng.init(seed); - return prep.prepare(self, shape, fill, prng.random()); + const adversarial = self.which == .attention and fill == .random; + return prep.prepare(self, shape, fill, prng.random(), adversarial); } pub fn run(self: *H3) !void { diff --git a/zig/tests/cuda/contract_h3_prep.zig b/zig/tests/cuda/contract_h3_prep.zig index aa2bd4a9209..0d80592084a 100644 --- a/zig/tests/cuda/contract_h3_prep.zig +++ b/zig/tests/cuda/contract_h3_prep.zig @@ -25,6 +25,31 @@ fn mirror(x: []f64, w: []f64, k: usize, rows: usize, n: usize) void { }; } +/// Query tile 0 ties maxima in two key tiles then changes the maximum; special bf16 bits are set before upload. +fn attentionAdversarial(q: []f64, k: []f64, v: []f64, list: []const i32, sz: []const i32, ksel: usize) void { + @memset(q[0..128], 0); // head 0, first query slot + q[0] = 1; + q[1] = -0.0; + q[2] = c.fromBf16(0x0001); + q[3] = c.fromBf16(0x8001); + q[4] = c.fromBf16(0x007f); + q[5] = c.fromBf16(0x807f); + for (0..slots) |j| k[j * 128] = 0; + for ([3]usize{ 0, 1, ksel - 1 }, 0..) |which, i| { + const tile: usize = @intCast(list[which]); + const size: usize = @intCast(sz[tile]); + const at = (tile * 64 + (if (i == 0) size - 1 else 0)) * 128; + k[at] = if (i < 2) 16 else 32; + k[at + 1] = if (i == 0) -0.0 else 0; + k[at + 2] = if (i == 0) c.fromBf16(0x0001) else c.fromBf16(0x8001); + k[at + 3] = if (i == 0) c.fromBf16(0x807f) else c.fromBf16(0x007f); + v[at] = 1 + 2 * @as(f64, @floatFromInt(i)); + v[at + 1] = if (i == 0) -0.0 else 0; + v[at + 2] = if (i == 0) c.fromBf16(0x0001) else c.fromBf16(0x8001); + v[at + 3] = if (i == 0) c.fromBf16(0x8001) else c.fromBf16(0x007f); + v[at + 4] = if (i == 0) c.fromBf16(0x007f) else c.fromBf16(0x807f); + } +} /// Tile sizes: most whole, some short (the last rows of a segment), never empty. fn sizes(self: *H3, n: usize, rng: std.Random) ![]i32 { const v = try self.arena.allocator().alloc(i32, n); @@ -39,7 +64,7 @@ fn rowOf(self: *H3, slot: []const i32) ![]i32 { return v; } -pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { +pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random, adversarial: bool) !bool { const al = self.arena.allocator(); const stress = fill == .stress; self.in = .{ .rows = s.rows, .n = s.n, .k = s.k, .heads = heads, .slots = slots }; @@ -195,6 +220,7 @@ pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { rows += 1; }; self.in = .{ .a = q, .b = k, .d = v, .ints = list, .more = sz, .rows = T, .n = s.n, .k = s.k, .heads = heads, .slots = slots, .scale = 1.0 / @sqrt(128.0) }; + if (adversarial) attentionAdversarial(q, k, v, list, sz, ksel); for ([_][]const f64{ q, k, v }) |x| try self.upload(x, true); try self.ints(list); try self.ints(sz); diff --git a/zig/tests/cuda/contract_hy4_attn.zig b/zig/tests/cuda/contract_hy4_attn.zig new file mode 100644 index 00000000000..c426b14b539 --- /dev/null +++ b/zig/tests/cuda/contract_hy4_attn.zig @@ -0,0 +1,229 @@ +//! HY4 sink finish and split MLA merge under the raw-output kernel contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const rows = core.contract.rows; +const latent = 512; +const Kind = enum { sink, merge }; + +const sink_shapes = [_]c.Shape{ .{ .rows = 1, .n = 1, .k = 64 }, .{ .rows = 2, .n = 3, .k = 128 }, .{ .rows = 4, .n = 2, .k = latent } }; +const merge_shapes = [_]c.Shape{ .{ .rows = 1, .n = 1, .k = 1 }, .{ .rows = 2, .n = 3, .k = 4 }, .{ .rows = 4, .n = 2, .k = 32 } }; + +fn noDepth(_: c.Shape) usize { + return 0; +} +fn mergeDepth(s: c.Shape) usize { + return s.k + 1; +} + +pub const Entry = struct { + rig: rig_.Rig, + f: cuda.Function, + kind: Kind, + shape: c.Shape = undefined, + maxima: []f32 = &.{}, + mass: []f32 = &.{}, + numerator: []f32 = &.{}, + sinks: []f32 = &.{}, + dev: [4]u64 = @splat(0), + out: u64 = 0, + + pub fn kernel(self: *Entry) g.Kernel { + const name = if (self.kind == .sink) "cuda hy4 tf_hy4_finish_attention" else "cuda hy4 tf_hy4_attend_merge"; + return .{ .spec = if (self.kind == .sink) + .{ .name = name, .accum = .none, .depth = noDepth, .ops = 8, .out = .f32, .served = &sink_shapes } + else + .{ .name = name, .accum = .f32, .depth = mergeDepth, .ops = 8, .mids = 1, .out = .bf16, .served = &merge_shapes, .sums = .{ .why = "split partials use fp32 mass/numerator merges before the bf16 output" } }, .ctx = self, .vt = &vt }; + } + const vt = g.hooks(Entry); + + fn width(self: *const Entry) usize { + return if (self.kind == .sink) self.shape.k else latent; + } + fn plane(self: *const Entry) usize { + return self.shape.rows * self.shape.n; + } + fn chunks(self: *const Entry) usize { + return if (self.kind == .merge) self.shape.k else 1; + } + pub fn count(self: *const Entry) usize { + return self.plane() * self.width(); + } + + fn free(self: *Entry) void { + const a = self.rig.gpu.gpa; + for ([_][]f32{ self.maxima, self.mass, self.numerator, self.sinks }) |x| a.free(x); + self.maxima = &.{}; + self.mass = &.{}; + self.numerator = &.{}; + self.sinks = &.{}; + } + pub fn deinit(self: *Entry) void { + self.free(); + self.rig.deinit(); + } + + pub fn prepare(self: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + self.maxima = try a.alloc(f32, self.plane() * self.chunks()); + self.mass = try a.alloc(f32, self.maxima.len); + self.numerator = try a.alloc(f32, self.maxima.len * self.width()); + self.sinks = try a.alloc(f32, shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (self.maxima) |*x| x.* = @floatCast(rng.floatNorm(f64)); + for (self.mass) |*x| x.* = @floatCast(0.5 + rng.float(f64)); + for (self.numerator) |*x| x.* = @floatCast(rng.floatNorm(f64)); + for (self.sinks) |*x| x.* = @floatCast(rng.floatNorm(f64)); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + if (fill == .random) self.plantAdversarial(); + const bytes = [_][]const u8{ std.mem.sliceAsBytes(self.maxima), std.mem.sliceAsBytes(self.mass), std.mem.sliceAsBytes(self.numerator), std.mem.sliceAsBytes(self.sinks) }; + for (bytes, &self.dev) |x, *p| p.* = try self.rig.input(x); + self.out = try self.rig.output(self.count() * if (self.kind == .sink) 4 else 2); + return true; + } + + fn plantNonfinite(self: *Entry) void { + self.numerator[5] = std.math.nan(f32); + self.numerator[9] = std.math.inf(f32); + if (self.plane() > 1) { + const at = self.width(); + for (self.numerator[at..][0..self.width()]) |*x| x.* = std.math.nan(f32); + } + } + + fn plantAdversarial(self: *Entry) void { + if (self.kind == .sink) { + self.sinks[0] = 5; + self.maxima[0] = 5; + self.numerator[0] = -0.0; + self.numerator[1] = @bitCast(@as(u32, 1)); + if (self.plane() > 1) { + self.maxima[1] = 3; + self.numerator[self.width()] = -0.0; + } + if (self.shape.n > 1) self.sinks[1] = 5; + } else { + for (self.maxima) |*x| x.* = 4; + self.maxima[0] = 5; + if (self.maxima.len > 1) self.maxima[self.plane()] = 5; + @memset(self.sinks, 0); + self.numerator[0] = -0.0; + self.numerator[1] = @bitCast(@as(u32, 1)); + self.numerator[2] = @bitCast(@as(u32, 0x80000001)); + } + } + + fn stress(self: *Entry, rng: std.Random) !void { + @memset(self.maxima, 0); + @memset(self.mass, 1); + @memset(self.sinks, 0); + if (self.kind == .sink) return; + const a = self.rig.gpu.gpa; + const terms = try a.alloc(f32, self.shape.k); + defer a.free(terms); + for (0..self.plane()) |rh| for (0..latent) |col| { + attn.mirrored(rng, terms); + for (terms, 0..) |x, chunk| self.numerator[(chunk * self.plane() + rh) * latent + col] = x; + }; + } + + pub fn run(self: *Entry) !void { + var args: cuda.Args = .{}; + if (self.kind == .sink) for (self.dev) |p| args.add(p) else for ([_]usize{ 2, 0, 1, 3 }) |i| args.add(self.dev[i]); + args.add(self.out); + const s = self.shape; + if (self.kind == .sink) { + for ([_]usize{ s.rows, s.n, s.k }) |x| args.add(@as(c_uint, @intCast(x))); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.plane()), .y = @intCast((s.k + 255) / 256) }, .block = .{ .x = 256 } }, self.rig.s, &args); + } else { + args.add(@as(i64, @intCast(s.rows))); + args.add(@as(i64, @intCast(s.n))); + args.add(@as(c_int, @intCast(s.k))); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(s.rows), .y = @intCast(s.n) }, .block = .{ .x = 128 } }, self.rig.s, &args); + } + try self.rig.s.synchronize(); + } + + pub fn reference(self: *Entry, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*w, *m, i| { + const rh = i / self.width(); + const head = rh % self.shape.n; + const col = i % self.width(); + var top: f64 = self.sinks[head]; + if (self.kind == .sink) top = @max(top, self.maxima[rh]) else for (0..self.chunks()) |chunk| top = @max(top, self.maxima[chunk * self.plane() + rh]); + var denom: f64 = @exp(self.sinks[head] - top); + var acc: f64 = 0; + var absolute: f64 = 0; + for (0..self.chunks()) |chunk| { + const base = chunk * self.plane() + rh; + const weight = @exp(self.maxima[base] - top); + const value = self.numerator[base * self.width() + col] * weight; + denom += self.mass[base] * weight; + acc += value; + absolute += @abs(value); + } + w.* = acc / denom; + m.* = absolute / denom; + } + } + + pub fn simulate(self: *Entry, acc: c.Accum, order: g.Order, out: []f64) !void { + if (self.kind == .sink) return error.NoSums; + const a = self.rig.gpu.gpa; + const terms = try a.alloc(f64, self.chunks() + 1); + defer a.free(terms); + const ones = try a.alloc(f64, self.chunks() + 1); + defer a.free(ones); + @memset(ones, 1); + for (out, 0..) |*o, i| { + const rh = i / latent; + const col = i % latent; + for (0..self.chunks()) |chunk| terms[chunk] = self.numerator[(chunk * self.plane() + rh) * latent + col]; + terms[self.chunks()] = 0; + o.* = rows.sumIn(acc, order, terms) / rows.sumIn(acc, order, ones); + } + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + sink_mod: cuda.Module, + merge_mod: cuda.Module, + items: [2]Entry, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const sink_mod = try cuda.Module.load(gpu.d, cuda.kernels.hy4_attention_sink); + errdefer sink_mod.unload(); + const merge_mod = try cuda.Module.load(gpu.d, cuda.kernels.hy4_mla_attention); + errdefer merge_mod.unload(); + const self = try a.create(Group); + errdefer a.destroy(self); + self.* = .{ .a = a, .sink_mod = sink_mod, .merge_mod = merge_mod, .items = undefined }; + self.items[0] = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try self.sink_mod.function("tf_hy4_finish_attention"), .kind = .sink }; + self.items[1] = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try self.merge_mod.function("tf_hy4_attend_merge"), .kind = .merge }; + for (&self.items) |*item| try kernels.append(a, item.kernel()); + return self; + } + + pub fn destroy(self: *Group) void { + for (&self.items) |*item| item.deinit(); + self.sink_mod.unload(); + self.merge_mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_hy4_chunks.zig b/zig/tests/cuda/contract_hy4_chunks.zig new file mode 100644 index 00000000000..97306e7a295 --- /dev/null +++ b/zig/tests/cuda/contract_hy4_chunks.zig @@ -0,0 +1,227 @@ +//! HY4's real wide MLA chunks: raw numerator/maxima/mass and their sink merge on every head/key form. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const mla = @import("contract_mla_chunks.zig"); +const pages = @import("contract_glm_pages.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lw = 512; +const kw = 576; +const chunk = 512; +const scale: f32 = 0.0625; + +/// n is heads * 512 and k is the serving key_stride. Counts form causal rows ending at k. +pub const shapes = [_]c.Shape{ + .{ .rows = 1, .n = 2 * lw, .k = 1 }, + .{ .rows = 3, .n = 16 * lw, .k = 512 }, + .{ .rows = 8, .n = 17 * lw, .k = 513 }, + .{ .rows = 8, .n = 32 * lw, .k = 33 }, + .{ .rows = 4, .n = 33 * lw, .k = 1024 }, + .{ .rows = 4, .n = 64 * lw, .k = 2 * chunk }, +}; +fn depth(s: c.Shape) usize { + return kw + chunk + (s.k + chunk - 1) / chunk + 1; +} + +pub const Entry = struct { + rig: rig_.Rig, + source: mla.Chunks, + f: cuda.Function, + merge: cuda.Function, + control: bool = false, + shape: c.Shape = undefined, + cache: []u16 = &.{}, + slots: []i32 = &.{}, + counts: []i32 = &.{}, + sinks: []f32 = &.{}, + nch: usize = 0, + dev: [5]u64 = @splat(0), // q, reversed cache, slots, counts, sinks + parts: [3]u64 = @splat(0), + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn kernel(self: *Entry) g.Kernel { + return .{ .spec = .{ .name = if (self.control) "control: HY4 attend chunks with reversed slots against a forward cache" else "cuda hy4 tf_hy4_attend_chunks raw numerator/maxima/mass + tf_hy4_attend_merge", .accum = .none, .depth = depth, .out = .raw, .nan = .{ .stated = "all chunk partial bytes are compared directly; merged finite outputs meet the wide-MLA bound and non-finite classes match float64" }, .served = &shapes }, .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + const vt = g.hooks(Entry); + + fn free(self: *Entry) void { + const a = self.rig.gpu.gpa; + inline for (.{ &self.cache, &self.slots, &self.counts, &self.sinks }) |p| { + a.free(p.*); + p.* = &.{}; + } + } + pub fn deinit(self: *Entry) void { + self.free(); + self.source.deinit(); + self.rig.deinit(); + } + fn heads(self: *const Entry) usize { + return self.shape.n / lw; + } + fn partialHeads(self: *const Entry) usize { + return self.nch * self.shape.rows * self.heads(); + } + fn semanticCount(self: *const Entry) usize { + return self.shape.rows * self.heads() * lw; + } + pub fn count(self: *Entry) usize { + return self.partialHeads() * (lw + 2) * 4 + self.semanticCount() * 2; + } + + pub fn prepare(self: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % lw != 0 or shape.n / lw > 64 or shape.k == 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + self.nch = (shape.k + chunk - 1) / chunk; + // Shift the wide-MLA generator so its fullest causal row ends at this key_stride. + const source_shape: c.Shape = if (shape.k > shape.rows) + .{ .rows = shape.rows, .n = shape.n, .k = shape.k - shape.rows + @min(shape.k - shape.rows, shape.rows / 2) } + else + shape; + if (!try self.source.prepare(source_shape, if (fill == .nonfinite) .random else fill, seed)) return false; + if (fill == .nonfinite) { + // Query-row/head plants avoid shared-key poisoning and retain a finite second head for one-key shapes. + self.source.q[3] = c.toBf16(std.math.nan(f32)); + if (shape.rows > 1) self.source.q[self.heads() * kw + 4] = c.toBf16(std.math.inf(f32)); + if (shape.rows > 2) self.source.q[2 * self.heads() * kw + 5] = c.toBf16(-std.math.inf(f32)); + } + self.cache = try a.alloc(u16, shape.k * kw); + self.slots = try a.alloc(i32, shape.rows * shape.k); + self.counts = try a.alloc(i32, shape.rows); + self.sinks = try a.alloc(f32, self.heads()); + @memset(self.sinks, -1.0e30); // zero sink weight: the merge leaves the chunk reference unchanged + for (0..shape.k) |i| @memcpy(self.cache[(shape.k - 1 - i) * kw ..][0..kw], self.source.cache[i * kw ..][0..kw]); + for (self.slots, 0..) |*x, i| x.* = @intCast(shape.k - 1 - i % shape.k); + for (self.counts, 0..) |*x, r| x.* = @intCast(@min(shape.k, self.source.at + r + 1)); + if (self.control) { + for (self.slots, 0..) |*x, i| x.* = @intCast(i % shape.k); + } + self.dev = .{ + try self.rig.input(std.mem.sliceAsBytes(self.source.q)), try self.rig.input(std.mem.sliceAsBytes(self.cache)), + try self.rig.input(std.mem.sliceAsBytes(self.slots)), try self.rig.input(std.mem.sliceAsBytes(self.counts)), + try self.rig.input(std.mem.sliceAsBytes(self.sinks)), + }; + const n = self.partialHeads(); + self.parts = .{ try self.rig.output(n * lw * 4), try self.rig.output(n * 4), try self.rig.output(n * 4) }; + self.out = try self.rig.output(self.semanticCount() * 2); + return true; + } + + pub fn run(self: *Entry) !void { + const rows64: i64 = @intCast(self.shape.rows); + const heads64: i64 = @intCast(self.heads()); + var args: cuda.Args = .{}; + inline for (.{ self.dev[0], self.dev[1], self.dev[2], self.dev[3], self.parts[0], self.parts[1], self.parts[2], rows64, heads64, @as(i64, @intCast(self.shape.k)), scale }) |x| args.add(x); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast((self.heads() + cuda.mla.heads_tile - 1) / cuda.mla.heads_tile), .z = @intCast(self.nch) }, .block = .{ .x = 256 }, .shared = cuda.mla.chunksSmem(cuda.mla.heads_tile) }, self.rig.s, &args); + var merge: cuda.Args = .{}; + inline for (.{ self.parts[0], self.parts[1], self.parts[2], self.dev[4], self.out, rows64, heads64, @as(c_int, @intCast(self.nch)) }) |x| merge.add(x); + try cuda.launch.launch(self.merge, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast(self.heads()) }, .block = .{ .x = 128 } }, self.rig.s, &merge); + try self.rig.s.synchronize(); + } + + fn attend(self: *const Entry, r: usize, h: usize, out: []f64, tol: []f64) !void { + const a = self.rig.gpu.gpa; + const n: usize = @intCast(self.counts[r]); + const terms = try a.alloc(f64, 4 * n + kw); + defer a.free(terms); + const scores = terms[0..n]; + const ds = terms[n .. 2 * n]; + const p = terms[2 * n .. 3 * n]; + const col = terms[3 * n .. 4 * n]; + const products = terms[4 * n ..]; + var most = -std.math.inf(f64); + for (0..n) |i| { + var abs: f64 = 0; + for (products, 0..) |*x, d| { + x.* = c.fromBf16(self.source.q[(r * self.heads() + h) * kw + d]) * c.fromBf16(self.source.cache[i * kw + d]); + abs += @abs(x.*); + } + scores[i] = pages.sumIn(.none, .sequential, products) * scale; + ds[i] = abs * scale * (kw + 8) * 0x1p-24; + most = pages.maxNan(most, scores[i]); + } + for (p, scores) |*x, score| x.* = @exp(score - most); + const mass = pages.sumIn(.none, .sequential, p); + for (out, tol, 0..) |*o, *t, d| { + var spread: f64 = 0; + for (col, p, 0..) |*x, weight, i| { + const v = c.fromBf16(self.source.cache[i * kw + d]); + x.* = weight * v; + spread += weight * @abs(v) * (0x1p-8 + ds[i]); + } + o.* = pages.sumIn(.none, .sequential, col) / mass; + t[d] = @abs(o.*) * 0x1p-8 + spread / mass + 1e-30; + } + } + + pub fn reference(_: *Entry, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + pub fn check(self: *Entry, gate: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const n = self.semanticCount(); + const work = try a.alloc(f64, 2 * n); + defer a.free(work); + const want = work[0..n]; + const tol = work[n..]; + const raw = try self.rig.outputBytes(); + const merged = raw[self.partialHeads() * (lw + 2) * 4 ..]; + var planted: usize = 0; + for (0..self.shape.rows) |r| for (0..self.heads()) |h| { + const at = (r * self.heads() + h) * lw; + try self.attend(r, h, want[at..][0..lw], tol[at..][0..lw]); + for (want[at..][0..lw], tol[at..][0..lw], 0..) |w, t, d| { + const got = c.read(.bf16, merged, at + d); + if (c.classOf(w) != .finite) planted += 1; + if (c.classOf(got) != c.classOf(w)) return try std.fmt.bufPrint(&self.msg, "row {d} head {d} column {d}: {t} where float64 gives {t}", .{ r, h, d, c.classOf(got), c.classOf(w) }); + if (gate != .nonfinite and std.math.isFinite(w) and !(@abs(got - w) <= t)) return try std.fmt.bufPrint(&self.msg, "row {d} head {d} column {d}: error {e} exceeds {e}", .{ r, h, d, @abs(got - w), t }); + } + }; + if (gate == .nonfinite and (planted == 0 or planted == n)) return try std.fmt.bufPrint(&self.msg, "planted non-finite values cover {d} of {d} outputs", .{ planted, n }); + return null; + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + items: [2]Entry = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.hy4_mla_attention); + const f = try self.mod.?.function("tf_hy4_attend_chunks"); + try f.allowDynamicShared(cuda.mla.chunksSmem(cuda.mla.heads_tile)); + const merge = try self.mod.?.function("tf_hy4_attend_merge"); + for (&self.items, [_]bool{ false, true }) |*item, control| { + item.* = .{ + .rig = .{ .gpu = gpu, .s = s }, + .source = .{ .rig = .{ .gpu = gpu, .s = s }, .f = undefined, .merge = undefined }, + .f = f, + .merge = merge, + .control = control, + }; + self.made += 1; + try kernels.append(a, item.kernel()); + } + return self; + } + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + if (self.mod) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_idol_attn.zig b/zig/tests/cuda/contract_idol_attn.zig index bc59d7603c1..440a6c37ecc 100644 --- a/zig/tests/cuda/contract_idol_attn.zig +++ b/zig/tests/cuda/contract_idol_attn.zig @@ -91,6 +91,7 @@ pub const Attn = struct { .nonfinite => t.plant(), .stress => t.stress(rng), } + if (fill == .random) t.adversarial(); } fn at(t: *Attn, row: usize, part: usize, head: usize, e: usize) *u16 { @@ -106,6 +107,37 @@ pub const Attn = struct { t.at(t.tokens / 3, 2, last, 9).* = half(r.inf); } + /// Adjacent 64-key tiles tie maxima before a changed maximum; Q/K/V carry signed zeros and extreme fp16 subnormals. + fn adversarial(t: *Attn) void { + const q = t.qkv.items[0..r.D]; + @memset(q[0..r.D], 0); + q[0] = half(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x03ff; + q[5] = 0x83ff; + for (0..t.tokens) |j| @memset(t.qkv.items[j * t.stride() + r.D ..][0..r.D], 0); + const tile = @min(64, (t.tokens - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, t.tokens - 1) }; + for (spots, 0..) |j, i| { + const k = t.qkv.items[j * t.stride() + t.heads * r.D ..]; + k[0] = half(if (i < 2) 16 else 32); + k[1] = 0x8000; + k[2] = 0x0001; + k[3] = 0x8001; + k[4] = 0x03ff; + k[5] = 0x83ff; + const v = t.qkv.items[j * t.stride() + 2 * t.heads * r.D ..]; + v[0] = half(1 + 2 * @as(f64, @floatFromInt(i))); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x03ff; + v[4] = if (i == 0) 0x03ff else 0x83ff; + } + } + /// Gate 4: keys alike (weights 1), odd values below 256 mirrored: fp16 lane sums pass 2048, fp32 sums stay exact. fn stress(t: *Attn, rng: std.Random) void { const n = t.tokens; diff --git a/zig/tests/cuda/contract_idol_dec_attn.zig b/zig/tests/cuda/contract_idol_dec_attn.zig index ea6e8878f11..58f114236e9 100644 --- a/zig/tests/cuda/contract_idol_dec_attn.zig +++ b/zig/tests/cuda/contract_idol_dec_attn.zig @@ -52,6 +52,10 @@ fn half(x: f64) f16 { return @floatCast(@as(f32, @floatCast(x))); } +fn bits16(b: u16) f16 { + return @bitCast(b); +} + /// The spacing of fp16 values at |x| (subnormals 2^-24). fn ulp16(x: f64) f64 { const a = @abs(x); @@ -201,6 +205,7 @@ pub const Attention = struct { t.qAt(0, 1)[5] = half(r.nan); if (L > 7) t.kAt(7, 1)[3] = half(r.inf); } + if (fill == .random) t.adversarial(); // every head's queries repeat at the period, so float64 computes each distinct one once const p = @min(t.lq, query_period); for (p..t.lq) |i| @memcpy(t.q.items[i * H ..][0..H], t.q.items[(i % p) * H ..][0..H]); @@ -210,6 +215,37 @@ pub const Attention = struct { return true; } + /// Two tied maxima in adjacent tiles, then a new maximum, with exact special fp16 bits in Q, K and V. + fn adversarial(t: *Attention) void { + const q = t.qAt(0, 0); + @memset(q, 0); + q[0] = 1; + q[1] = bits16(0x8000); + q[2] = bits16(0x0001); + q[3] = bits16(0x8001); + q[4] = bits16(0x03ff); + q[5] = bits16(0x83ff); + for (0..t.lk) |j| @memset(t.kAt(j, 0), 0); + const tile = @min(64, (t.lk - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, t.lk - 1) }; + for (spots, 0..) |j, i| { + const k = t.kAt(j, 0); + k[0] = half(if (i < 2) 16 else 32); + k[1] = bits16(0x8000); + k[2] = bits16(0x0001); + k[3] = bits16(0x8001); + k[4] = bits16(0x03ff); + k[5] = bits16(0x83ff); + const v = t.vAt(j, 0); + v[0] = half(1 + 2 * @as(f64, @floatFromInt(i))); + v[1] = bits16(if (i == 0) 0x8000 else 0); + v[2] = bits16(if (i == 0) 0x0001 else 0x8001); + v[3] = bits16(if (i == 0) 0x8001 else 0x03ff); + v[4] = bits16(if (i == 0) 0x03ff else 0x83ff); + } + } + /// Head hd: scores 0, -1/8 (last key) and -256 (P = 1, e^-1/8, 0), values -2^m fp16(P) and 2^m: O = 2^m lo / l. fn exact(t: *Attention, rng: std.Random, hd: usize) void { const L = t.lk; diff --git a/zig/tests/cuda/contract_inkling2_attn_rows.zig b/zig/tests/cuda/contract_inkling2_attn_rows.zig index ad95cb5de5a..93c3390f710 100644 --- a/zig/tests/cuda/contract_inkling2_attn_rows.zig +++ b/zig/tests/cuda/contract_inkling2_attn_rows.zig @@ -165,6 +165,7 @@ pub const Attn = struct { const rng = prng.random(); try self.fillAll(rng, ring); if (fill == .nonfinite) self.plantNonfinite(ring); + if (fill == .random) self.adversarial(ring); const tiles = try a.alloc(K.Tile, K.tileCount(rows, ref.group) + 2); defer a.free(tiles); self.n_tiles = @intCast(try K.tiles(segs[0..self.streams], ref.group, tiles)); @@ -265,6 +266,55 @@ pub const Attn = struct { if (p0 > 0) self.vc[at(1, (p0 - 1) % ring, 10, ring)] = inf | 0x8000; } + /// Row 0 ties tile maxima then changes one; sink and Q/K/V/gate carry signed zeros and extreme bf16 subnormals. + fn adversarial(self: *Attn, ring: usize) void { + const q = self.q[0..D]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + @memset(self.tab[0..ref.extent], 0); + self.sink[0] = c.toBf16(-128); + const gate = self.gate[0..D]; + gate[0] = 0x8000; + gate[1] = 0x0001; + gate[2] = 0x8001; + gate[3] = 0x007f; + gate[4] = 0x807f; + const st = self.stream[0]; + for (0..ring) |slot| @memset(self.kc[((st * kv) * ring + slot) * D ..][0..D], 0); + const pos = self.pos[0]; + const lo = if (self.layer.window > 0) (pos + 1) -| self.layer.window else 0; + const n = pos + 1 - lo; + const wanted: usize = switch (self.path) { + .sliding => 256, + .split => 1024, + .fold, .prompt => 16384, + }; + const tile = if (2 * wanted < n) wanted else (n - 1) / 2; + if (tile == 0) return; + const spots = [3]usize{ lo + tile - 1, lo + tile, lo + @min(2 * tile + 1, n - 1) }; + for (spots, 0..) |p, i| { + const at = ((st * kv) * ring + p % ring) * D; + const k = self.kc[at..][0..D]; + k[0] = c.toBf16(if (i < 2) 16 else 32); + k[1] = 0x8000; + k[2] = 0x0001; + k[3] = 0x8001; + k[4] = 0x007f; + k[5] = 0x807f; + const v = self.vc[at..][0..D]; + v[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + } + /// The device's own inputs: a control's faulted copy, else the true ones. fn planted(self: *Attn) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_minimax_attn.zig b/zig/tests/cuda/contract_minimax_attn.zig index 88d06f6aafa..456454ea7fe 100644 --- a/zig/tests/cuda/contract_minimax_attn.zig +++ b/zig/tests/cuda/contract_minimax_attn.zig @@ -145,6 +145,7 @@ pub const Attn = struct { } self.sel = try a.alloc(i32, shape.rows * hk * topk); for (0..shape.rows) |r| for (0..hk) |h| self.choose(rng, r, self.sel[(r * hk + h) * topk ..][0..topk]); + if (fill == .random) try self.adversarial(); const dev = try a.dupe(i32, self.sel); defer a.free(dev); if (self.drop) for (0..topk - 1) |i| { // row 0, key head 0: its first kept block other than its own goes @@ -177,6 +178,42 @@ pub const Attn = struct { return (keys + 127) / 128; } + /// Tied maxima in adjacent 64-key tiles of row 0, then a changed maximum; special bf16 bits reach Q, K and V. + fn adversarial(self: *Attn) !void { + const a = self.rig.gpu.gpa; + const list = try a.alloc(usize, self.last(0) + 1); + defer a.free(list); + const n = self.seen(0, 0, list); + const q = self.q[0..D]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (list[0..n]) |j| @memset(self.keys[(j * hk) * D ..][0..D], 0); + const tile = @min(64, (n - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, n - 1) }; + for (spots, 0..) |at, i| { + const j = list[at]; + const k = self.keys[(j * hk) * D ..][0..D]; + k[0] = c.toBf16(if (i < 2) 16 else 32); + k[1] = 0x8000; + k[2] = 0x0001; + k[3] = 0x8001; + k[4] = 0x007f; + k[5] = 0x807f; + const v = self.values[(j * hk) * D ..][0..D]; + v[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + } + /// Row r's kept blocks for a key head: picked forms keep its own and 15 others at random once it sees more than 16. fn choose(self: *const Attn, rng: std.Random, r: usize, out: []i32) void { @memset(out, -1); diff --git a/zig/tests/cuda/contract_mla_chunks.zig b/zig/tests/cuda/contract_mla_chunks.zig index c4b814b4079..b220567a9a9 100644 --- a/zig/tests/cuda/contract_mla_chunks.zig +++ b/zig/tests/cuda/contract_mla_chunks.zig @@ -119,6 +119,7 @@ pub const Chunks = struct { self.cache[9] = c.toBf16(std.math.inf(f32)); self.cache[2 * kw + 530] = c.toBf16(-std.math.inf(f32)); // key 2, a roped column: scores only } + if (fill == .random) self.adversarial(); const p: i32 = @intCast(self.at); const cnt: i32 = 0; if (self.fault == .next_head) { @@ -146,6 +147,33 @@ pub const Chunks = struct { return true; } + /// The fullest row has tied maxima in adjacent chunks, then a changed maximum, plus special bf16 bits in Q/K/V. + fn adversarial(self: *Chunks) void { + const r = self.shape.rows - 1; + const n = self.at + r + 1; + const q = self.q[(r * self.heads) * kw ..][0..kw]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..n) |j| @memset(self.cache[j * kw ..][0..kw], 0); + const tile = @min(512, (n - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, n - 1) }; + for (spots, 0..) |j, i| { + const kv = self.cache[j * kw ..][0..kw]; + kv[0] = c.toBf16(if (i < 2) 16 else 32); + kv[1] = 0x8000; + kv[2] = 0x0001; + kv[3] = 0x8001; + kv[4] = 0x007f; + kv[5] = 0x807f; + } + } + pub fn run(self: *Chunks) !void { if (self.split) |f| return splitRun(self, f[0], f[1]); const rows: i64 = @intCast(self.shape.rows); diff --git a/zig/tests/cuda/contract_moss_image_encoder_attn.zig b/zig/tests/cuda/contract_moss_image_encoder_attn.zig index 67f9f5be22b..d777ebd85c8 100644 --- a/zig/tests/cuda/contract_moss_image_encoder_attn.zig +++ b/zig/tests/cuda/contract_moss_image_encoder_attn.zig @@ -147,6 +147,7 @@ pub const Attn = struct { .nonfinite => t.plant(), .stress => try t.stress(rng), } + if (fill == .random) t.adversarial(); t.ins[0] = try mi.input(&t.rig, t.q); t.ins[1] = try mi.input(&t.rig, t.kb); t.ins[2] = try mi.input(&t.rig, t.vb); @@ -164,6 +165,38 @@ pub const Attn = struct { if (t.kvHeads() > 1 and rows > 2) t.keyRow(1, rows / 3)[5] = mi.nan16; } + /// The last causal query sees two tied maxima, then a changed maximum; Q, K and V carry special bf16 bits. + fn adversarial(t: *Attn) void { + const rows = t.shape.k; + const q = t.queryRow(0, rows - 1); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..rows) |j| @memset(t.keyRow(0, j), 0); + const tile = @min(8, (rows - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, rows - 1) }; + for (spots, 0..) |j, i| { + const k = t.keyRow(0, j); + k[0] = c.toBf16(if (i < 2) 16 else 32); + k[1] = 0x8000; + k[2] = 0x0001; + k[3] = 0x8001; + k[4] = 0x007f; + k[5] = 0x807f; + const v = t.valueRow(0, j); + v[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + } + /// Gate 4: one key vector a head (every weight exactly 1, the rescaling too), each value column a mirrored pair. fn stress(t: *Attn, rng: std.Random) !void { const a = t.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_muse_attn.zig b/zig/tests/cuda/contract_muse_attn.zig index 2ab68ce19cc..ecbff8f1480 100644 --- a/zig/tests/cuda/contract_muse_attn.zig +++ b/zig/tests/cuda/contract_muse_attn.zig @@ -191,6 +191,7 @@ pub const Attn = struct { }; if (n > 3) self.k[self.cacheAt(3, self.keyOf(3, 1), 0) + 4] = std.math.inf(f64); } + if (fill == .random) self.adversarial(); const slot = try a.alloc(i32, n); for (slot, 0..) |*s, r| s.* = @intCast(r); self.dev[0] = try mu.put(&self.rig, ga, f16, self.q); @@ -235,6 +236,7 @@ pub const Attn = struct { if (H > 1) self.part[0][nch * HD + 9] = std.math.inf(f64); // head 1: inf / L, then inf * 0 if (H > 2) self.gate[2 * HD + 5] = -std.math.inf(f64); // head 2: sigmoid 0 at one element } + if (fill == .random) self.adversarial(); for (0..3) |i| self.dev[i] = try mu.put(&self.rig, ga, f32, self.part[i]); self.dev[3] = try mu.put(&self.rig, ga, f16, self.gate); self.dev[4] = try self.rig.output(n * H * HD * 2); @@ -252,6 +254,68 @@ pub const Attn = struct { return ((r * self.len + key % self.len) * self.hk + kh) * HD; } + /// Streamed rows and merged partials each get tied maxima, then a changed maximum and exact special input values. + fn adversarial(self: *Attn) void { + const hsub: f64 = 0x1p-24; + const hmax: f64 = 0x1p-14 - hsub; + switch (self.kind) { + .prep_rope, .prep_nope => unreachable, + .rows_slide, .rows_full => { + const q = self.q[0..HD]; + @memset(q, 0); + q[0] = 1; + q[1] = -0.0; + q[2] = hsub; + q[3] = -hsub; + q[4] = hmax; + q[5] = -hmax; + const first = self.chunk(0, 0)[0]; + const n: usize = @as(usize, @intCast(self.pos[0])) + 1 - first; + for (first..first + n) |p| @memset(self.k[self.cacheAt(0, p, 0)..][0..HD], 0); + const tile = if (2 * CK < n) CK else (n - 1) / 2; + if (tile == 0) return; + const spots = [3]usize{ first + tile - 1, first + tile, first + @min(2 * tile, n - 1) }; + for (spots, 0..) |p, i| { + const at = self.cacheAt(0, p, 0); + self.k[at] = if (i < 2) 16 else 32; + self.k[at + 1] = -0.0; + self.k[at + 2] = hsub; + self.k[at + 3] = -hsub; + self.k[at + 4] = hmax; + self.k[at + 5] = -hmax; + self.v[at] = 1 + 2 * @as(f64, @floatFromInt(i)); + self.v[at + 1] = if (i == 0) -0.0 else 0; + self.v[at + 2] = if (i == 0) hsub else -hsub; + self.v[at + 3] = if (i == 0) -hsub else hmax; + self.v[at + 4] = if (i == 0) hmax else -hmax; + } + }, + .merge_slide, .merge_full => { + const fsub: f64 = 0x1p-149; + const fmax: f64 = 0x1p-126 - fsub; + const nch = self.nch; + const last = nch - 1; // retain the existing all-masked final partial + for (0..last) |ch| self.part[1][ch] = -128; + const spots = [3]usize{ 0, @min(1, last - 1), last - 1 }; + for (spots, 0..) |ch, i| { + self.part[1][ch] = if (i < 2) 16 else 32; + self.part[2][ch] = 1; + const o = self.part[0][ch * HD ..][0..HD]; + o[0] = 1 + 2 * @as(f64, @floatFromInt(i)); + o[1] = if (i == 0) -0.0 else 0; + o[2] = if (i == 0) fsub else -fsub; + o[3] = if (i == 0) -fmax else fmax; + o[4] = if (i == 0) fmax else -fmax; + } + self.gate[0] = -0.0; + self.gate[1] = hsub; + self.gate[2] = -hsub; + self.gate[3] = hmax; + self.gate[4] = -hmax; + }, + } + } + /// Gate 4's V: each chunk's values mirrored (integer sums near 2^20, a small result), every score 0 (q = 0). fn mirrorV(self: *Attn, rng: std.Random) !void { const a = self.arena.allocator(); diff --git a/zig/tests/cuda/contract_muse_draft.zig b/zig/tests/cuda/contract_muse_draft.zig index 394fae910eb..c268f2b05a7 100644 --- a/zig/tests/cuda/contract_muse_draft.zig +++ b/zig/tests/cuda/contract_muse_draft.zig @@ -180,13 +180,13 @@ pub const Draft = struct { self.dev[5] = try mu.ints(&self.rig, i32, slot); self.dev[6] = try self.rig.output(n * nh * HD * (if (self.kind == .norm_q) @as(usize, 4) else 2)); }, - .attn => return self.prepareAttn(fill, rng), + .attn => return self.prepareAttn(fill, rng, seed), } return true; } /// Streams (rows) of B queries at positions p0 .. p0 + B - 1, p0 = k; n query heads over n / 8 KV heads. - fn prepareAttn(self: *Draft, fill: g.Fill, rng: std.Random) !bool { + fn prepareAttn(self: *Draft, fill: g.Fill, rng: std.Random, _: u64) !bool { const sh = self.shape; if (sh.n % 8 != 0) return false; const a = self.arena.allocator(); @@ -209,6 +209,7 @@ pub const Draft = struct { self.in[2][self.cacheAt(0, p0 + 4, 1) + 1] = -std.math.inf(f64); if (S > 1) self.in[1][self.cacheAt(1, @as(usize, @intCast(self.pos[1])) + 1, 0) + 4] = std.math.inf(f64); } + if (fill == .random) self.adversarial(); const slot = try a.alloc(i32, S); for (slot, 0..) |*s, i| s.* = @intCast(i); self.dev[0] = try mu.put(&self.rig, ga, f32, self.in[0]); @@ -224,6 +225,40 @@ pub const Draft = struct { return ((s * self.ring + kp % self.ring) * self.kv + kh) * HD; } + /// The fullest query sees tied maxima in adjacent 32-key tiles, then a changed maximum and exact special values. + fn adversarial(self: *Draft) void { + const sub: f64 = 0x1p-24; + const most: f64 = 0x1p-14 - sub; + const q = self.in[0][((B - 1) * self.shape.n) * HD ..][0..HD]; + @memset(q, 0); + q[0] = 1; + q[1] = -0.0; + q[2] = 0x1p-149; + q[3] = -0x1p-149; + q[4] = 0x1p-126 - 0x1p-149; + q[5] = -(0x1p-126 - 0x1p-149); + const ks = self.keys(0, B - 1); + const n = ks[1] + 1 - ks[0]; + for (ks[0]..ks[1] + 1) |p| @memset(self.in[1][self.cacheAt(0, p, 0)..][0..HD], 0); + const tile = if (64 < n) 32 else (n - 1) / 2; + if (tile == 0) return; + const spots = [3]usize{ ks[0] + tile - 1, ks[0] + tile, ks[0] + @min(2 * tile, n - 1) }; + for (spots, 0..) |p, i| { + const at = self.cacheAt(0, p, 0); + self.in[1][at] = if (i < 2) 16 else 32; + self.in[1][at + 1] = -0.0; + self.in[1][at + 2] = sub; + self.in[1][at + 3] = -sub; + self.in[1][at + 4] = most; + self.in[1][at + 5] = -most; + self.in[2][at] = 1 + 2 * @as(f64, @floatFromInt(i)); + self.in[2][at + 1] = if (i == 0) -0.0 else 0; + self.in[2][at + 2] = if (i == 0) sub else -sub; + self.in[2][at + 3] = if (i == 0) -sub else most; + self.in[2][at + 4] = if (i == 0) most else -most; + } + } + /// Keys [lo, hi] query b of stream s sees. fn keys(self: *const Draft, s: usize, b: usize) [2]usize { const p0: usize = @intCast(self.pos[s]); diff --git a/zig/tests/cuda/contract_nemo_audio_attn.zig b/zig/tests/cuda/contract_nemo_audio_attn.zig index e69db26eea8..17187f62fe3 100644 --- a/zig/tests/cuda/contract_nemo_audio_attn.zig +++ b/zig/tests/cuda/contract_nemo_audio_attn.zig @@ -85,6 +85,7 @@ pub const Full = struct { .nonfinite => self.plant(), .stress => try self.stress(rng), } + if (fill == .random) self.plantAdversarial(); self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); self.out = try self.rig.output(L * shape.rows * D * 2); return true; @@ -106,6 +107,42 @@ pub const Full = struct { if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; } + /// Maxima tie across the 64-key tile boundary then change; Q/K/V carry signed zeros and extreme bf16 subnormals. + fn plantAdversarial(self: *Full) void { + const q = self.at(0, 0, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.shape.k) |row| @memset(self.at(row, 1, 0), 0); + for ([2]usize{ 63, 64 }, 0..) |row, i| { + const key = self.at(row, 1, 0); + key[0] = c.toBf16(16); + key[1] = if (i == 0) 0x8000 else 0; + key[2] = if (i == 0) 0x0001 else 0x8001; + key[3] = if (i == 0) 0x807f else 0x007f; + const value = self.at(row, 2, 0); + value[0] = c.toBf16(if (i == 0) 1 else 3); + value[1] = if (i == 0) 0x8000 else 0; + value[2] = if (i == 0) 0x0001 else 0x8001; + value[3] = if (i == 0) 0x8001 else 0x007f; + value[4] = if (i == 0) 0x007f else 0x807f; + } + const key = self.at(65, 1, 0); + key[0] = c.toBf16(32); + key[1] = 0x8000; + key[2] = 0x007f; + key[3] = 0x8001; + const value = self.at(65, 2, 0); + value[0] = c.toBf16(5); + value[1] = 0x8000; + value[2] = 0x0001; + value[3] = 0x807f; + } + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. fn stress(self: *Full, rng: std.Random) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_nemo_direct_attn.zig b/zig/tests/cuda/contract_nemo_direct_attn.zig new file mode 100644 index 00000000000..d9d06fbcda9 --- /dev/null +++ b/zig/tests/cuda/contract_nemo_direct_attn.zig @@ -0,0 +1,458 @@ +//! Direct Nemotron/Qwen chunk, prefetch and merge kernels, bit-compared with their _segs forms. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const hd = 128; +const chunk = 512; +const chunk_blocks = 64; +const page = 512; +const max_segs = 8; +const pad = 64; + +const Kind = enum { chunk, prefetch, control }; +const Layout = enum { nemotron, qwen16, qwen32 }; +const Form = struct { name: []const u8, layout: Layout, kind: Kind }; + +const forms = [_]Form{ + .{ .name = "cuda direct tf_nemo_attn_chunk + tf_nemo_attn_merge, Nemotron 32/2 paged QKV rows", .layout = .nemotron, .kind = .chunk }, + .{ .name = "cuda direct tf_nemo_attn_chunk_pf + tf_nemo_attn_merge, Nemotron 32/2 paged QKV rows", .layout = .nemotron, .kind = .prefetch }, + .{ .name = "control: directABI tf_ctl_nemo_attn_chunk_segs values from the neighbouring lane, Nemotron 32/2", .layout = .nemotron, .kind = .control }, + .{ .name = "cuda direct tf_nemo_attn_chunk + tf_nemo_attn_merge, Qwen3 16/8 contiguous query rows", .layout = .qwen16, .kind = .chunk }, + .{ .name = "cuda direct tf_nemo_attn_chunk_pf + tf_nemo_attn_merge, Qwen3 16/8 contiguous query rows", .layout = .qwen16, .kind = .prefetch }, + .{ .name = "control: directABI tf_ctl_nemo_attn_chunk_segs values from the neighbouring lane, Qwen3 16/8", .layout = .qwen16, .kind = .control }, + .{ .name = "cuda direct tf_nemo_attn_chunk + tf_nemo_attn_merge, Qwen3 32/8 contiguous query rows", .layout = .qwen32, .kind = .chunk }, + .{ .name = "cuda direct tf_nemo_attn_chunk_pf + tf_nemo_attn_merge, Qwen3 32/8 contiguous query rows", .layout = .qwen32, .kind = .prefetch }, + .{ .name = "control: directABI tf_ctl_nemo_attn_chunk_segs values from the neighbouring lane, Qwen3 32/8", .layout = .qwen32, .kind = .control }, +}; + +/// Nemotron's direct decode calls, including the tail, exact-chunk and >64-chunk-block classes. +const nemo_served = [_]c.Shape{ + .{ .rows = 1, .n = 32, .k = 0 }, + .{ .rows = 1, .n = 32, .k = 3000 }, + .{ .rows = 16, .n = 32, .k = 1500 }, + .{ .rows = 128, .n = 32, .k = 700 }, + .{ .rows = 8, .n = 32, .k = 4000 }, + .{ .rows = 2, .n = 32, .k = 511 }, + .{ .rows = 2, .n = 32, .k = 32768 }, +}; + +/// Qwen3's one-row and row-block calls, including whole prompt blocks and the grid.z chunk wrap. +fn qwenServed(comptime h: usize) [7]c.Shape { + return .{ + .{ .rows = 1, .n = h, .k = 0 }, + .{ .rows = 1, .n = h, .k = 3000 }, + .{ .rows = 256, .n = h, .k = 0 }, + .{ .rows = 64, .n = h, .k = 3000 }, + .{ .rows = 100, .n = h, .k = 500 }, + .{ .rows = 512, .n = h, .k = 0 }, + .{ .rows = 2, .n = h, .k = 32768 }, + }; +} +const qwen16_served = qwenServed(16); +const qwen32_served = qwenServed(32); + +fn noDepth(_: c.Shape) usize { + return 0; +} + +fn served(layout: Layout) []const c.Shape { + return switch (layout) { + .nemotron => &nemo_served, + .qwen16 => &qwen16_served, + .qwen32 => &qwen32_served, + }; +} + +fn heads(layout: Layout) usize { + return if (layout == .qwen16) 16 else 32; +} + +fn kvHeads(layout: Layout) usize { + return if (layout == .nemotron) 2 else 8; +} + +fn spec(f: Form) c.Spec { + return .{ + .name = f.name, + .accum = .none, + .depth = noDepth, + .out = .raw, + .replaces = "tf_nemo_attn_chunk_segs + tf_nemo_attn_merge_segs", + .nan = .{ .stated = "PO, PM, PL, OUT and XS are byte-identical to the one-segment kernels, including non-finite inputs and untouched tail chunks" }, + .tiles = .{ .{}, .{}, .{ .size = 64, .step = 1, .min = 0 } }, + .served = served(f.layout), + }; +} + +/// paged_attn.cuh's AttnSegs for the single stream that defines a direct launch. +const AttnSegs = extern struct { + kc: [max_segs]u64, + vc: [max_segs]u64, + meta: [max_segs]u64, + pt: [max_segs]u64, + ps: i64, + row0: [max_segs]c_int, + n: c_int, +}; + +const Dev = struct { + q: u64 = 0, + cache: u64 = 0, + meta: u64 = 0, + ids: u64 = 0, + po: u64 = 0, + pm: u64 = 0, + pl: u64 = 0, + out: u64 = 0, + xs: u64 = 0, + bpo: u64 = 0, + bpm: u64 = 0, + bpl: u64 = 0, + bout: u64 = 0, + bxs: u64 = 0, +}; + +pub const Entry = struct { + rig: rig_.Rig, + form: Form, + f: cuda.Function, + merge: cuda.Function, + seg_chunk: cuda.Function, + seg_merge: cuda.Function, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + nch: usize = 0, + nqkv: usize = 0, + vc_offset: usize = 0, + ps: usize = 0, + pages: usize = 0, + q: std.ArrayList(u16) = .empty, + cache: std.ArrayList(u16) = .empty, + ids: std.ArrayList(i32) = .empty, + base: std.ArrayList(u8) = .empty, + dev: Dev = .{}, + msg: [192]u8 = undefined, + + pub fn kernel(self: *Entry) g.Kernel { + return .{ + .spec = spec(self.form), + .ctx = self, + .vt = &vt, + .control = if (self.form.kind == .control) .shapes else null, + }; + } + const vt = g.hooks(Entry); + + pub fn deinit(self: *Entry) void { + const a = self.rig.gpu.gpa; + inline for (.{ "q", "cache", "ids", "base" }) |name| @field(self, name).deinit(a); + self.rig.deinit(); + } + + fn h(self: *const Entry) usize { + return heads(self.form.layout); + } + fn hk(self: *const Entry) usize { + return kvHeads(self.form.layout); + } + fn kvd(self: *const Entry) usize { + return self.hk() * hd; + } + fn total(self: *const Entry) usize { + return self.shape.k + self.shape.rows; + } + fn paged(self: *const Entry) bool { + return self.form.layout == .nemotron; + } + fn parts(self: *const Entry) usize { + return self.shape.rows * self.nch * self.h(); + } + fn poBytes(self: *const Entry) usize { + return self.parts() * hd * 4; + } + fn pmBytes(self: *const Entry) usize { + return self.parts() * 4; + } + fn outBytes(self: *const Entry) usize { + return self.shape.rows * self.h() * hd * 2; + } + fn xsBytes(self: *const Entry) usize { + return self.shape.rows * self.h() * (hd / 64) * 4; + } + pub fn count(self: *const Entry) usize { + return self.poBytes() + 2 * self.pmBytes() + self.outBytes() + self.xsBytes(); + } + fn scale(_: *const Entry) f32 { + return @floatCast(std.math.pow(f64, hd, -0.5)); + } + + /// Element offset of a logical key, exactly as direct chunk_at/key_at and the _segs reference see it. + fn keyAt(self: *const Entry, key: usize, kh: usize) usize { + if (!self.paged()) return key * self.kvd() + kh * hd; + const id: usize = @intCast(self.ids.items[key / page]); + return id * self.ps + (key % page) * self.kvd() + kh * hd; + } + fn valueAt(self: *const Entry, key: usize, kh: usize) usize { + return self.keyAt(key, kh) + self.vc_offset; + } + fn query(self: *Entry, row: usize, head: usize) []u16 { + return self.q.items[row * self.nqkv + head * hd ..][0..hd]; + } + + pub fn prepare(self: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != self.h()) return false; + self.rig.reset(); + self.base.clearRetainingCapacity(); + self.shape = shape; + const a = self.rig.gpu.gpa; + const nq = self.h() * hd; + self.nqkv = if (self.paged()) (self.h() + 2 * self.hk()) * hd else nq; + self.nch = (self.total() + chunk - 1) / chunk + 1; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + try self.q.resize(a, shape.rows * self.nqkv); + for (self.q.items) |*x| x.* = attn.normal(rng); + self.vc_offset = if (self.paged()) page * self.kvd() else (self.total() + pad) * self.kvd(); + self.ps = if (self.paged()) 2 * page * self.kvd() + pad else 0; + self.pages = (self.total() + pad + page - 1) / page + 2; + const cap = if (self.paged()) self.pages * page else self.total() + pad; + try self.cache.resize(a, if (self.paged()) self.pages * self.ps else 2 * cap * self.kvd()); + for (self.cache.items) |*x| x.* = attn.normal(rng); + try self.ids.resize(a, self.pages); + for (self.ids.items, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, self.ids.items); + // A poisoned, unallocated logical tail proves that causal/tile masks never read it. + for (self.total()..cap) |key| for (0..self.hk()) |kh| { + @memset(self.cache.items[self.keyAt(key, kh)..][0..hd], 0xff); + @memset(self.cache.items[self.valueAt(key, kh)..][0..hd], 0xff); + }; + if (fill == .random and self.form.kind != .control) self.adversarial(); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + const meta = [1]i32{@intCast(shape.k)}; + self.dev.q = try self.rig.input(std.mem.sliceAsBytes(self.q.items)); + self.dev.cache = try self.rig.input(std.mem.sliceAsBytes(self.cache.items)); + self.dev.meta = try self.rig.input(std.mem.sliceAsBytes(&meta)); + self.dev.ids = if (self.paged()) try self.rig.input(std.mem.sliceAsBytes(self.ids.items)) else 0; + self.dev.po = try self.rig.output(self.poBytes()); + self.dev.pm = try self.rig.output(self.pmBytes()); + self.dev.pl = try self.rig.output(self.pmBytes()); + self.dev.out = try self.rig.output(self.outBytes()); + self.dev.xs = try self.rig.output(self.xsBytes()); + inline for (.{ "bpo", "bpm", "bpl", "bout", "bxs" }, .{ self.poBytes(), self.pmBytes(), self.pmBytes(), self.outBytes(), self.xsBytes() }) |name, len| { + const ptr = try self.rig.scratch(len); + @field(self.dev, name) = ptr; + try (cuda.DeviceBuffer{ .d = self.rig.gpu.d, .ptr = ptr, .len = len }).fill8(0xff, self.rig.s.handle); + } + return true; + } + + /// NaN in one query and key, both infinities in values at row 0's own (universally visible) key. + fn plant(self: *Entry) void { + const at = self.shape.k; + self.query(0, 0)[3] = c.toBf16(std.math.nan(f32)); + self.cache.items[self.valueAt(at, 0) + 7] = c.toBf16(std.math.inf(f32)); + self.cache.items[self.valueAt(at, 1 % self.hk()) + 9] = c.toBf16(-std.math.inf(f32)); + if (at > 0) self.cache.items[self.valueAt(at - 1, 1 % self.hk()) + 9] = c.toBf16(std.math.inf(f32)); + self.cache.items[self.keyAt(at, 2 % self.hk())] = c.toBf16(std.math.nan(f32)); + } + + fn spot(self: *Entry, key: usize, score: f32, index: usize) void { + const k = self.keyAt(key, 0); + self.cache.items[k] = c.toBf16(score); + self.cache.items[k + 1] = if (index == 0) 0x8000 else 0; + self.cache.items[k + 2] = if (index == 0) 0x0001 else 0x8001; + self.cache.items[k + 3] = if (index == 0) 0x807f else 0x007f; + const v = self.valueAt(key, 0); + self.cache.items[v] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(index))); + self.cache.items[v + 1] = if (index == 0) 0x8000 else 0; + self.cache.items[v + 2] = if (index == 0) 0x0001 else 0x8001; + self.cache.items[v + 3] = if (index == 0) 0x8001 else 0x807f; + self.cache.items[v + 4] = if (index == 0) 0x007f else 0x807f; + } + + /// Tied tile/chunk maxima followed by a changed maximum, plus signed zero and bf16 subnormals. + fn adversarial(self: *Entry) void { + const last = self.shape.rows - 1; + const end = self.total() - 1; + const q = self.query(last, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..end + 1) |key| @memset(self.cache.items[self.keyAt(key, 0)..][0..hd], 0); + self.spot(0, 16, 0); + if (end >= 63) self.spot(63, 16, 1); + if (end >= 64) self.spot(64, 16, 2); + if (end >= 511) self.spot(511, 16, 3); + if (end >= 512) self.spot(512, 32, 4); + if (end >= 576) self.spot(576, 32, 5); + if (end > 0 and end < 512) self.spot(end, 32, 6); + } + + /// Every key scores alike; mirrored values exercise numerator and mass sums in all tiles. + fn stress(self: *Entry, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const same = try a.alloc(u16, self.kvd()); + defer a.free(same); + for (same) |*x| x.* = attn.normal(rng); + const col = try a.alloc(f32, self.total()); + defer a.free(col); + for (0..self.total()) |key| { + @memcpy(self.cache.items[self.keyAt(key, 0)..][0..self.kvd()], same); + @memset(self.cache.items[self.valueAt(key, 0)..][0..self.kvd()], 0); + } + for (0..self.hk()) |kh| for (0..hd) |d| { + attn.mirrored(rng, col); + for (col, 0..) |x, key| self.cache.items[self.valueAt(key, kh) + d] = c.toBf16(x); + }; + } + + fn segs(self: *const Entry) AttnSegs { + var sg = std.mem.zeroes(AttnSegs); + sg.kc[0] = self.dev.cache; + sg.vc[0] = self.dev.cache + self.vc_offset * 2; + sg.meta[0] = self.dev.meta; + sg.pt[0] = self.dev.ids; + sg.ps = @intCast(self.ps); + sg.n = 1; + return sg; + } + + fn launchChunk(self: *Entry, f: cuda.Function, segmented: bool, po: u64, pm: u64, pl: u64) !void { + var args: cuda.Args = .{}; + if (segmented) args.add(self.segs()); + args.add(self.dev.q); + if (!segmented) { + args.add(self.dev.cache); + args.add(self.dev.cache + self.vc_offset * 2); + args.add(self.dev.meta); + } + inline for (.{ po, pm, pl }) |p| args.add(p); + for ([_]usize{ self.nqkv, self.h(), self.hk(), self.h() / self.hk(), chunk, self.nch }) |x| args.add(@as(c_int, @intCast(x))); + args.add(self.scale()); + if (!segmented) { + args.add(self.dev.ids); + args.add(@as(i64, @intCast(self.ps))); + } + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast(self.hk()), .z = @intCast(@min(self.nch, chunk_blocks)) }, .block = .{ .x = 256 } }, self.rig.s, &args); + } + + fn launchMerge(self: *Entry, f: cuda.Function, segmented: bool, po: u64, pm: u64, pl: u64, out: u64, xs: u64) !void { + var args: cuda.Args = .{}; + if (segmented) args.add(self.segs()); + inline for (.{ po, pm, pl }) |p| args.add(p); + if (!segmented) args.add(self.dev.meta); + args.add(out); + args.add(xs); + for ([_]usize{ self.h(), self.hk(), self.h() / self.hk(), chunk, self.nch }) |x| args.add(@as(c_int, @intCast(x))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = @intCast(self.hk()), .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &args); + } + + pub fn run(self: *Entry) !void { + try self.launchChunk(self.f, self.form.kind == .control, self.dev.po, self.dev.pm, self.dev.pl); + try self.launchMerge(self.merge, false, self.dev.po, self.dev.pm, self.dev.pl, self.dev.out, self.dev.xs); + try self.rig.s.synchronize(); + } + + /// The exact one-segment kernels over the same pages, with untouched chunks poisoned identically. + pub fn replaced(self: *Entry) ![]const u8 { + try self.launchChunk(self.seg_chunk, true, self.dev.bpo, self.dev.bpm, self.dev.bpl); + try self.launchMerge(self.seg_merge, true, self.dev.bpo, self.dev.bpm, self.dev.bpl, self.dev.bout, self.dev.bxs); + try self.rig.s.synchronize(); + const a = self.rig.gpu.gpa; + self.base.clearRetainingCapacity(); + inline for (.{ "bpo", "bpm", "bpl", "bout", "bxs" }, .{ self.poBytes(), self.pmBytes(), self.pmBytes(), self.outBytes(), self.xsBytes() }) |name, len| { + const old = self.base.items.len; + try self.base.resize(a, old + len); + const bytes = try self.rig.bytes(@field(self.dev, name), len); + @memcpy(self.base.items[old..], bytes); + } + return self.base.items; + } + + pub fn check(self: *Entry, at: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |i| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from the one-segment kernels", .{ i, got.len }); + if (at != .nonfinite) return null; + const first = self.poBytes() + 2 * self.pmBytes(); + const out = got[first..][0..self.outBytes()]; + var finite: usize = 0; + var planted: usize = 0; + for (0..out.len / 2) |i| switch (c.classOf(c.read(.bf16, out, i))) { + .finite => finite += 1, + else => planted += 1, + }; + if (finite == 0 or planted == 0) return try std.fmt.bufPrint(&self.msg, "the plant gives {d} finite and {d} non-finite final outputs: no mixed proof", .{ finite, planted }); + return null; + } + + pub fn reference(_: *Entry, _: []f64, _: []f64) !void { + return error.ReplacementUsesOneSegmentBytes; + } +}; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +/// Heap-owned registrations and both images, stable for the gate and raw-output runs. +pub const Group = struct { + a: std.mem.Allocator, + mod: ?cuda.Module = null, + ctl: ?cuda.Module = null, + items: [forms.len]Entry = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.mod = try cuda.Module.load(gpu.d, cuda.kernels.nemotron_attention); + self.ctl = try cuda.Module.load(gpu.d, &controls.bytes); + const direct = try self.mod.?.function("tf_nemo_attn_chunk"); + const prefetch = try self.mod.?.function("tf_nemo_attn_chunk_pf"); + const merge = try self.mod.?.function("tf_nemo_attn_merge"); + const seg_chunk = try self.mod.?.function("tf_nemo_attn_chunk_segs"); + const seg_merge = try self.mod.?.function("tf_nemo_attn_merge_segs"); + const planted = try self.ctl.?.function("tf_ctl_nemo_attn_chunk_segs"); + for (&self.items, forms) |*entry, form| { + entry.* = .{ + .rig = .{ .gpu = gpu, .s = s }, + .form = form, + .f = switch (form.kind) { + .chunk => direct, + .prefetch => prefetch, + .control => planted, + }, + .merge = merge, + .seg_chunk = seg_chunk, + .seg_merge = seg_merge, + }; + self.made += 1; + try kernels.append(a, entry.kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*entry| entry.deinit(); + if (self.ctl) |mod| mod.unload(); + if (self.mod) |mod| mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_paged_attn.zig b/zig/tests/cuda/contract_paged_attn.zig index 2dbe8033300..050a7f03ec7 100644 --- a/zig/tests/cuda/contract_paged_attn.zig +++ b/zig/tests/cuda/contract_paged_attn.zig @@ -206,6 +206,9 @@ pub const Paged = struct { if (self.r) |*r| r.deinit(); self.r = null; self.r = try attn.Ref.init(a, f.d, most); + if (fill == .random and !f.control) { + if (f.form == .decode) self.adversarial() else self.promptAdversarial(); + } switch (fill) { .random => {}, .nonfinite => self.plant(), @@ -241,6 +244,67 @@ pub const Paged = struct { self.arena.items[self.keyAt(s, p, 2 % f.hk)] = c.toBf16(std.math.nan(f32)); } + /// Tied tile/chunk maxima precede a changed maximum; stream 0 row 0 reads exact bf16 bits via shuffled pages. + fn adversarial(self: *Paged) void { + const f = self.f; + const s = self.segs.items[0]; + const q = self.q.items[0..f.d]; // row 0, query head 0 (key head 0) + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..s.pos0 + 1) |key| self.arena.items[self.keyAt(s, key, 0)] = 0; + const spots = [5]usize{ 63, 64, 511, 512, 576 }; + for (spots, 0..) |key, i| { + const k = self.keyAt(s, key, 0); + self.arena.items[k] = c.toBf16(if (i < 4) 16 else 32); + self.arena.items[k + 1] = if (i == 0) 0x8000 else 0; + self.arena.items[k + 2] = if (i == 0) 0x0001 else 0x8001; + self.arena.items[k + 3] = if (i == 0) 0x807f else 0x007f; + const v = self.value(s, key, 0); + self.arena.items[v] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + self.arena.items[v + 1] = if (i == 0) 0x8000 else 0; + self.arena.items[v + 2] = if (i == 0) 0x0001 else 0x8001; + self.arena.items[v + 3] = if (i == 0) 0x8001 else 0x007f; + self.arena.items[v + 4] = if (i == 0) 0x007f else 0x807f; + } + } + + /// Prompt rows use the last served row up to key 576; k=0 shapes change maxima within recorded pages. + fn promptAdversarial(self: *Paged) void { + const f = self.f; + const s = self.segs.items[0]; + const row = @min(576, s.rows - 1); + const end = s.pos0 + row; + const q = self.q.items[((s.row0 + row) * f.h) * f.d ..][0..f.d]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..end + 1) |key| self.arena.items[self.keyAt(s, key, 0)] = 0; + const spots = [5]usize{ 0, end / 2, end, @min(511, end), @min(576, end) }; + for (spots, 0..) |key, i| { + const k = self.keyAt(s, key, 0); + const tie = i < 2 or (i == 3 and end >= 512); + self.arena.items[k] = c.toBf16(if (tie) 16 else 32); + self.arena.items[k + 1] = if (i == 0) 0x8000 else 0; + self.arena.items[k + 2] = if (i == 0) 0x0001 else 0x8001; + self.arena.items[k + 3] = if (i == 0) 0x807f else 0x007f; + const v = self.value(s, key, 0); + self.arena.items[v] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + self.arena.items[v + 1] = if (i == 0) 0x8000 else 0; + self.arena.items[v + 2] = if (i == 0) 0x0001 else 0x8001; + self.arena.items[v + 3] = if (i == 0) 0x8001 else 0x007f; + self.arena.items[v + 4] = if (i == 0) 0x007f else 0x807f; + } + } + /// Gate 4: every key of the stream alike (each p is 1); values mirrored over the keys row 0 sees, 0 after them. fn stress(self: *Paged, rng: std.Random) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_prefill_full_ab.zig b/zig/tests/cuda/contract_prefill_full_ab.zig new file mode 100644 index 00000000000..76723142511 --- /dev/null +++ b/zig/tests/cuda/contract_prefill_full_ab.zig @@ -0,0 +1,271 @@ +//! prefill_attention.cu's remaining full-attention exports, at their serving scales and row tiles. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const Kind = enum { siglip, gemma, radio }; +const Form = struct { kind: Kind, control: bool = false }; +const forms = [_]Form{ + .{ .kind = .siglip }, .{ .kind = .siglip, .control = true }, + .{ .kind = .gemma }, .{ .kind = .gemma, .control = true }, + .{ .kind = .radio }, .{ .kind = .radio, .control = true }, +}; + +const siglip_rows = [_]c.Shape{ + .{ .rows = 16, .n = 72, .k = 1 }, + .{ .rows = 16, .n = 72, .k = 7 }, + .{ .rows = 16, .n = 72, .k = 129 }, + .{ .rows = 16, .n = 72, .k = 308 }, + .{ .rows = 2, .n = 72, .k = 1024 }, // two heads stand for the full tile's 16 +}; +const gemma_rows = [_]c.Shape{ + .{ .rows = 16, .n = 72, .k = 9 }, + .{ .rows = 16, .n = 72, .k = 63 }, + .{ .rows = 16, .n = 72, .k = 126 }, + .{ .rows = 16, .n = 72, .k = 252 }, + .{ .rows = 2, .n = 72, .k = 2520 }, +}; +const radio_rows = [_]c.Shape{ + .{ .rows = 16, .n = 80, .k = 16 }, + .{ .rows = 16, .n = 80, .k = 65 }, + .{ .rows = 16, .n = 80, .k = 129 }, + .{ .rows = 16, .n = 80, .k = 576 }, + .{ .rows = 2, .n = 80, .k = 2304 }, +}; + +fn dim(kind: Kind) usize { + return if (kind == .radio) 80 else 72; +} + +fn scale(kind: Kind) f32 { + return switch (kind) { + .gemma => 1.0, + .siglip => 1.0 / @sqrt(@as(f32, 72)), + .radio => 1.0 / @sqrt(@as(f32, 80)), + }; +} + +fn served(kind: Kind) []const c.Shape { + return switch (kind) { + .siglip => &siglip_rows, + .gemma => &gemma_rows, + .radio => &radio_rows, + }; +} + +fn name(f: Form) []const u8 { + if (f.control) return switch (f.kind) { + .siglip => "control: SigLIP2 full_kernel<72, 8, 8> doubling its score scale", + .gemma => "control: Gemma4 full_kernel<72, 8, 8> doubling its unit score scale", + .radio => "control: RADIO vision_kernel<80, 8> doubling its score scale", + }; + return switch (f.kind) { + .siglip => "cuda SigLIP2 prefill full_kernel<72, 8, 8>, 16 heads", + .gemma => "cuda Gemma4 prefill full_kernel<72, 8, 8>, unit scale", + .radio => "cuda RADIO prefill vision_kernel<80, 8>, 16 heads", + }; +} + +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn spec(f: Form) c.Spec { + return .{ + .name = name(f), + .accum = .f32, + .depth = keyChain, + .ops = 1, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 64 } }, + .served = served(f.kind), + .sums = .{ .why = attn.why }, + }; +} + +const Full = struct { + rig: rig_.Rig, + att: *const cuda.vit.Attention, + form: Form, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + qkv: std.ArrayList(u16) = .empty, + dev: u64 = 0, + out: u64 = 0, + + fn kernel(self: *Full) g.Kernel { + return .{ .spec = spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Full); + + fn deinit(self: *Full) void { + if (self.r) |*r| r.deinit(); + self.qkv.deinit(self.rig.gpu.gpa); + self.rig.deinit(); + } + + fn stride(self: *const Full) usize { + return 3 * self.shape.rows * dim(self.form.kind); + } + + fn at(self: *Full, row: usize, which: usize, head: usize) []u16 { + const d = dim(self.form.kind); + return self.qkv.items[row * self.stride() + (which * self.shape.rows + head) * d ..][0..d]; + } + + fn prepare(self: *Full, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + const d = dim(self.form.kind); + if (shape.n != d or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.shape = shape; + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, d, shape.k); + try self.qkv.resize(a, shape.k * self.stride()); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (self.qkv.items) |*x| x.* = attn.normal(rng); + if (fill == .random) self.plantAdversarial(); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv.items)); + self.out = try self.rig.output(shape.k * shape.rows * d * 2); + return true; + } + + fn plantNonfinite(self: *Full) void { + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + const rows = self.shape.k; + self.at(0, 0, 0)[3] = nan; + self.at(rows - 1, 2, 0)[7] = inf; + self.at(rows / 2, 2, 0)[9] = ninf; + if (rows >= 3) { + self.at(1, 2, 0)[11] = inf; + self.at(2, 2, 0)[11] = ninf; + } + if (self.shape.rows > 1) self.at(rows / 3, 1, 1)[5] = nan; + } + + /// Equal maxima straddle a 64-key tile, a later maximum changes, and exact signed/subnormal bits survive upload. + fn plantAdversarial(self: *Full) void { + const q = self.at(0, 0, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.shape.k) |row| @memset(self.at(row, 1, 0), 0); + const tile = @min(64, (self.shape.k - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, self.shape.k - 1) }; + for (spots, 0..) |row, i| { + const key = self.at(row, 1, 0); + key[0] = c.toBf16(if (i < 2) 16 else 32); + key[1] = if (i == 0) 0x8000 else 0; + key[2] = if (i == 0) 0x0001 else 0x8001; + key[3] = if (i == 0) 0x807f else 0x007f; + const value = self.at(row, 2, 0); + value[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + value[1] = if (i == 0) 0x8000 else 0; + value[2] = if (i == 0) 0x0001 else 0x8001; + value[3] = if (i == 0) 0x8001 else 0x007f; + value[4] = if (i == 0) 0x007f else 0x807f; + } + } + + fn stress(self: *Full, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const d = dim(self.form.kind); + const rows = self.shape.k; + const key = try a.alloc(u16, d); + defer a.free(key); + const col = try a.alloc(f32, rows); + defer a.free(col); + for (key) |*x| x.* = attn.normal(rng); + for (0..self.shape.rows) |h| { + for (0..rows) |row| @memcpy(self.at(row, 1, h), key); + for (0..d) |e| { + attn.mirrored(rng, col); + for (col, 0..) |x, row| self.at(row, 2, h)[e] = c.toBf16(x); + } + } + } + + fn run(self: *Full) !void { + const d = dim(self.form.kind); + const sc = scale(self.form.kind) * (if (self.form.control) @as(f32, 2) else 1); + try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, d, sc); + try self.rig.s.synchronize(); + } + + fn count(self: *Full) usize { + return self.shape.k * self.shape.rows * dim(self.form.kind); + } + + fn heads(self: *Full) usize { + return self.shape.k * self.shape.rows; + } + + fn load(self: *Full, i: usize, hd: *attn.Head) !void { + const d = dim(self.form.kind); + const row = i / self.shape.rows; + const head = i % self.shape.rows; + for (hd.q, self.at(row, 0, head)) |*y, x| y.* = c.fromBf16(x); + for (0..self.shape.k) |j| for (0..d) |e| { + hd.k[j * d + e] = c.fromBf16(self.at(j, 1, head)[e]); + hd.v[j * d + e] = c.fromBf16(self.at(j, 2, head)[e]); + }; + hd.n = self.shape.k; + } + + fn check(self: *Full, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.heads(), scale(self.form.kind), try self.rig.outputBytes(), gate); + } + fn reference(self: *Full, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.heads(), scale(self.form.kind), want, mag); + } + fn simulate(self: *Full, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.heads(), scale(self.form.kind), acc, order, out); + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + att: cuda.vit.Attention, + items: [forms.len]Full = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + self.* = .{ .a = a, .att = try cuda.vit.Attention.load(gpu.d) }; + errdefer self.att.unload(); + errdefer for (self.items[0..self.made]) |*item| item.deinit(); + for (forms) |form| { + self.items[self.made] = .{ .rig = .{ .gpu = gpu, .s = s }, .att = &self.att, .form = form }; + self.made += 1; + try kernels.append(a, self.items[self.made - 1].kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + self.att.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_q35_attn.zig b/zig/tests/cuda/contract_q35_attn.zig index bf423e80642..ff20ea380fe 100644 --- a/zig/tests/cuda/contract_q35_attn.zig +++ b/zig/tests/cuda/contract_q35_attn.zig @@ -4,7 +4,6 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const attn = @import("contract_attn.zig"); - const contract = core.contract; const c = contract.spec; const g = contract.gates; @@ -174,6 +173,7 @@ pub const Q35 = struct { try self.kv.append(a, buf); self.fillRandom(si, rng); } + if (fill == .random) self.plantAdversarial(); switch (fill) { .random => {}, .nonfinite => self.plant(), @@ -243,6 +243,55 @@ pub const Q35 = struct { } } + /// Writes exact input bits (and a unit scale for fp8) to one key or value element. + fn putBits(self: *Q35, value: bool, pos: usize, e: usize, bf: u16, fp: u8) void { + const b = self.kv.items[0].items; + const n = kvh * self.cap(0); + const r = pos + @as(usize, if (value) n else 0); // stream 0, key head 0 + switch (self.form.cache) { + .bf16 => std.mem.bytesAsSlice(u16, b)[r * hd + e] = bf, + .fp8 => { + b[r * hd + e] = fp; + std.mem.bytesAsSlice(f32, b[2 * n * hd ..])[r] = 1; + }, + } + } + + /// Two 128-key tile/chunk maxima tie before a new maximum; special values reach Q/K/V before upload. + fn plantAdversarial(self: *Q35) void { + const q = self.q.items[0..hd]; // row 0, query head 0 (key head 0) + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.cap(0)) |pos| self.putBits(false, pos, 0, 0, 0); + const keys = self.lens.items[0] + seen(self.anc.items[0]); + const ck = @max(128, (keys + maxch * 128 - 1) / (maxch * 128) * 128); + for ([2]usize{ ck - 1, ck }, 0..) |pos, i| { + self.putBits(false, pos, 0, c.toBf16(16), toCode(16)); + self.putBits(false, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + self.putBits(false, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + self.putBits(false, pos, 3, if (i == 0) 0x807f else 0x007f, if (i == 0) 0x87 else 0x07); + self.putBits(true, pos, 0, c.toBf16(if (i == 0) 1 else 3), toCode(if (i == 0) 1 else 3)); + self.putBits(true, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + self.putBits(true, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + self.putBits(true, pos, 3, if (i == 0) 0x8001 else 0x007f, if (i == 0) 0x81 else 0x07); + self.putBits(true, pos, 4, if (i == 0) 0x007f else 0x807f, if (i == 0) 0x07 else 0x87); + } + const changed = 2 * ck; + self.putBits(false, changed, 0, c.toBf16(32), toCode(32)); + self.putBits(false, changed, 1, 0x8000, 0x80); + self.putBits(false, changed, 2, 0x007f, 0x07); + self.putBits(false, changed, 3, 0x8001, 0x81); + self.putBits(true, changed, 0, c.toBf16(5), toCode(5)); + self.putBits(true, changed, 1, 0x8000, 0x80); + self.putBits(true, changed, 2, 0x0001, 0x01); + self.putBits(true, changed, 3, 0x807f, 0x87); + } + /// NaN in a query, +inf and -inf values, both in one column (bf16), and a NaN key in a row's last chunk. fn plant(self: *Q35) void { const p0 = self.lens.items[0]; diff --git a/zig/tests/cuda/contract_q35_contiguous.zig b/zig/tests/cuda/contract_q35_contiguous.zig index b5951eaa044..0ca64f73712 100644 --- a/zig/tests/cuda/contract_q35_contiguous.zig +++ b/zig/tests/cuda/contract_q35_contiguous.zig @@ -4,7 +4,6 @@ const cuda = @import("cuda"); const core = @import("core"); const rig_ = @import("contract_rig.zig"); const attn = @import("contract_attn.zig"); - const contract = core.contract; const c = contract.spec; const g = contract.gates; @@ -157,6 +156,7 @@ pub const Q35 = struct { try self.kv.append(a, buf); self.fillRandom(si, rng); } + if (fill == .random) self.plantAdversarial(); switch (fill) { .random => {}, .nonfinite => self.plant(), @@ -239,6 +239,55 @@ pub const Q35 = struct { self.put(0, false, 3, p0 - 1, 0, std.math.nan(f32)); } + /// Writes exact input bits (and a unit scale for fp8) to one key or value element. + fn putBits(self: *Q35, value: bool, pos: usize, e: usize, bf: u16, fp: u8) void { + const b = self.kv.items[0].items; + const n = kvh * self.cap(0); + const r = pos + @as(usize, if (value) n else 0); // stream 0, key head 0 + switch (self.form.cache) { + .bf16 => std.mem.bytesAsSlice(u16, b)[r * hd + e] = bf, + .fp8 => { + b[r * hd + e] = fp; + std.mem.bytesAsSlice(f32, b[2 * n * hd ..])[r] = 1; + }, + } + } + + /// Two 128-key tile/chunk maxima tie before a new maximum; special values reach Q/K/V before upload. + fn plantAdversarial(self: *Q35) void { + const q = self.q.items[0..hd]; // row 0, query head 0 (key head 0) + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.cap(0)) |pos| self.putBits(false, pos, 0, 0, 0); + const keys = self.lens.items[0] + seen(self.anc.items[0]); + const ck = @max(128, (keys + maxch * 128 - 1) / (maxch * 128) * 128); + for ([2]usize{ ck - 1, ck }, 0..) |pos, i| { + self.putBits(false, pos, 0, c.toBf16(16), toCode(16)); + self.putBits(false, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + self.putBits(false, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + self.putBits(false, pos, 3, if (i == 0) 0x807f else 0x007f, if (i == 0) 0x87 else 0x07); + self.putBits(true, pos, 0, c.toBf16(if (i == 0) 1 else 3), toCode(if (i == 0) 1 else 3)); + self.putBits(true, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + self.putBits(true, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + self.putBits(true, pos, 3, if (i == 0) 0x8001 else 0x007f, if (i == 0) 0x81 else 0x07); + self.putBits(true, pos, 4, if (i == 0) 0x007f else 0x807f, if (i == 0) 0x07 else 0x87); + } + const changed = 2 * ck; + self.putBits(false, changed, 0, c.toBf16(32), toCode(32)); + self.putBits(false, changed, 1, 0x8000, 0x80); + self.putBits(false, changed, 2, 0x007f, 0x07); + self.putBits(false, changed, 3, 0x8001, 0x81); + self.putBits(true, changed, 0, c.toBf16(5), toCode(5)); + self.putBits(true, changed, 1, 0x8000, 0x80); + self.putBits(true, changed, 2, 0x0001, 0x01); + self.putBits(true, changed, 3, 0x807f, 0x87); + } + /// Gate 4: every key of a head alike (each p is 1), committed values mirrored per column, window values 0. fn stress(self: *Q35, rng: std.Random) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_qwen35_draft_attn.zig b/zig/tests/cuda/contract_qwen35_draft_attn.zig new file mode 100644 index 00000000000..479cca11cfb --- /dev/null +++ b/zig/tests/cuda/contract_qwen35_draft_attn.zig @@ -0,0 +1,403 @@ +//! Qwen3.5 draft attention under the contract: the legacy block kernel and both batched frame kinds. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const hd = 128; +const heads = 32; +const kv_heads = 8; +const group = heads / kv_heads; +const width = kv_heads * hd; + +const Variant = enum { legacy, dflash2, dspine }; + +pub const Form = struct { variant: Variant, dspine_window: usize = 0, control: bool = false }; +pub const forms = [_]Form{ + .{ .variant = .legacy }, .{ .variant = .dflash2 }, + .{ .variant = .dspine, .dspine_window = 16 }, .{ .variant = .dspine, .dspine_window = 4096 }, + .{ .variant = .dspine, .dspine_window = 8192 }, .{ .variant = .legacy, .control = true }, + .{ .variant = .dflash2, .control = true }, .{ .variant = .dspine, .dspine_window = 16, .control = true }, + .{ .variant = .dspine, .dspine_window = 4096, .control = true }, .{ .variant = .dspine, .dspine_window = 8192, .control = true }, +}; + +/// qwen35_draft_frame.cuh's DraftSegment. +const Segment = extern struct { ring: u64, begin: i64, position: i64 }; + +const legacy_served = [_]c.Shape{ + .{ .rows = 16, .n = heads, .k = 257 }, .{ .rows = 16, .n = heads, .k = 0 }, + .{ .rows = 16, .n = heads, .k = 63 }, .{ .rows = 16, .n = heads, .k = 64 }, + .{ .rows = 16, .n = heads, .k = 65 }, .{ .rows = 16, .n = heads, .k = 255 }, + .{ .rows = 16, .n = heads, .k = 256 }, .{ .rows = 16, .n = heads, .k = 2047 }, + .{ .rows = 16, .n = heads, .k = 2048 }, +}; +const dflash2_served = [_]c.Shape{ + .{ .rows = 8, .n = heads, .k = 257 }, .{ .rows = 1, .n = heads, .k = 0 }, + .{ .rows = 4, .n = heads, .k = 63 }, .{ .rows = 4, .n = heads, .k = 64 }, + .{ .rows = 4, .n = heads, .k = 65 }, .{ .rows = 4, .n = heads, .k = 255 }, + .{ .rows = 4, .n = heads, .k = 256 }, .{ .rows = 1, .n = heads, .k = 2047 }, + .{ .rows = 1, .n = heads, .k = 2048 }, .{ .rows = 8, .n = heads, .k = 700 }, + .{ .rows = 64, .n = heads, .k = 63 }, +}; +const dspine16_served = [_]c.Shape{ + .{ .rows = 4, .n = heads, .k = 16 }, .{ .rows = 1, .n = heads, .k = 0 }, + .{ .rows = 1, .n = heads, .k = 1 }, .{ .rows = 4, .n = heads, .k = 15 }, + .{ .rows = 64, .n = heads, .k = 16 }, +}; +const dspine4096_served = [_]c.Shape{ + .{ .rows = 4, .n = heads, .k = 257 }, .{ .rows = 1, .n = heads, .k = 0 }, + .{ .rows = 4, .n = heads, .k = 63 }, .{ .rows = 4, .n = heads, .k = 64 }, + .{ .rows = 4, .n = heads, .k = 65 }, .{ .rows = 2, .n = heads, .k = 255 }, + .{ .rows = 2, .n = heads, .k = 256 }, .{ .rows = 1, .n = heads, .k = 4095 }, + .{ .rows = 1, .n = heads, .k = 4096 }, .{ .rows = 4, .n = heads, .k = 700 }, + .{ .rows = 64, .n = heads, .k = 63 }, +}; +const dspine_served = [_]c.Shape{ + .{ .rows = 4, .n = heads, .k = 257 }, .{ .rows = 1, .n = heads, .k = 0 }, + .{ .rows = 4, .n = heads, .k = 63 }, .{ .rows = 4, .n = heads, .k = 64 }, + .{ .rows = 4, .n = heads, .k = 65 }, .{ .rows = 2, .n = heads, .k = 255 }, + .{ .rows = 2, .n = heads, .k = 256 }, .{ .rows = 1, .n = heads, .k = 4096 }, + .{ .rows = 1, .n = heads, .k = 8192 }, .{ .rows = 4, .n = heads, .k = 700 }, + .{ .rows = 64, .n = heads, .k = 63 }, +}; + +const DepthFn = *const fn (c.Shape) usize; + +fn legacyDepth(s: c.Shape) usize { + return @min(s.k + s.rows - 1, 2048) + s.rows + 16; +} +fn dflash2Depth(s: c.Shape) usize { + return @min(s.k + 15, 2048) + 16 + 9; +} +fn dspine16Depth(s: c.Shape) usize { + return @min(s.k + 15, 16) + 16 + 1; +} +fn dspine4096Depth(s: c.Shape) usize { + return @min(s.k + 15, 4096) + 16 + 17; +} +fn dspine8192Depth(s: c.Shape) usize { + return @min(s.k + 15, 8192) + 16 + 33; +} + +pub fn spec(f: Form) c.Spec { + const name = switch (f.variant) { + .legacy => if (f.control) "control qwen35 legacy draft attention leaves its output unwritten" else "cuda qwen35 draft block attention tf_q35d_attn", + .dflash2 => if (f.control) "control qwen35 DFlash2 draft attention leaves its output unwritten" else "cuda qwen35 DFlash2 frame attention tf_q35d_attn_partial, tf_q35d_attn_merge", + .dspine => switch (f.dspine_window) { + 16 => if (f.control) "control qwen35 DSpine 16-window attention leaves its output unwritten" else "cuda qwen35 DSpine 16-window causal attention tf_q35d_attn_partial, tf_q35d_attn_merge", + 4096 => if (f.control) "control qwen35 DSpine 4096-window attention leaves its output unwritten" else "cuda qwen35 DSpine 4096-window causal attention tf_q35d_attn_partial, tf_q35d_attn_merge", + else => if (f.control) "control qwen35 DSpine 8192-window attention leaves its output unwritten" else "cuda qwen35 DSpine 8192-window causal attention tf_q35d_attn_partial, tf_q35d_attn_merge", + }, + }; + const selection = switch (f.variant) { + .legacy => .{ @as([]const c.Shape, &legacy_served), @as(DepthFn, legacyDepth) }, + .dflash2 => .{ @as([]const c.Shape, &dflash2_served), @as(DepthFn, dflash2Depth) }, + .dspine => switch (f.dspine_window) { + 16 => .{ @as([]const c.Shape, &dspine16_served), @as(DepthFn, dspine16Depth) }, + 4096 => .{ @as([]const c.Shape, &dspine4096_served), @as(DepthFn, dspine4096Depth) }, + else => .{ @as([]const c.Shape, &dspine_served), @as(DepthFn, dspine8192Depth) }, + }, + }; + return .{ .name = name, .accum = .f32, .depth = selection[1], .ops = 3, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256 } }, .served = selection[0], .sums = .{ .why = attn.why } }; +} + +pub const Draft = struct { + rig: rig_.Rig, + form: Form, + legacy_fn: cuda.Function, + partial: cuda.Function, + merge: cuda.Function, + arena: std.heap.ArenaAllocator, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + rows: usize = 0, + ns: usize = 0, + q: []u16 = &.{}, + kb: []u16 = &.{}, + vb: []u16 = &.{}, + ring: []u16 = &.{}, + dq: u64 = 0, + dkb: u64 = 0, + dvb: u64 = 0, + dring: u64 = 0, + segments: u64 = 0, + part: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn init(rig: rig_.Rig, form: Form, mod: cuda.Module) !Draft { + return .{ .rig = rig, .form = form, .legacy_fn = try mod.function("tf_q35d_attn"), .partial = try mod.function("tf_q35d_attn_partial"), .merge = try mod.function("tf_q35d_attn_merge"), .arena = .init(rig.gpu.gpa) }; + } + + pub fn deinit(self: *Draft) void { + if (self.r) |*r| r.deinit(); + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Draft) g.Kernel { + return .{ .spec = spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Draft); + + fn window(self: *const Draft) usize { + return if (self.form.variant == .dspine) (if (self.form.dspine_window == 0) 8192 else self.form.dspine_window) else 2048; + } + fn block(self: *const Draft) usize { + return if (self.form.variant == .legacy) self.shape.rows else 16; + } + fn ringRows(self: *const Draft) usize { + return self.window() + 16; + } + fn chunks(self: *const Draft) usize { + return (self.ringRows() + 255) / 256; + } + /// Unequal served positions, all crossing the ring's wrap for contexts of at least three rows. + fn begin(self: *const Draft) usize { + return self.ringRows() - 3; + } + fn context(self: *const Draft, si: usize) usize { + return self.shape.k -| si * self.shape.k / self.ns; + } + fn position(self: *const Draft, si: usize) usize { + return self.begin() + self.context(si); + } + + fn first(self: *const Draft, m: usize) usize { + const local = if (self.form.variant == .legacy) m else m % 16; + return @max(self.begin(), self.position(m / self.block()) + local -| (self.window() - 1)); + } + fn ringTerms(self: *const Draft, m: usize) usize { + return self.position(m / self.block()) - self.first(m); + } + fn blockTerms(self: *const Draft, m: usize) usize { + return if (self.form.variant == .dspine) m % 16 + 1 else self.block(); + } + + fn term(self: *Draft, m: usize, j: usize, kvh: usize, values: bool) []u16 { + const nr = self.ringTerms(m); + if (j < nr) { + const at = ((self.first(m) + j) % self.ringRows()) * width + kvh * hd; + return self.ring[at + @as(usize, if (values) self.ringRows() * width else 0) ..][0..hd]; + } + const si = m / self.block(); + const r = si * self.block() + (if (self.form.variant == .legacy) j - nr else j - nr); + const at = r * width + kvh * hd; + return (if (values) self.vb else self.kb)[at..][0..hd]; + } + + pub fn prepare(self: *Draft, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + _ = self.arena.reset(.free_all); + if (shape.n != heads or shape.rows == 0 or shape.k > self.window()) return false; + if (self.form.variant == .legacy) { + if (shape.rows > 16) return false; + self.ns = 1; + self.rows = shape.rows; + } else { + if (shape.rows > 64) return false; // cuda_draft_frame.max_streams = cuda_engine.max_segs + self.ns = shape.rows; + self.rows = shape.rows * 16; + } + self.shape = shape; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(self.rig.gpu.gpa, hd, shape.k + 32); + self.q = try a.alloc(u16, self.rows * heads * hd); + self.kb = try a.alloc(u16, self.rows * width); + self.vb = try a.alloc(u16, self.rows * width); + self.ring = try a.alloc(u16, 2 * self.ringRows() * width); + for (self.q) |*x| x.* = attn.normal(rng); + for (self.kb) |*x| x.* = attn.normal(rng); + for (self.vb) |*x| x.* = attn.normal(rng); + for (self.ring) |*x| x.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + if (fill == .random) self.plantAdversarial(); + + self.dq = try self.rig.input(std.mem.sliceAsBytes(self.q)); + self.dkb = try self.rig.input(std.mem.sliceAsBytes(self.kb)); + self.dvb = try self.rig.input(std.mem.sliceAsBytes(self.vb)); + self.dring = try self.rig.input(std.mem.sliceAsBytes(self.ring)); + if (self.form.variant != .legacy) { + const sg = try a.alloc(Segment, self.ns); + for (sg, 0..) |*x, si| x.* = .{ .ring = self.dring, .begin = @intCast(self.begin()), .position = @intCast(self.position(si)) }; + self.segments = try self.rig.input(std.mem.sliceAsBytes(sg)); + const slots = self.rows * heads * self.chunks(); + for (&self.part, [_]usize{ 4, 4, 4 * hd }) |*p, w| p.* = try self.rig.scratch(slots * w); + } + self.out = try self.rig.output(self.rows * heads * hd * 2); + return true; + } + + /// The query NaN and both infinities reach every frame kind; a NaN block key reaches causal rows too. + fn plantNonfinite(self: *Draft) void { + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + self.q[3] = nan; + self.vb[7] = inf; + self.vb[hd + 9] = ninf; + if (self.rows > 1) self.vb[width + 11] = inf; + if (self.rows > 2) self.vb[2 * width + 11] = ninf; + if (self.context(0) > 0) { + const last = self.position(0) - 1; + const at = (last % self.ringRows()) * width + hd; + self.ring[at + 5] = inf; + self.kb[2 * width] = nan; + } + } + + /// Gate 4: every score is zero, with exact mirrored committed values and zero block values. + fn stress(self: *Draft, rng: std.Random) !void { + const a = self.arena.allocator(); + @memset(self.q, 0); + @memset(self.kb, 0); + @memset(self.vb, 0); + @memset(self.ring, 0); + const col = try a.alloc(f32, self.shape.k); + defer a.free(col); + for (0..kv_heads) |kvh| for (0..hd) |e| { + attn.mirrored(rng, col); + for (0..self.shape.k) |j| { + const at = ((self.begin() + j) % self.ringRows()) * width + kvh * hd + e; + self.ring[self.ringRows() * width + at] = c.toBf16(col[j]); + } + }; + } + + /// Keys 63 and 64 tie across warp/slice paths and key 256 changes the maximum; special values reach Q/K/V. + fn plantAdversarial(self: *Draft) void { + const q = self.q[0..hd]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + const n = self.ringTerms(0) + self.blockTerms(0); + for (0..n) |j| self.term(0, j, 0, false)[0] = 0; + const tie0 = if (n > 64) 63 else 0; + const tie1 = if (n > 64) 64 else @min(1, n - 1); + const changed = if (n > 256) 256 else @min(2, n - 1); + for ([2]usize{ tie0, tie1 }, 0..) |j, i| { + const k = self.term(0, j, 0, false); + const v = self.term(0, j, 0, true); + k[0] = c.toBf16(16); + k[1] = if (i == 0) 0x8000 else 0; + k[2] = if (i == 0) 0x0001 else 0x8001; + k[3] = if (i == 0) 0x807f else 0x007f; + v[0] = c.toBf16(if (i == 0) 1 else 3); + v[1] = if (i == 0) 0x8000 else 0; + v[2] = if (i == 0) 0x0001 else 0x8001; + v[3] = if (i == 0) 0x8001 else 0x007f; + v[4] = if (i == 0) 0x007f else 0x807f; + } + const k = self.term(0, changed, 0, false); + const v = self.term(0, changed, 0, true); + k[0] = c.toBf16(32); + k[1] = 0x8000; + k[2] = 0x007f; + k[3] = 0x8001; + v[0] = c.toBf16(5); + v[1] = 0x8000; + v[2] = 0x0001; + v[3] = 0x807f; + } + + pub fn run(self: *Draft) !void { + if (!self.form.control) switch (self.form.variant) { + .legacy => { + var a: cuda.Args = .{}; + inline for (.{ self.dq, self.dkb, self.dvb, self.dring, self.dring + self.ringRows() * width * 2, @as(c_int, @intCast(self.rows)), @as(c_int, heads), @as(c_int, kv_heads), @as(c_int, @intCast(self.ringRows())), @as(c_longlong, @intCast(self.begin())), @as(c_longlong, @intCast(self.position(0))), @as(c_int, @intCast(self.window())), self.out }) |v| a.add(v); + try cuda.launch.launch(self.legacy_fn, .{ .grid = .{ .x = @intCast(self.rows), .y = heads }, .block = .{ .x = 32 } }, self.rig.s, &a); + }, + .dflash2, .dspine => { + var a: cuda.Args = .{}; + inline for (.{ self.dq, self.dkb, self.dvb, self.segments, @as(c_int, 16), @as(c_int, heads), @as(c_int, kv_heads), @as(c_int, @intCast(self.ringRows())), @as(c_int, @intCast(self.window())), @as(c_int, 0), @as(c_int, @intCast(self.chunks())), @as(c_int, @intFromBool(self.form.variant == .dspine)), self.part[0], self.part[1], self.part[2] }) |v| a.add(v); + try cuda.launch.launch(self.partial, .{ .grid = .{ .x = @intCast(self.rows), .y = heads, .z = @intCast(self.chunks()) }, .block = .{ .x = 128 } }, self.rig.s, &a); + var m: cuda.Args = .{}; + inline for (.{ self.part[0], self.part[1], self.part[2], @as(c_int, heads), @as(c_int, @intCast(self.chunks())), self.out }) |v| m.add(v); + try cuda.launch.launch(self.merge, .{ .grid = .{ .x = @intCast(self.rows), .y = heads }, .block = .{ .x = 32 } }, self.rig.s, &m); + }, + }; + try self.rig.s.synchronize(); + } + + pub fn count(self: *const Draft) usize { + return self.rows * heads * hd; + } + + /// Output head i: its visible wrapping ring keys in position order, then its whole or causal block. + pub fn load(self: *Draft, i: usize, h: *attn.Head) !void { + const m = i / heads; + const head = i % heads; + const kvh = head / group; + for (h.q, 0..) |*x, e| x.* = c.fromBf16(self.q[(m * heads + head) * hd + e]); + const nr = self.ringTerms(m); + const n = nr + self.blockTerms(m); + for (0..n) |j| { + const k = self.term(m, j, kvh, false); + const v = self.term(m, j, kvh, true); + for (0..hd) |e| { + h.k[j * hd + e] = c.fromBf16(k[e]); + h.v[j * hd + e] = c.fromBf16(v[e]); + } + } + h.n = n; + } + + fn scale() f64 { + return 1 / @sqrt(@as(f64, hd)); + } + pub fn check(self: *Draft, at: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.rows * heads, scale(), try self.rig.outputBytes(), at); + } + pub fn reference(self: *Draft, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.rows * heads, scale(), want, mag); + } + pub fn simulate(self: *Draft, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.rows * heads, scale(), acc, order, out); + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + mod: cuda.Module, + items: []Draft, + + pub fn create(a: std.mem.Allocator, rig: rig_.Rig, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + const mod = try cuda.Module.load(rig.gpu.d, cuda.kernels.qwen35_draft); + errdefer mod.unload(); + const items = try a.alloc(Draft, forms.len); + errdefer a.free(items); + self.* = .{ .a = a, .mod = mod, .items = items }; + var initialized: usize = 0; + errdefer for (self.items[0..initialized]) |*item| item.deinit(); + for (forms) |form| { + self.items[initialized] = try Draft.init(rig, form, self.mod); + initialized += 1; + try kernels.append(a, self.items[initialized - 1].kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items) |*item| item.deinit(); + self.a.free(self.items); + self.mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_qwen_mtp_rows.zig b/zig/tests/cuda/contract_qwen_mtp_rows.zig index f7ea2da9cbf..5720f7e14b7 100644 --- a/zig/tests/cuda/contract_qwen_mtp_rows.zig +++ b/zig/tests/cuda/contract_qwen_mtp_rows.zig @@ -4,7 +4,6 @@ const cuda = @import("cuda"); const core = @import("core"); const tc = @import("check.zig"); const rig_ = @import("contract_rig.zig"); - const contract = core.contract; const c = contract.spec; const g = contract.gates; @@ -171,6 +170,8 @@ pub const Rows = struct { self.rk[self.segs.len - 1][at] = c.toBf16(std.math.inf(f32)); // the last stream's first slot self.vb[(rows - 1) * width + 9] = c.toBf16(-std.math.inf(f32)); } + + if (fill == .random) self.plantAdversarial(); self.dq = try self.rig.input(std.mem.sliceAsBytes(self.q)); self.dg = try self.rig.input(std.mem.sliceAsBytes(self.gate)); self.dkb = try self.rig.input(std.mem.sliceAsBytes(self.kb)); @@ -187,6 +188,48 @@ pub const Rows = struct { return true; } + /// Maxima tie in ring loads then change in block rows; short rings wrap and special bits reach Q/K/V/gate. + fn plantAdversarial(self: *Rows) void { + const q = self.q[0..hd]; // row 0, query head 0 (key head 0) + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + const s = self.segs[0]; + for (0..s.slots) |j| self.rk[0][((s.begin + j) % s.cap) * width] = 0; + self.kb[0] = 0; + const tie = if (s.slots > 8) 8 else s.slots - 1; + const first = (s.begin % s.cap) * width; + const second = ((s.begin + tie) % s.cap) * width; + for ([2]usize{ first, second }, 0..) |at, i| { + self.rk[0][at] = c.toBf16(16); + self.rk[0][at + 1] = if (i == 0) 0x8000 else 0; + self.rk[0][at + 2] = if (i == 0) 0x0001 else 0x8001; + self.rk[0][at + 3] = if (i == 0) 0x807f else 0x007f; + self.rv[0][at] = c.toBf16(if (i == 0) 1 else 3); + self.rv[0][at + 1] = if (i == 0) 0x8000 else 0; + self.rv[0][at + 2] = if (i == 0) 0x0001 else 0x8001; + self.rv[0][at + 3] = if (i == 0) 0x8001 else 0x007f; + self.rv[0][at + 4] = if (i == 0) 0x007f else 0x807f; + } + self.kb[0] = c.toBf16(32); + self.kb[1] = 0x8000; + self.kb[2] = 0x007f; + self.kb[3] = 0x8001; + self.vb[0] = c.toBf16(5); + self.vb[1] = 0x8000; + self.vb[2] = 0x0001; + self.vb[3] = 0x807f; + self.gate[hd] = 0x8000; + self.gate[hd + 1] = 0x0001; + self.gate[hd + 2] = 0x8001; + self.gate[hd + 3] = 0x007f; + self.gate[hd + 4] = 0x807f; + } + pub fn run(self: *Rows) !void { var a: cuda.Args = .{}; inline for (.{ self.dq, self.dg, @as(c_int, gstride), self.dkb, self.dvb, self.table, @as(c_int, heads), @as(c_int, kv_heads), self.out }) |v| a.add(v); diff --git a/zig/tests/cuda/contract_qwen_pages_ab.zig b/zig/tests/cuda/contract_qwen_pages_ab.zig new file mode 100644 index 00000000000..cb6fb639013 --- /dev/null +++ b/zig/tests/cuda/contract_qwen_pages_ab.zig @@ -0,0 +1,405 @@ +//! Qwen3.5's paged decode partials: raw PO/PM/PL, merged rows, and their contiguous replacements. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const fixture = @import("contract_qwen_pages.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const hd = fixture.hd; +const qh = fixture.q_heads; +const kvh = fixture.kv_heads; +const group = qh / kvh; +const chunks = fixture.max_chunks; +const layers = fixture.attentions; +const scale: f32 = 1.0 / 16.0; +const Format = fixture.Format; +const Geo = fixture.Geo; +const Seg = fixture.Seg; +const Ancestor = fixture.Ancestor; +const Case = fixture.Case; + +/// Every key/page/split class exercised by contract_qwen_pages, in the same logical layouts. +const cases = [_]Case{ + .{ .lens = .{ 0, 3 }, .rows = 1, .ptok = 16 }, + .{ .lens = .{ 127, 128 }, .rows = 4, .ptok = 16 }, + .{ .lens = .{ 129, 1000 }, .rows = 8, .ptok = 128 }, + .{ .lens = .{ 700, 33 }, .rows = 2, .ptok = 48 }, + .{ .lens = .{ 4095, 5000 }, .rows = 16, .ptok = 256 }, + .{ .lens = .{ 9000, 300 }, .rows = 3, .ptok = 512 }, + .{ .lens = .{ 31, 128 }, .rows = 128, .ptok = 48 }, + .{ .lens = .{ 4096, 4097 }, .rows = 64, .ptok = 48 }, + .{ .lens = .{ 4096, 4097 }, .rows = 65, .ptok = 48 }, + .{ .lens = .{ 32767, 32768 }, .rows = 1, .ptok = 256 }, + .{ .lens = .{ 4096, 8192 }, .rows = 1, .ptok = 48 }, + .{ .lens = .{ 8, 16 }, .rows = 5, .ptok = 16 }, +}; +const Form = struct { case: usize, format: Format, control: bool = false }; +const forms = blk: { + var out: [2 * cases.len + 2]Form = undefined; + var n = 0; + for (cases, 0..) |_, i| for ([_]Format{ .bf16, .fp8 }) |format| { + out[n] = .{ .case = i, .format = format }; + n += 1; + }; + for ([_]Format{ .bf16, .fp8 }) |format| { + out[n] = .{ .case = 1, .format = format, .control = true }; + n += 1; + } + break :blk out; +}; + +fn code(v: f32) u8 { + var x: u8 = 0; + while (x < 0x7f) : (x += 1) if (core.quant.fp8.e4m3(x) == @abs(v)) break; + return x | @as(u8, if (v < 0) 0x80 else 0); +} + +const Entry = struct { + rig: rig_.Rig, + alt: rig_.Rig, + form: Form, + primary: cuda.Function, + contiguous: cuda.Function, + merge: cuda.Function, + label: [240]u8 = undefined, + served_shape: [1]c.Shape = undefined, + arena: ?std.heap.ArenaAllocator = null, + r: ?attn.Ref = null, + f: fixture.Fixture = undefined, + pages: []u8 = &.{}, + segs: u64 = 0, + flat_segs: u64 = 0, + rowseg: u64 = 0, + rowanc: u64 = 0, + q: u64 = 0, + kv: u64 = 0, + p: u64 = 0, + pm: u64 = 0, + pl: u64 = 0, + po: u64 = 0, + out: u64 = 0, + alt_pm: u64 = 0, + alt_pl: u64 = 0, + alt_po: u64 = 0, + alt_out: u64 = 0, + m: usize = 0, + rows_per: [2]usize = .{ 0, 0 }, + + fn kernel(self: *Entry) g.Kernel { + const ca = cases[self.form.case]; + self.served_shape[0] = .{ .rows = 2 * ca.rows, .n = qh, .k = @max(ca.lens[0], ca.lens[1]) + ca.rows }; + const name = std.fmt.bufPrint(&self.label, "{s}cuda qwen35 {s} raw PM/PL/PO + merge, {d}/{d} heads, keys {d}+{d} rows, {d}-position pages", .{ + if (self.form.control) "control: swapped first/last pages on " else "", + if (self.form.format == .bf16) "tf_q35_attn_partial_paged" else "tf_q35_attn_partial8_paged", + qh, + kvh, + @max(ca.lens[0], ca.lens[1]), + ca.rows, + ca.ptok, + }) catch unreachable; + return .{ + .spec = .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = if (self.form.control) null else if (self.form.format == .bf16) "tf_q35_attn_partial_contiguous over identical logical rows" else "tf_q35_attn_partial8_contiguous over identical logical rows", + .nan = .{ .stated = "every raw partial byte, including unwritten empty-chunk PO poison, and merged BF16 classes" }, + .served = &self.served_shape, + }, + .ctx = self, + .vt = &vt, + .control = if (self.form.control) .shapes else null, + }; + } + const vt = g.hooks(Entry); + + fn deinit(self: *Entry) void { + if (self.r) |*r| r.deinit(); + if (self.arena) |*a| a.deinit(); + self.alt.deinit(); + self.rig.deinit(); + } + + fn partialBytes(self: *const Entry) usize { + return self.m * qh * chunks * (hd + 2) * 4; + } + fn mergedBytes(self: *const Entry) usize { + return self.m * qh * hd * 2; + } + fn count(self: *Entry) usize { + return self.partialBytes() + self.mergedBytes(); + } + + fn put(self: *Entry, st: usize, part: usize, head: usize, pos: usize, d: usize, bits: u16, fp8: u8, sc: f32) void { + const sp = self.f.logical(1, part, head, pos); + const cache = self.f.kv[st]; + if (self.form.format == .bf16) { + std.mem.writeInt(u16, cache[sp[0].off + 2 * d ..][0..2], bits, .little); + } else { + cache[sp[0].off + d] = fp8; + std.mem.writeInt(u32, cache[sp[1].off..][0..4], @bitCast(sc), .little); + } + } + + fn putScore(self: *Entry, pos: usize, which: usize, changed: bool) void { + const v: f32 = if (changed) 32 else 16; + self.put(0, 0, 0, pos, 0, c.toBf16(v), code(v), 1); + self.put(0, 0, 0, pos, 1, if (which == 0) 0x8000 else 0, if (which == 0) 0x80 else 0, 1); + self.put(0, 0, 0, pos, 2, if (which == 0) 1 else 0x8001, if (which == 0) 1 else 0x81, 1); + self.put(0, 0, 0, pos, 3, if (which == 0) 0x807f else 0x007f, if (which == 0) 0x87 else 7, 1); + const value: f32 = if (changed) 9 else 1 + 2 * @as(f32, @floatFromInt(which)); + self.put(0, 1, 0, pos, 0, c.toBf16(value), code(value), 1); + self.put(0, 1, 0, pos, 1, if (which == 0) 0x8000 else 0, if (which == 0) 0x80 else 0, 1); + self.put(0, 1, 0, pos, 2, if (which == 0) 1 else 0x8001, if (which == 0) 1 else 0x81, 1); + self.put(0, 1, 0, pos, 3, if (which == 0) 0x807f else 0x007f, if (which == 0) 0x87 else 7, 1); + self.put(0, 1, 0, pos, 4, if (which == 0) 0x007f else 0x807f, if (which == 0) 7 else 0x87, 1); + } + + fn adversarial(self: *Entry) void { + const ca = cases[self.form.case]; + const row = self.rows_per[0] - 1; + const visible = ca.lens[0] + row + 1; + const q = self.f.q[(row * qh) * hd ..][0..hd]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 1; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..visible) |pos| self.put(0, 0, 0, pos, 0, 0, 0, 1); + // One term has no tie or later maximum; two terms can tie but cannot then change it. + if (visible == 1) { + self.putScore(0, 0, false); + return; + } + const ck = @max(128, (visible + chunks * 128 - 1) / (chunks * 128) * 128); + var first: usize = 0; + var second: usize = 1; + if (visible > 2 * ck) { + first = ck - 1; + second = ck; + } + self.putScore(first, 0, false); + self.putScore(second, 1, false); + const changed: ?usize = if (visible >= 3) @min(2 * ck, visible - 1) else null; + if (changed) |pos| self.putScore(pos, 2, true); + if (ca.ptok < visible) for ([2]usize{ ca.ptok - 1, ca.ptok }, 0..) |pos, i| { + if (pos != first and pos != second and (changed == null or pos != changed.?)) self.putScore(pos, i, false); + }; + } + + fn nonfinite(self: *Entry) void { + const ca = cases[self.form.case]; + const visible = ca.lens[0] + self.rows_per[0]; + self.f.q[3] = c.toBf16(std.math.nan(f32)); + self.put(0, 1, 0, 0, 7, c.toBf16(std.math.inf(f32)), 0x38, std.math.inf(f32)); + self.put(0, 1, 1, 0, 11, c.toBf16(std.math.inf(f32)), 0x38, std.math.inf(f32)); + if (visible > 1) self.put(0, 1, 1, 1, 11, c.toBf16(-std.math.inf(f32)), 0x38, -std.math.inf(f32)); + self.put(0, 0, 2, visible - 1, 5, c.toBf16(std.math.nan(f32)), 0x7f, 1); + } + + fn stress(self: *Entry) void { + @memset(self.f.q, 0); + for (0..2) |st| for (0..kvh) |head| for (0..self.f.cap) |pos| { + for (0..hd) |d| self.put(st, 0, head, pos, d, 0, 0, 1); + for (0..hd) |d| { + const half = self.f.cap / 2; + const mag: f32 = @floatFromInt(1 + 2 * (d % 8)); + const value = if (pos < half) mag else @as(f32, @intFromBool(pos - half < 8)) - mag; + self.put(st, 1, head, pos, d, c.toBf16(value), code(value), 1); + } + }; + } + + fn prepare(self: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const ca = cases[self.form.case]; + if (shape.rows == 0 or shape.n != qh) return false; + self.rig.reset(); + self.alt.reset(); + if (self.arena) |*old| old.deinit(); + self.arena = .init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.m = shape.rows; + self.rows_per = .{ (self.m + 1) / 2, self.m / 2 }; + const most = @max(ca.lens[0] + self.rows_per[0], ca.lens[1] + self.rows_per[1]); + self.r = try attn.Ref.init(self.rig.gpu.gpa, hd, most); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const cap = (most + ca.ptok - 1) / ca.ptok * ca.ptok; + const np = cap / ca.ptok; + const ids = try a.alloc(u32, 2 * np + 2); + for (ids, 0..) |*id, i| id.* = @intCast(i); + rng.shuffle(u32, ids); + self.f = .{ .c = ca, .format = self.form.format, .cap = cap, .kv = .{ &.{}, &.{} }, .q = try fixture.randoms(a, rng, self.m * qh * hd), .k = &.{}, .v = &.{}, .ids = .{ ids[0..np], ids[np .. 2 * np] }, .pages = ids.len }; + for (&self.f.kv) |*cache| { + cache.* = try a.alloc(u8, fixture.blockBytes(self.form.format, cap, layers)); + for (0..layers) |layer| for (0..2) |part| for (0..kvh) |head| for (0..cap) |pos| { + fixture.Fixture.fill(self.form.format, rng, cache.*, self.f.logical(layer, part, head, pos)); + }; + } + if (fill == .random) self.adversarial(); + switch (fill) { + .random => {}, + .nonfinite => self.nonfinite(), + .stress => self.stress(), + } + const page_bytes = fixture.blockBytes(self.form.format, ca.ptok, layers); + self.pages = try a.alloc(u8, ids.len * page_bytes); + rng.bytes(self.pages); + for (0..2) |st| for (0..layers) |layer| for (0..2) |part| for (0..kvh) |head| for (0..cap) |pos| { + const from = self.f.logical(layer, part, head, pos); + const to = fixture.spans(self.form.format, ca.ptok, layer, part, head, pos % ca.ptok); + for (from, to) |x, y| { + const off = self.f.ids[st][pos / ca.ptok] * page_bytes + y.off; + @memcpy(self.pages[off..][0..y.len], self.f.kv[st][x.off..][0..x.len]); + } + }; + // Requested gate rows change causal depths and therefore which trailing IDs must stay unread. + for (0..2) |st| { + const used = (ca.lens[st] + self.rows_per[st] + ca.ptok - 1) / ca.ptok; + for (self.f.ids[st][used..]) |*id| id.* = @bitCast(@as(i32, -1)); + } + if (self.form.control) { + const used = (ca.lens[0] + self.rows_per[0] + ca.ptok - 1) / ca.ptok; + if (used > 1) std.mem.swap(u32, &self.f.ids[0][0], &self.f.ids[0][used - 1]); + } + var paged: [2]Seg = undefined; + var flat: [2]Seg = undefined; + const rs = try a.alloc(i32, self.m); + const ra = try a.alloc(Ancestor, self.m); + for (0..self.m) |row| { + const st: usize = @intFromBool(row >= self.rows_per[0]); + const local = row - @as(usize, if (st == 0) 0 else self.rows_per[0]); + rs[row] = @intCast(st); + ra[row] = .{ .bits = 0, .depth = @intCast(local), .chain = 1 }; + } + const table_ptrs = try a.alloc(u64, 2); + defer a.free(table_ptrs); + for (0..2) |st| { + table_ptrs[st] = try self.rig.input(std.mem.sliceAsBytes(self.f.ids[st])); + const row0 = @as(usize, if (st == 0) 0 else self.rows_per[0]); + paged[st] = .{ .kv = 0, .cap = @intCast(cap), .len = @intCast(ca.lens[st]), .row0 = @intCast(row0), .rows = @intCast(self.rows_per[st]), .pt = table_ptrs[st], .ps = if (self.form.format == .fp8) page_bytes else page_bytes / 2, .ptok = @intCast(ca.ptok) }; + flat[st] = paged[st]; + flat[st].kv = try self.alt.input(self.f.kv[st]); + flat[st].pt = 0; + flat[st].ps = 0; + flat[st].ptok = 0; + } + self.kv = try self.rig.input(self.pages); + for (&paged) |*sg| sg.kv = self.kv; + self.segs = try self.rig.input(std.mem.sliceAsBytes(&paged)); + self.flat_segs = try self.alt.input(std.mem.sliceAsBytes(&flat)); + self.rowseg = try self.rig.input(std.mem.sliceAsBytes(rs)); + self.rowanc = try self.rig.input(std.mem.sliceAsBytes(ra)); + self.q = try self.rig.input(std.mem.sliceAsBytes(self.f.q)); + const counts: [5]i32 = .{ 0, 0, @intCast(self.m), 2, 0 }; + self.p = try self.rig.input(std.mem.sliceAsBytes(&counts)); + const slots = self.m * qh * chunks; + self.pm = try self.rig.output(slots * 4); + self.pl = try self.rig.output(slots * 4); + self.po = try self.rig.output(slots * hd * 4); + self.out = try self.rig.output(self.mergedBytes()); + self.alt_pm = try self.alt.output(slots * 4); + self.alt_pl = try self.alt.output(slots * 4); + self.alt_po = try self.alt.output(slots * hd * 4); + self.alt_out = try self.alt.output(self.mergedBytes()); + return true; + } + + fn launch(self: *Entry, replacement: bool) !void { + const geo: Geo = .{ .hid = 0, .nk = 0, .nv = 0, .qh = qh, .kvh = kvh, .nl = 0 }; + const layer: c_int = 1; + const segs = if (replacement) self.flat_segs else self.segs; + const pm = if (replacement) self.alt_pm else self.pm; + const pl = if (replacement) self.alt_pl else self.pl; + const po = if (replacement) self.alt_po else self.po; + const out = if (replacement) self.alt_out else self.out; + var args: cuda.Args = .{}; + inline for (.{ geo, self.q, segs, self.rowseg, self.rowanc, layer, self.p, scale, pm, pl, po }) |x| args.add(x); + try cuda.launch.launch(if (replacement) self.contiguous else self.primary, .{ .grid = .{ .x = chunks, .y = kvh, .z = @intCast(self.m) }, .block = .{ .x = 32 * group } }, self.rig.s, &args); + args = .{}; + inline for (.{ geo, pm, pl, po, segs, self.rowseg, self.rowanc, self.p, out }) |x| args.add(x); + try cuda.launch.launch(self.merge, .{ .grid = .{ .x = qh, .y = @intCast(self.m) }, .block = .{ .x = 32 } }, self.rig.s, &args); + } + + fn run(self: *Entry) !void { + try self.launch(false); + try self.rig.s.synchronize(); + } + fn replaced(self: *Entry) ![]const u8 { + try self.launch(true); + return self.alt.outputBytes(); + } + + fn load(self: *Entry, i: usize, head: *attn.Head) !void { + const ca = cases[self.form.case]; + const row = i / qh; + const st: usize = @intFromBool(row >= self.rows_per[0]); + const local = row - @as(usize, if (st == 0) 0 else self.rows_per[0]); + const kh = (i % qh) / group; + head.n = ca.lens[st] + local + 1; + for (head.q, self.f.q[(row * qh + i % qh) * hd ..][0..hd]) |*v, x| v.* = c.fromBf16(x); + for (0..head.n) |pos| for (0..hd) |d| { + head.k[pos * hd + d] = self.f.value(self.f.kv[st], 1, 0, kh, pos, d); + head.v[pos * hd + d] = self.f.value(self.f.kv[st], 1, 1, kh, pos, d); + }; + } + fn reference(_: *Entry, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + fn check(self: *Entry, gate: g.Gate) !?[]const u8 { + const raw = try self.rig.outputBytes(); + return self.r.?.check(self, self.m * qh, scale, raw[self.partialBytes()..], gate); + } +}; + +fn depth(shape: c.Shape) usize { + return shape.k + 64; +} + +pub const Group = struct { + a: std.mem.Allocator, + bf16: ?cuda.Module = null, + fp8: ?cuda.Module = null, + items: [forms.len]Entry = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.bf16 = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + self.fp8 = try cuda.Module.load(gpu.d, cuda.kernels.qwen35_kv8); + const merge = try self.bf16.?.function("tf_q35_attn_merge"); + for (&self.items, forms) |*item, form| { + const mod = if (form.format == .bf16) self.bf16.? else self.fp8.?; + item.* = .{ + .rig = .{ .gpu = gpu, .s = s }, + .alt = .{ .gpu = gpu, .s = s }, + .form = form, + .merge = merge, + .primary = try mod.function(if (form.format == .bf16) "tf_q35_attn_partial_paged" else "tf_q35_attn_partial8_paged"), + .contiguous = try mod.function(if (form.format == .bf16) "tf_q35_attn_partial_contiguous" else "tf_q35_attn_partial8_contiguous"), + }; + self.made += 1; + try kernels.append(a, item.kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + if (self.fp8) |mod| mod.unload(); + if (self.bf16) |mod| mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_qwen_prompt_ab.zig b/zig/tests/cuda/contract_qwen_prompt_ab.zig new file mode 100644 index 00000000000..93a2c58a86a --- /dev/null +++ b/zig/tests/cuda/contract_qwen_prompt_ab.zig @@ -0,0 +1,456 @@ +//! Direct raw-output fixtures for every 256-wide HPATTN prompt kernel and its serving replacement. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const e4m3 = core.quant.fp8.e4m3; + +const D = 256; +const qh = 24; +const kvh = 4; +const group = qh / kvh; +const smem: u32 = 98304; +const scale: f32 = 1.0 / 16.0; +const page_ids = 768; + +const Kind = enum { paged_bf16, paged_fp8, p256, p256_ids, whole_bf16, whole_fp8 }; +const Form = struct { kind: Kind, control: bool = false }; +const forms = [_]Form{ + .{ .kind = .paged_bf16 }, .{ .kind = .paged_bf16, .control = true }, + .{ .kind = .paged_fp8 }, .{ .kind = .paged_fp8, .control = true }, + .{ .kind = .p256 }, .{ .kind = .p256, .control = true }, + .{ .kind = .p256_ids }, .{ .kind = .p256_ids, .control = true }, + .{ .kind = .whole_bf16 }, .{ .kind = .whole_bf16, .control = true }, + .{ .kind = .whole_fp8 }, .{ .kind = .whole_fp8, .control = true }, +}; + +/// Cold chunks, causal/page seams, a second 64-row CTA, 256-page crossings, and the served long-prefix class. +const served = [_]c.Shape{ + .{ .rows = 1, .n = qh, .k = 0 }, + .{ .rows = 6, .n = qh, .k = 47 }, + .{ .rows = 65, .n = qh, .k = 63 }, + .{ .rows = 3, .n = qh, .k = 257 }, + .{ .rows = 16, .n = qh, .k = 4095 }, +}; + +fn isFp8(kind: Kind) bool { + return kind == .paged_fp8 or kind == .whole_fp8; +} +fn isWhole(kind: Kind) bool { + return kind == .whole_bf16 or kind == .whole_fp8; +} +fn isP256(kind: Kind) bool { + return kind == .p256 or kind == .p256_ids; +} +fn ptok(kind: Kind) usize { + return if (isP256(kind)) 256 else 48; +} + +fn symbol(kind: Kind) [:0]const u8 { + return switch (kind) { + .paged_bf16 => "_ZN20tf_prefill_attention13hpattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi", + .paged_fp8 => "_ZN20tf_prefill_attention14hpattn8_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16PKhS5_PKfS7_PS1_iiiiifiPKixi", + .p256 => "_ZN20tf_prefill_attention18hpattn_p256_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi", + .p256_ids => "_ZN20tf_prefill_attention22hpattn_p256_ids_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifiPKixi", + .whole_bf16 => "_ZN20tf_prefill_attention19hpattn_whole_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifi", + .whole_fp8 => "_ZN20tf_prefill_attention20hpattn8_whole_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16PKhS5_PKfS7_PS1_iiiiifi", + }; +} + +fn baseSymbol(kind: Kind) [:0]const u8 { + return switch (kind) { + .p256_ids => symbol(.p256), + .paged_fp8, .whole_fp8 => symbol(.paged_fp8), + else => symbol(.paged_bf16), + }; +} + +fn name(f: Form) []const u8 { + if (f.control) return switch (f.kind) { + .paged_bf16 => "control: hpattn_kernel<256> doubling its score scale", + .paged_fp8 => "control: hpattn8_kernel<256> doubling its score scale", + .p256 => "control: hpattn_p256_kernel<256> doubling its score scale", + .p256_ids => "control: hpattn_p256_ids_kernel<256> doubling its score scale", + .whole_bf16 => "control: hpattn_whole_kernel<256> doubling its score scale", + .whole_fp8 => "control: hpattn8_whole_kernel<256> doubling its score scale", + }; + return switch (f.kind) { + .paged_bf16 => "cuda qwen prompt hpattn_kernel<256, 8, 2, 2>, 48-position pages", + .paged_fp8 => "cuda qwen prompt hpattn8_kernel<256, 8, 2, 2>, 48-position pages", + .p256 => "cuda qwen prompt hpattn_p256_kernel<256, 8, 2, 2>", + .p256_ids => "cuda qwen prompt hpattn_p256_ids_kernel<256, 8, 2, 2>", + .whole_bf16 => "cuda qwen prompt hpattn_whole_kernel<256, 8, 2, 2>", + .whole_fp8 => "cuda qwen prompt hpattn8_whole_kernel<256, 8, 2, 2>", + }; +} + +fn keyChain(s: c.Shape) usize { + return s.k + s.rows + 128; +} + +fn spec(f: Form) c.Spec { + const replacement: ?[]const u8 = if (f.control) null else switch (f.kind) { + .p256 => "hpattn_kernel over the same 256-position pages", + .p256_ids => "hpattn_p256_kernel reading PT for every tile", + .whole_bf16, .whole_fp8 => "the page-aware entry over the identical contiguous cache", + else => null, + }; + return .{ + .name = name(f), + .accum = .f32, + .depth = keyChain, + .ops = if (isFp8(f.kind)) 6 else 4, + .out = .bf16, + .replaces = replacement, + .tiles = .{ .{ .size = 64 }, .{}, .{ .size = 64 } }, + .served = &served, + .sums = .{ .why = attn.why }, + }; +} + +const Prompt = struct { + rig: rig_.Rig, + form: Form, + f: cuda.Function, + base: cuda.Function, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + cap: usize = 0, + pages: usize = 0, + q: std.ArrayList(u16) = .empty, + cache: std.ArrayList(u8) = .empty, + ids: std.ArrayList(i32) = .empty, + dev_q: u64 = 0, + dev_cache: u64 = 0, + dev_ids: u64 = 0, + out: u64 = 0, + alt: u64 = 0, + + fn kernel(self: *Prompt) g.Kernel { + return .{ .spec = spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Prompt); + + fn deinit(self: *Prompt) void { + const a = self.rig.gpu.gpa; + if (self.r) |*r| r.deinit(); + self.q.deinit(a); + self.cache.deinit(a); + self.ids.deinit(a); + self.rig.deinit(); + } + + fn width(self: *const Prompt) usize { + return if (isWhole(self.form.kind)) self.cap else ptok(self.form.kind); + } + + fn pageStride(self: *const Prompt) usize { + return 2 * kvh * self.width() * @as(usize, if (isFp8(self.form.kind)) D + 4 else 2 * D); + } + + fn locate(self: *const Prompt, pos: usize) struct { page: usize, row: usize } { + if (isWhole(self.form.kind)) return .{ .page = 0, .row = pos }; + return .{ .page = @intCast(self.ids.items[pos / self.width()]), .row = pos % self.width() }; + } + + fn offset(self: *const Prompt, value: bool, head: usize, pos: usize, e: usize) usize { + const at = self.locate(pos); + const plane = (@as(usize, @intFromBool(value)) * kvh + head) * self.width() + at.row; + const unit: usize = if (isFp8(self.form.kind)) 1 else 2; + return at.page * self.pageStride() + plane * D * unit + e * unit; + } + + fn scaleOffset(self: *const Prompt, value: bool, head: usize, pos: usize) usize { + const at = self.locate(pos); + const plane = (@as(usize, @intFromBool(value)) * kvh + head) * self.width() + at.row; + return at.page * self.pageStride() + 2 * kvh * self.width() * D + 4 * plane; + } + + fn writeScale(self: *Prompt, value: bool, head: usize, pos: usize, x: f32) void { + std.mem.writeInt(u32, self.cache.items[self.scaleOffset(value, head, pos)..][0..4], @bitCast(x), .little); + } + + fn readScale(self: *const Prompt, value: bool, head: usize, pos: usize) f32 { + return @bitCast(std.mem.readInt(u32, self.cache.items[self.scaleOffset(value, head, pos)..][0..4], .little)); + } + + /// One exact bf16 element, or one e4m3 element and its row's fp32 scale. + fn put(self: *Prompt, value: bool, head: usize, pos: usize, e: usize, bf: u16, code: u8, sc: f32) void { + const at = self.offset(value, head, pos, e); + if (isFp8(self.form.kind)) { + self.cache.items[at] = code; + self.writeScale(value, head, pos, sc); + } else std.mem.writeInt(u16, self.cache.items[at..][0..2], bf, .little); + } + + fn get(self: *const Prompt, value: bool, head: usize, pos: usize, e: usize) f64 { + const at = self.offset(value, head, pos, e); + if (isFp8(self.form.kind)) return e4m3(self.cache.items[at]) * self.readScale(value, head, pos); + return c.fromBf16(std.mem.readInt(u16, self.cache.items[at..][0..2], .little)); + } + + fn prepare(self: *Prompt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != qh or shape.rows == 0) return false; + const a = self.rig.gpu.gpa; + self.shape = shape; + const span = shape.k + shape.rows; + const whole = isWhole(self.form.kind); + const page_width = ptok(self.form.kind); + self.cap = if (whole) span else (span + page_width - 1) / page_width * page_width; + const used = if (whole) 1 else self.cap / page_width; + self.pages = used + @as(usize, @intFromBool(!whole)) * 2; + try self.ids.resize(a, if (whole) 0 else used); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (!whole) { + const order = try a.alloc(i32, self.pages); + defer a.free(order); + for (order, 0..) |*x, i| x.* = @intCast(i); + rng.shuffle(i32, order); + @memcpy(self.ids.items, order[0..used]); + } + try self.cache.resize(a, self.pages * self.pageStride()); + try self.q.resize(a, shape.rows * qh * D); + for (self.q.items) |*x| x.* = attn.normal(rng); + self.fillRandom(rng); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, D, span); + if (fill == .random) self.plantAdversarial(); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + self.dev_q = try self.rig.input(std.mem.sliceAsBytes(self.q.items)); + self.dev_cache = try self.rig.input(self.cache.items); + self.dev_ids = if (whole) 0 else try self.rig.input(std.mem.sliceAsBytes(self.ids.items)); + self.out = try self.rig.output(self.count() * 2); + self.alt = try self.rig.scratch(self.count() * 2); + return true; + } + + fn fillRandom(self: *Prompt, rng: std.Random) void { + for (0..self.pages) |page| for (0..2) |v| for (0..kvh) |h| for (0..self.width()) |row| { + // Spare pages use the same layout but need no page-table entry; address them directly here. + const plane = (v * kvh + h) * self.width() + row; + const unit: usize = if (isFp8(self.form.kind)) 1 else 2; + const off = page * self.pageStride() + plane * D * unit; + if (isFp8(self.form.kind)) { + for (0..D) |e| { + const code = rng.int(u8); + self.cache.items[off + e] = if (code & 0x7f == 0x7f) code ^ 1 else code; + } + const so = page * self.pageStride() + 2 * kvh * self.width() * D + 4 * plane; + const sc = 3.0 / 448.0 * (0.5 + rng.float(f32)); + std.mem.writeInt(u32, self.cache.items[so..][0..4], @bitCast(sc), .little); + } else for (0..D) |e| std.mem.writeInt(u16, self.cache.items[off + 2 * e ..][0..2], attn.normal(rng), .little); + }; + } + + fn score(self: *Prompt, pos: usize, i: usize, changed: bool) void { + self.put(false, 0, pos, 0, c.toBf16(if (changed) 32 else 16), if (changed) toCode(32) else toCode(16), 1); + self.put(false, 0, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0, 1); + self.put(false, 0, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81, 1); + self.put(false, 0, pos, 3, if (i == 0) 0x807f else 0x007f, if (i == 0) 0x87 else 0x07, 1); + self.put(true, 0, pos, 0, c.toBf16(if (changed) 5 else 1 + 2 * @as(f32, @floatFromInt(i))), if (changed) toCode(5) else toCode(1 + 2 * @as(f32, @floatFromInt(i))), 1); + self.put(true, 0, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0, 1); + self.put(true, 0, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81, 1); + self.put(true, 0, pos, 3, if (i == 0) 0x8001 else 0x007f, if (i == 0) 0x81 else 0x07, 1); + self.put(true, 0, pos, 4, if (i == 0) 0x007f else 0x807f, if (i == 0) 0x07 else 0x87, 1); + } + + /// Stable maxima cross key-tile and physical-page boundaries before a later maximum changes. + fn plantAdversarial(self: *Prompt) void { + const q = self.q.items[0..D]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + if (self.shape.rows > 1) { + const other = self.q.items[qh * D ..][0..D]; + @memset(other, 0); + other[0] = c.toBf16(-1); + } + const visible = self.shape.k + 1; + for (0..visible) |pos| self.put(false, 0, pos, 0, 0, 0, 1); + const tile = @min(64, (visible - 1) / 2); + if (tile == 0) return; + const changed = @min(2 * tile, visible - 1); + for ([3]usize{ tile - 1, tile, changed }, 0..) |pos, i| self.score(pos, i, i == 2); + if (!isWhole(self.form.kind) and self.width() < visible) { + for ([2]usize{ self.width() - 1, self.width() }, 0..) |pos, i| { + if (pos != changed) self.score(pos, i, false); + } + } + } + + fn nonfinite(self: *Prompt, value: bool, head: usize, pos: usize, e: usize, x: f32) void { + self.put(value, head, pos, e, c.toBf16(x), 0x38, x); + } + + fn plantNonfinite(self: *Prompt) void { + const span = self.shape.k + self.shape.rows; + self.q.items[3] = c.toBf16(std.math.nan(f32)); + self.nonfinite(true, 0, 0, 7, std.math.inf(f32)); + self.nonfinite(true, 1, @min(1, span - 1), 11, std.math.inf(f32)); + self.nonfinite(true, 1, 0, 11, -std.math.inf(f32)); + self.nonfinite(false, 2, span - 1, 5, std.math.nan(f32)); + } + + fn stress(self: *Prompt, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const span = self.shape.k + self.shape.rows; + const key = try a.alloc(u16, D); + defer a.free(key); + const codes = try a.alloc(u8, D); + defer a.free(codes); + const col = try a.alloc(f32, span); + defer a.free(col); + for (0..kvh) |h| { + for (key, codes) |*b, *code| { + b.* = attn.normal(rng); + code.* = if (rng.boolean()) 0x38 else 0; + } + for (0..span) |pos| for (0..D) |e| self.put(false, h, pos, e, key[e], codes[e], 1.0 / 16.0); + for (0..D) |e| { + if (isFp8(self.form.kind)) mirroredE4m3(rng, col) else attn.mirrored(rng, col); + for (col, 0..) |x, pos| self.put(true, h, pos, e, c.toBf16(x), if (isFp8(self.form.kind)) toCode(x) else 0, 1); + } + } + } + + fn pn(self: *const Prompt) u32 { + return @intCast((self.shape.k + self.shape.rows + 255) / 256); + } + + fn launch(self: *Prompt, replacement: bool, dst: u64) !void { + const kind = self.form.kind; + const whole = isWhole(kind) and !replacement; + const null_table = isWhole(kind) and replacement; + const fp8 = isFp8(kind); + const cache_width = self.width(); + var args: cuda.Args = .{}; + args.add(self.dev_q); + const key_bytes = kvh * cache_width * D * (if (fp8) @as(usize, 1) else 2); + args.add(self.dev_cache); + args.add(self.dev_cache + key_bytes); + if (fp8) { + const scales = self.dev_cache + 2 * kvh * cache_width * D; + args.add(scales); + args.add(scales + kvh * cache_width * 4); + } + args.add(dst); + for ([_]usize{ self.shape.k, self.shape.rows, qh, kvh, group }) |x| args.add(@as(c_int, @intCast(x))); + const sc = scale * (if (self.form.control and !replacement) @as(f32, 2) else 1); + args.add(sc); + args.add(@as(c_int, @intCast(self.cap))); + const ids = if (kind == .p256 or kind == .p256_ids) self.pn() else 0; + if (!whole) { + args.add(if (null_table) @as(u64, 0) else self.dev_ids); + args.add(@as(i64, if (null_table) 0 else @intCast(if (fp8) self.pageStride() else self.pageStride() / 2))); + const last: usize = if (isP256(kind) and !replacement) ids else if (null_table) 1 else cache_width; + args.add(@as(c_int, @intCast(last))); + } + const shared: u32 = smem + if (kind == .p256_ids and !replacement) 4 * ids else 0; + const cfg: cuda.Config = .{ .grid = .{ .x = @intCast((self.shape.rows + 63) / 64), .y = kvh * (group / 2) }, .block = .{ .x = 256 }, .shared = shared }; + try cuda.launch.launch(if (replacement) self.base else self.f, cfg, self.rig.s, &args); + } + + fn run(self: *Prompt) !void { + try self.launch(false, self.out); + try self.rig.s.synchronize(); + } + + fn replaced(self: *Prompt) ![]const u8 { + try self.launch(true, self.alt); + return self.rig.bytes(self.alt, self.count() * 2); + } + + fn count(self: *Prompt) usize { + return self.shape.rows * qh * D; + } + + fn load(self: *Prompt, i: usize, hd: *attn.Head) !void { + const row = i / qh; + const head = i % qh; + const kh = head / group; + for (hd.q, self.q.items[(row * qh + head) * D ..][0..D]) |*y, x| y.* = c.fromBf16(x); + const n = self.shape.k + row + 1; + for (0..n) |pos| for (0..D) |e| { + hd.k[pos * D + e] = self.get(false, kh, pos, e); + hd.v[pos * D + e] = self.get(true, kh, pos, e); + }; + hd.n = n; + } + + fn heads(self: *Prompt) usize { + return self.shape.rows * qh; + } + + fn check(self: *Prompt, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.heads(), scale, try self.rig.outputBytes(), gate); + } + fn reference(self: *Prompt, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.heads(), scale, want, mag); + } + fn simulate(self: *Prompt, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.heads(), scale, acc, order, out); + } +}; + +fn mirroredE4m3(rng: std.Random, out: []f32) void { + const h = out.len / 2; + for (0..h) |i| { + const v: f32 = @floatFromInt(1 + 2 * rng.uintLessThan(u32, 8)); + out[i] = v; + out[h + i] = (if (i < 8 and i % 2 == 0) @as(f32, 1) else 0) - v; + } + if (out.len % 2 == 1) out[out.len - 1] = 0; +} + +fn toCode(v: f32) u8 { + var code: u8 = 0; + while (code < 0x7f) : (code += 1) if (e4m3(code) == @abs(v)) break; + return code | @as(u8, if (v < 0) 0x80 else 0); +} + +pub const Group = struct { + a: std.mem.Allocator, + mod: cuda.Module, + items: [forms.len]Prompt = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + self.* = .{ .a = a, .mod = try cuda.Module.load(gpu.d, cuda.kernels.prefill_attention) }; + errdefer self.mod.unload(); + errdefer for (self.items[0..self.made]) |*item| item.deinit(); + for (forms) |form| { + const f = try self.mod.function(symbol(form.kind)); + const base = try self.mod.function(baseSymbol(form.kind)); + try f.allowDynamicShared(smem + if (form.kind == .p256_ids) 4 * page_ids else 0); + try base.allowDynamicShared(smem); + self.items[self.made] = .{ .rig = .{ .gpu = gpu, .s = s }, .form = form, .f = f, .base = base }; + self.made += 1; + try kernels.append(a, self.items[self.made - 1].kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + self.mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_qwen_tc_ab.zig b/zig/tests/cuda/contract_qwen_tc_ab.zig new file mode 100644 index 00000000000..08d1127b19e --- /dev/null +++ b/zig/tests/cuda/contract_qwen_tc_ab.zig @@ -0,0 +1,440 @@ +//! Raw identity A/B for Qwen3.5's whole-cache TC tiles and cross-stream page joins. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const qp = @import("contract_qwen_pages.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Format = qp.Format; +const Seg = qp.Seg; +const Ancestor = qp.Ancestor; +const hd = qp.hd; +const qh = qp.q_heads; +const kvh = qp.kv_heads; +const group = qh / kvh; +const maxch = qp.max_chunks; +const layers = qp.attentions; +const shared = qp.attn_tiles; +const scale: f32 = 1.0 / 16.0; +const cache_layer: usize = 1; +const layer: c_int = cache_layer; +const geo: qp.Geo = .{ .hid = 0, .nk = 0, .nv = 0, .qh = qh, .kvh = kvh, .nl = 0 }; + +const Mode = enum { partial_whole, rows_whole, rows_join }; +const Form = struct { mode: Mode, format: Format, control: bool = false }; +const forms = [_]Form{ + .{ .mode = .partial_whole, .format = .bf16 }, + .{ .mode = .partial_whole, .format = .fp8 }, + .{ .mode = .rows_whole, .format = .bf16 }, + .{ .mode = .rows_whole, .format = .fp8 }, + .{ .mode = .rows_join, .format = .bf16 }, + .{ .mode = .rows_join, .format = .fp8 }, + .{ .mode = .rows_join, .format = .bf16, .control = true }, + .{ .mode = .rows_join, .format = .fp8, .control = true }, +}; +const short_shapes = [_]c.Shape{ + .{ .rows = 16, .n = qh, .k = 2100 }, + .{ .rows = 64, .n = qh, .k = 700 }, + .{ .rows = 128, .n = qh, .k = 300 }, + .{ .rows = 16, .n = qh, .k = 9000 }, + .{ .rows = 64, .n = qh, .k = 9000 }, + .{ .rows = 64, .n = qh, .k = 5000 }, // 5000/6250/7500/8750: mixed partial and rows in one serving launch +}; +const row_shapes = [_]c.Shape{ + .{ .rows = 3, .n = qh, .k = 8191 }, // rows skips strictly below GROUP_LEN + .{ .rows = 3, .n = qh, .k = 8192 }, + .{ .rows = 16, .n = qh, .k = 9000 }, + .{ .rows = 5, .n = qh, .k = 9000 }, + .{ .rows = 6, .n = qh, .k = 9000 }, + .{ .rows = 3, .n = qh, .k = 32768 }, + .{ .rows = 16, .n = qh, .k = 65535 }, + .{ .rows = 1, .n = qh, .k = 122779 }, + .{ .rows = 64, .n = qh, .k = 9000 }, + .{ .rows = 64, .n = qh, .k = 5000 }, +}; +const join_shapes = [_]c.Shape{ + .{ .rows = 4, .n = qh, .k = 34000 }, + .{ .rows = 8, .n = qh, .k = 33000 }, // one row per sharing stream + .{ .rows = 16, .n = qh, .k = 35000 }, + .{ .rows = 64, .n = qh, .k = 9000 }, + .{ .rows = 64, .n = qh, .k = 5000 }, +}; +const control_shapes = [_]c.Shape{.{ .rows = 8, .n = qh, .k = 34000 }}; + +fn name(f: Form) []const u8 { + if (f.control) return if (f.format == .bf16) "control: cuda tf_q35_attn_rows_join changed shared BF16 page" else "control: cuda tf_q35_attn_rows8_join changed shared FP8 page"; + return switch (f.mode) { + .partial_whole => if (f.format == .bf16) "cuda tf_q35_attn_partial_whole raw PM PL PO OUT" else "cuda tf_q35_attn_partial8_whole raw PM PL PO OUT", + .rows_whole => if (f.format == .bf16) "cuda tf_q35_attn_rows_whole raw PM PL PO OUT" else "cuda tf_q35_attn_rows8_whole raw PM PL PO OUT", + .rows_join => if (f.format == .bf16) "cuda tf_q35_attn_rows_join raw PM PL PO OUT" else "cuda tf_q35_attn_rows8_join raw PM PL PO OUT", + }; +} +fn served(f: Form) []const c.Shape { + if (f.control) return &control_shapes; + return switch (f.mode) { + .partial_whole => &short_shapes, + .rows_whole => &row_shapes, + .rows_join => &join_shapes, + }; +} +fn replaces(f: Form) []const u8 { + return switch (f.mode) { + .partial_whole => if (f.format == .bf16) "tf_q35_attn_partial with page-aware tiles" else "tf_q35_attn_partial8 with page-aware tiles", + .rows_whole => if (f.format == .bf16) "tf_q35_attn_rows with page-aware tiles" else "tf_q35_attn_rows8 with page-aware tiles", + .rows_join => if (f.format == .bf16) "tf_q35_attn_rows, every stream's rows independent" else "tf_q35_attn_rows8, every stream's rows independent", + }; +} +fn seen(a: Ancestor) usize { + return if (a.chain != 0) a.depth + 1 else @popCount(a.bits); +} +fn ptok(shape: c.Shape) usize { + return switch (shape.k) { + 300 => 16, + 700, 8192, 33000 => 48, + 2100, 35000 => 128, + 9000, 32768, 34000 => 256, + else => 512, + }; +} +const SpanPair = @TypeOf(qp.spans(.bf16, 0, 0, 0, 0, 0)); +fn e4m3Code(v: f32) u8 { + var x: u8 = 0; + while (x < 0x7f) : (x += 1) if (core.quant.fp8.e4m3(x) == @abs(v)) break; + return x | @as(u8, if (v < 0) 0x80 else 0); +} + +/// Join cases share a two-layer page arena; whole kernels receive canonical per-stream contiguous caches. +const Host = struct { + ns: usize, + ptok: usize, + page_bytes: usize, + lens: []usize, + caps: []usize, + firsts: []usize, + rowseg: []i32, + anc: []Ancestor, + q: []u16, + tables: [][]u32, + bad: []u32, + arena: []u8, + caches: [][]u8, + + fn span(h: *const Host, format: Format, si: usize, at: usize, value: bool, head: usize, pos: usize, id: usize) SpanPair { + if (h.caches.len != 0) return qp.spans(format, h.caps[si], at, @intFromBool(value), head, pos); + var s = qp.spans(format, h.ptok, at, @intFromBool(value), head, pos % h.ptok); + for (&s) |*x| x.off += id * h.page_bytes; + return s; + } + fn buffer(h: *Host, si: usize) []u8 { + return if (h.caches.len != 0) h.caches[si] else h.arena; + } + fn put(h: *Host, f: Form, value: bool, pos: usize, e: usize, bf: u16, fp: u8) void { + const s = h.span(f.format, 0, cache_layer, value, 0, pos, h.tables[0][pos / h.ptok]); + const out = h.buffer(0); + switch (f.format) { + .bf16 => std.mem.writeInt(u16, out[s[0].off + 2 * e ..][0..2], bf, .little), + .fp8 => { + out[s[0].off + e] = fp; + std.mem.writeInt(u32, out[s[1].off..][0..4], @bitCast(@as(f32, 1)), .little); + }, + } + } + /// Equal maxima at a chunk boundary, a larger next-chunk maximum, exact signed zero and subnormals. + fn adversarial(h: *Host, f: Form) void { + @memset(h.q[0..hd], 0); + h.q[0] = c.toBf16(1); + h.q[1] = 0x8000; + h.q[2] = 0x0001; + h.q[3] = 0x8001; + h.q[4] = 0x007f; + h.q[5] = 0x807f; + for (0..h.lens[0] + h.rowseg.len / h.ns) |pos| h.put(f, false, pos, 0, 0, 0); + const keys = h.lens[0] + seen(h.anc[0]); + const ck = @max(128, (keys + maxch * 128 - 1) / (maxch * 128) * 128); + for ([2]usize{ ck - 1, ck }, 0..) |pos, i| { + h.put(f, false, pos, 0, c.toBf16(16), e4m3Code(16)); + h.put(f, false, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + h.put(f, false, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + h.put(f, false, pos, 3, if (i == 0) 0x807f else 0x007f, if (i == 0) 0x87 else 0x07); + h.put(f, true, pos, 0, c.toBf16(if (i == 0) 1 else 3), e4m3Code(if (i == 0) 1 else 3)); + h.put(f, true, pos, 1, if (i == 0) 0x8000 else 0, if (i == 0) 0x80 else 0); + h.put(f, true, pos, 2, if (i == 0) 0x0001 else 0x8001, if (i == 0) 0x01 else 0x81); + h.put(f, true, pos, 3, if (i == 0) 0x8001 else 0x007f, if (i == 0) 0x81 else 0x07); + } + if (2 * ck < h.lens[0]) { + h.put(f, false, 2 * ck, 0, c.toBf16(32), e4m3Code(32)); + h.put(f, false, 2 * ck, 1, 0x8000, 0x80); + h.put(f, true, 2 * ck, 0, c.toBf16(5), e4m3Code(5)); + h.put(f, true, 2 * ck, 1, 0x0001, 0x01); + } + } + fn nonfinite(h: *Host, f: Form) void { + const p = h.lens[0]; + const out = h.buffer(0); + h.q[3] = 0x7fc1; + h.put(f, true, p - 1, 7, 0x7f80, 0x78); + if (f.format == .fp8) { + const s = h.span(.fp8, 0, cache_layer, true, 0, p - 1, h.tables[0][(p - 1) / h.ptok]); + std.mem.writeInt(u32, out[s[1].off..][0..4], @bitCast(std.math.inf(f32)), .little); + } + if (p >= 3) { + h.put(f, true, p - 2, 11, 0x7f80, 0x78); + h.put(f, true, p - 3, 11, 0xff80, 0xf8); + } + h.put(f, false, p - 1, 3, 0x7fc1, 0x7f); + } + fn stress(h: *Host, f: Form) void { + for (0..h.ns) |si| for (0..kvh) |head| { + const out = h.buffer(si); + for (0..h.caps[si]) |pos| for (0..hd) |e| { + const id = h.tables[si][pos / h.ptok]; + const ks = h.span(f.format, si, cache_layer, false, head, pos, id); + const vs = h.span(f.format, si, cache_layer, true, head, pos, id); + const kv: f32 = if (e == 0) 0.25 else 0; + const vv: f32 = if (pos < 2048) (if (pos % 2 == 0) 128 else -128) else 0; + switch (f.format) { + .bf16 => { + std.mem.writeInt(u16, out[ks[0].off + 2 * e ..][0..2], c.toBf16(kv), .little); + std.mem.writeInt(u16, out[vs[0].off + 2 * e ..][0..2], c.toBf16(if (e == 0) vv else 0), .little); + }, + .fp8 => { + out[ks[0].off + e] = e4m3Code(kv); + out[vs[0].off + e] = e4m3Code(if (e == 0) vv else 0); + if (e == 0) { + std.mem.writeInt(u32, out[ks[1].off..][0..4], @bitCast(@as(f32, 1)), .little); + std.mem.writeInt(u32, out[vs[1].off..][0..4], @bitCast(@as(f32, 1)), .little); + } + }, + } + }; + }; + } +}; + +fn makeHost(a: std.mem.Allocator, shape: c.Shape, f: Form, fill: g.Fill, seed: u64) !Host { + const join = f.mode == .rows_join; + const ns = if (join) (if (shape.rows <= 8) shape.rows else 4) else if (shape.rows > 64) 1 else (shape.rows + 15) / 16; + const per = ptok(shape); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + var h: Host = .{ .ns = ns, .ptok = per, .page_bytes = qp.blockBytes(f.format, per, layers), .lens = try a.alloc(usize, ns), .caps = try a.alloc(usize, ns), .firsts = try a.alloc(usize, ns), .rowseg = try a.alloc(i32, shape.rows), .anc = try a.alloc(Ancestor, shape.rows), .q = try qp.randoms(a, rng, shape.rows * qh * hd), .tables = try a.alloc([]u32, ns), .bad = undefined, .arena = undefined, .caches = try a.alloc([]u8, if (join) 0 else ns) }; + var np: usize = 0; + for (0..ns) |si| { + h.firsts[si] = if (join) si * shape.rows / ns else @min(si * 16, shape.rows); + const end = if (si + 1 == ns) shape.rows else if (join) (si + 1) * shape.rows / ns else @min((si + 1) * 16, shape.rows); + h.lens[si] = shape.k + if (join and shape.k != 5000) si * 500 else si * shape.k / ns; + h.caps[si] = h.lens[si] + end - h.firsts[si]; + const pages = (h.caps[si] + per - 1) / per; + np = @max(np, pages); + h.tables[si] = try a.alloc(u32, pages); + for (h.firsts[si]..end) |r| { + h.rowseg[r] = @intCast(si); + const j = r - h.firsts[si]; + if (ns == 1 and shape.rows > 64) { + h.anc[r] = .{ .bits = 0, .depth = @intCast(j), .chain = 1 }; + } else { + const parent: ?usize = if (j == 0 or rng.uintLessThan(u32, 6) == 0) null else rng.uintLessThan(usize, j); + const bits = if (parent) |p| h.anc[h.firsts[si] + p].bits else 0; + h.anc[r] = .{ .bits = bits | (@as(u64, 1) << @intCast(j)), .depth = 0, .chain = 0 }; + } + } + } + h.arena = try a.alloc(u8, if (join) (ns * np + 1) * h.page_bytes else 0); + rng.bytes(h.arena); + for (0..ns) |si| { + const common = if (join) h.tables[si].len -| 2 else 0; + for (h.tables[si], 0..) |*id, p| id.* = @intCast(if (p < common) p else si * np + (np - 1 - p)); + if (join) { + for (0..layers) |at| for (0..2) |value| for (0..kvh) |head| for (0..h.tables[si].len * per) |pos| { + const id = h.tables[si][pos / per]; + qp.Fixture.fill(f.format, rng, h.arena, h.span(f.format, si, at, value != 0, head, pos, @intCast(id))); + }; + } else { + h.caches[si] = try a.alloc(u8, qp.blockBytes(f.format, h.caps[si], layers)); + for (0..layers) |at| for (0..2) |value| for (0..kvh) |head| for (0..h.caps[si]) |pos| { + qp.Fixture.fill(f.format, rng, h.caches[si], qp.spans(f.format, h.caps[si], at, value, head, pos)); + }; + } + } + if (join) { + h.bad = try a.dupe(u32, h.tables[ns - 1]); + const copy = ns * np; + @memcpy(h.arena[copy * h.page_bytes ..][0..h.page_bytes], h.arena[0..h.page_bytes]); + const plant = qp.spans(f.format, per, cache_layer, 1, 0, 7); + switch (f.format) { + .bf16 => { + const at = h.arena[copy * h.page_bytes + plant[0].off + 6 ..][0..2]; + std.mem.writeInt(u16, at, if (std.mem.readInt(u16, at, .little) == 0x3f40) 0x3e80 else 0x3f40, .little); + }, + .fp8 => { + const at = &h.arena[copy * h.page_bytes + plant[0].off + 3]; + at.* ^= 0x40; + if (at.* & 0x7f == 0x7f) at.* ^= 1; + }, + } + h.bad[0] = @intCast(copy); + } else h.bad = try a.alloc(u32, 0); + if (fill == .random and !f.control) h.adversarial(f); + switch (fill) { + .random => {}, + .nonfinite => h.nonfinite(f), + .stress => h.stress(f), + } + return h; +} + +const Bind = struct { q: u64, segs: u64, rowseg: u64, rowanc: u64, pm: u64, pl: u64, po: u64, out: u64 }; +fn bind(rig: *rig_.Rig, a: std.mem.Allocator, h: *const Host, f: Form, bad: bool) !Bind { + const paged = f.mode == .rows_join; + const kv = if (paged) try rig.input(h.arena) else 0; + const segs = try a.alloc(Seg, h.ns); + defer a.free(segs); + for (segs, 0..) |*s, si| { + const end = if (si + 1 == h.ns) h.rowseg.len else h.firsts[si + 1]; + const table = if (bad and si + 1 == h.ns) h.bad else h.tables[si]; + s.* = .{ .kv = if (paged) kv else try rig.input(h.caches[si]), .cap = @intCast(if (paged) table.len * h.ptok else h.caps[si]), .len = @intCast(h.lens[si]), .row0 = @intCast(h.firsts[si]), .rows = @intCast(end - h.firsts[si]) }; + if (paged) { + s.pt = try rig.input(std.mem.sliceAsBytes(table)); + s.ps = if (f.format == .fp8) h.page_bytes else h.page_bytes / 2; + s.ptok = @intCast(h.ptok); + s.pn = @intCast(table.len); + } + } + const slots = h.rowseg.len * qh * maxch; + return .{ .q = try rig.input(std.mem.sliceAsBytes(h.q)), .segs = try rig.input(std.mem.sliceAsBytes(segs)), .rowseg = try rig.input(std.mem.sliceAsBytes(h.rowseg)), .rowanc = try rig.input(std.mem.sliceAsBytes(h.anc)), .pm = try rig.output(slots * 4), .pl = try rig.output(slots * 4), .po = try rig.output(slots * hd * 4), .out = try rig.output(h.rowseg.len * qh * hd * 2) }; +} + +const Entry = struct { + rig: rig_.Rig, + base: rig_.Rig, + form: Form, + partial: cuda.Function, + original_partial: cuda.Function, + rows: cuda.Function, + original_rows: cuda.Function, + merge: cuda.Function, + msg: [160]u8 = undefined, + arena: ?std.heap.ArenaAllocator = null, + host: ?Host = null, + dev: Bind = undefined, + base_dev: Bind = undefined, + + fn deinit(e: *Entry) void { + e.rig.deinit(); + e.base.deinit(); + if (e.arena) |*a| a.deinit(); + } + fn kernel(e: *Entry) g.Kernel { + return .{ .ctx = e, .vt = &vt, .control = if (e.form.control) .shapes else null, .spec = .{ .name = name(e.form), .accum = .none, .depth = 0, .out = .raw, .replaces = replaces(e.form), .served = served(e.form), .nan = .{ .stated = "raw PM PL PO OUT, poisoned unwritten slots, NaN and infinities" } } }; + } + const vt = g.hooks(Entry); + fn prepare(e: *Entry, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != qh or shape.k == 0) return false; + e.rig.reset(); + e.base.reset(); + if (e.arena) |*a| a.deinit(); + e.arena = .init(e.rig.gpu.gpa); + const a = e.arena.?.allocator(); + e.host = try makeHost(a, shape, e.form, fill, seed); + e.dev = try bind(&e.rig, a, &e.host.?, e.form, e.form.control); + e.base_dev = try bind(&e.base, a, &e.host.?, e.form, false); + return true; + } + fn launch(e: *Entry, rig: *rig_.Rig, b: Bind, primary: bool) !void { + const rows = e.host.?.rowseg.len; + var args: cuda.Args = .{}; + inline for (.{ geo, b.q, b.segs, b.rowseg, b.rowanc, layer, @as(u64, 0), scale }) |v| args.add(v); + inline for (.{ b.pm, b.pl, b.po }) |v| args.add(v); + const sm = if (e.form.format == .bf16) shared else 0; + try cuda.launch.launch(if (primary) e.partial else e.original_partial, .{ .grid = .{ .x = @intCast(rows), .y = maxch, .z = kvh }, .block = .{ .x = 128 }, .shared = sm }, rig.s, &args); + args = .{}; + inline for (.{ geo, b.q, b.segs, b.rowseg, b.rowanc, layer, @as(u64, 0), scale }) |v| args.add(v); + args.add(@as(c_int, @intCast(rows))); + inline for (.{ b.pm, b.pl, b.po }) |v| args.add(v); + const tiles = 64 / group; + try cuda.launch.launch(if (primary) e.rows else e.original_rows, .{ .grid = .{ .x = @intCast((rows + tiles - 1) / tiles), .y = maxch, .z = kvh }, .block = .{ .x = 256 }, .shared = sm }, rig.s, &args); + args = .{}; + inline for (.{ geo, b.pm, b.pl, b.po, b.segs, b.rowseg, b.rowanc, @as(u64, 0), b.out }) |v| args.add(v); + try cuda.launch.launch(e.merge, .{ .grid = .{ .x = qh, .y = @intCast(rows) }, .block = .{ .x = 32 } }, rig.s, &args); + try rig.s.synchronize(); + if (!try rig.intact() or rig.overlap()) return error.GuardChanged; + } + fn run(e: *Entry) !void { + try e.launch(&e.rig, e.dev, true); + } + fn replaced(e: *Entry) ![]const u8 { + try e.launch(&e.base, e.base_dev, false); + return e.base.outputBytes(); + } + fn count(e: *const Entry) usize { + const rows = e.host.?.rowseg.len; + return rows * qh * (maxch * (8 + hd * 4) + hd * 2); + } + fn reference(_: *Entry, _: []f64, _: []f64) !void { + return error.RawIdentityUsesReplacement; + } + fn check(e: *Entry, at: g.Gate) !?[]const u8 { + if (at != .nonfinite) return null; + const got = try e.rig.outputBytes(); + const want = try e.replaced(); + if (!std.mem.eql(u8, got, want)) return try std.fmt.bufPrint(&e.msg, "nonfinite primary and replacement raw bytes differ", .{}); + const out_n = e.host.?.rowseg.len * qh * hd; + const out = got[got.len - out_n * 2 ..]; + var finite: usize = 0; + var nan: usize = 0; + var inf: usize = 0; + for (0..out_n) |i| { + const bits = std.mem.readInt(u16, out[2 * i ..][0..2], .little); + if (bits & 0x7f80 != 0x7f80) finite += 1 else if (bits & 0x007f == 0) inf += 1 else nan += 1; + } + if (finite == 0 or nan == 0 or inf == 0) return try std.fmt.bufPrint(&e.msg, "planted output classes finite={d}, NaN={d}, infinity={d}: no proof", .{ finite, nan, inf }); + return null; + } +}; + +/// The six primary exports plus one planted changed-page control for each cache format. +pub const Group = struct { + a: std.mem.Allocator, + bf16: ?cuda.Module = null, + fp8: ?cuda.Module = null, + items: [forms.len]Entry = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + self.* = .{ .a = a }; + errdefer self.destroy(); + self.bf16 = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + self.fp8 = try cuda.Module.load(gpu.d, cuda.kernels.qwen35_kv8); + const merge = try self.bf16.?.function("tf_q35_attn_merge"); + for (forms) |f| { + const mod = if (f.format == .bf16) self.bf16.? else self.fp8.?; + const whole = f.mode != .rows_join; + const partial_name: [:0]const u8 = if (f.format == .fp8) + (if (whole) "tf_q35_attn_partial8_whole" else "tf_q35_attn_partial8") + else + (if (whole) "tf_q35_attn_partial_whole" else "tf_q35_attn_partial"); + const rows_name: [:0]const u8 = switch (f.mode) { + .partial_whole, .rows_whole => if (f.format == .fp8) "tf_q35_attn_rows8_whole" else "tf_q35_attn_rows_whole", + .rows_join => if (f.format == .fp8) "tf_q35_attn_rows8_join" else "tf_q35_attn_rows_join", + }; + const original_partial_name: [:0]const u8 = if (f.format == .fp8) "tf_q35_attn_partial8" else "tf_q35_attn_partial"; + const original_rows_name: [:0]const u8 = if (f.format == .fp8) "tf_q35_attn_rows8" else "tf_q35_attn_rows"; + const fns = [4]cuda.Function{ try mod.function(partial_name), try mod.function(original_partial_name), try mod.function(rows_name), try mod.function(original_rows_name) }; + if (f.format == .bf16) for (fns) |function| try function.allowDynamicShared(shared); + self.items[self.made] = .{ .rig = .{ .gpu = gpu, .s = s }, .base = .{ .gpu = gpu, .s = s }, .form = f, .partial = fns[0], .original_partial = fns[1], .rows = fns[2], .original_rows = fns[3], .merge = merge }; + self.made += 1; + try kernels.append(a, self.items[self.made - 1].kernel()); + } + return self; + } + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*e| e.deinit(); + if (self.fp8) |m| m.unload(); + if (self.bf16) |m| m.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_qwen_tree_ab.zig b/zig/tests/cuda/contract_qwen_tree_ab.zig new file mode 100644 index 00000000000..0437b767cb4 --- /dev/null +++ b/zig/tests/cuda/contract_qwen_tree_ab.zig @@ -0,0 +1,348 @@ +//! Raw identity A/B coverage for Qwen3.6 MTP tree attention at its actual CUDA ABI. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const heads = 16; +const kv_heads = 2; +const hd = 256; +const width = kv_heads * hd; +const gstride = heads * 2 * hd; +const lanes = 64; +const anc_stride = lanes + 1; +const nan_bits: u16 = 0x7fc0; + +/// k is live ring slots and n is heads times head_dim; cases cover root/no-ring, prefetch and long context. +const served = [_]c.Shape{ + .{ .rows = 1, .n = heads * hd, .k = 0 }, + .{ .rows = 1, .n = heads * hd, .k = 6 }, + .{ .rows = 15, .n = heads * hd, .k = 6 }, + .{ .rows = 16, .n = heads * hd, .k = 6 }, + .{ .rows = 17, .n = heads * hd, .k = 6 }, + .{ .rows = 64, .n = heads * hd, .k = 6 }, + .{ .rows = 4, .n = heads * hd, .k = 9 }, + .{ .rows = 4, .n = heads * hd, .k = 4200 }, +}; + +const Form = struct { wrapped: bool, control: bool = false, name: []const u8 }; +const forms = [_]Form{ + .{ .wrapped = false, .name = "cuda qwen3.6 mtp tree attention tf_q36m_attn_tree, contiguous ring" }, + .{ .wrapped = true, .name = "cuda qwen3.6 mtp tree attention tf_q36m_attn_tree, wrapping ring" }, + .{ .wrapped = false, .control = true, .name = "control: qwen tree attention dropping row zero's last ancestor" }, + .{ .wrapped = true, .control = true, .name = "control: wrapping qwen tree attention dropping row zero's last ancestor" }, +}; + +fn depth(s: c.Shape) usize { + return 2 * (s.k + lanes + 1) + 16; +} + +fn spec(form: Form) c.Spec { + return .{ + .name = form.name, + .accum = .f32, + .depth = depth, + .ops = 2, + .mids = 1, // o / l is rounded to bf16 before the gate product + .out = .bf16, + .served = &served, + .sums = .{ .why = attn.why }, + }; +} + +const Tree = struct { + rig: rig_.Rig, + f: cuda.Function, + form: Form, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + fill: g.Fill = .random, + cap: usize = 0, + begin: usize = 0, + q: []u16 = &.{}, + gate: []u16 = &.{}, + kb: []u16 = &.{}, + vb: []u16 = &.{}, + lk: []u16 = &.{}, + lv: []u16 = &.{}, + rk: []u16 = &.{}, + rv: []u16 = &.{}, + anc: []i32 = &.{}, + dev: [9]u64 = @splat(0), + out: u64 = 0, + + fn kernel(self: *Tree) g.Kernel { + return .{ .spec = spec(self.form), .ctx = self, .vt = &vt, .control = if (self.form.control) .shapes else null }; + } + const vt = g.hooks(Tree); + + fn deinit(self: *Tree) void { + self.rig.deinit(); + self.arena.deinit(); + } + + /// Controls drop one ancestor while row zero still expects two, so the shapes gate genuinely fails. + fn ancestors(self: *const Tree, row: usize) usize { + const n: usize = @intCast(self.anc[row * anc_stride]); + return if (self.form.control and row == 0) 2 else n; + } + + fn terms(self: *const Tree, row: usize) usize { + return self.shape.k + self.ancestors(row) + 1; + } + + /// Ring terms first, then root-to-parent ancestors from LK/LV, then this row's KB/VB. + fn term(self: *Tree, row: usize, j: usize, kvh: usize, value_side: bool) []u16 { + if (j < self.shape.k) { + const at = ((self.begin + j) % self.cap) * width + kvh * hd; + return (if (value_side) self.rv else self.rk)[at..][0..hd]; + } + const path = j - self.shape.k; + if (path < self.ancestors(row)) { + const lane: usize = @intCast(self.anc[row * anc_stride + 1 + path]); + return (if (value_side) self.lv else self.lk)[lane * width + kvh * hd ..][0..hd]; + } + return (if (value_side) self.vb else self.kb)[row * width + kvh * hd ..][0..hd]; + } + + fn prepare(self: *Tree, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > lanes or shape.n != heads * hd or shape.k > 4200) return false; + self.rig.reset(); + _ = self.arena.reset(.free_all); + const a = self.arena.allocator(); + self.shape = shape; + self.fill = fill; + self.cap = if (self.form.wrapped) 32768 else @max(7, shape.k + 1); + self.begin = if (self.form.wrapped) self.cap - 3 else 0; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows = shape.rows; + self.q = try a.alloc(u16, rows * heads * hd); + self.gate = try a.alloc(u16, rows * gstride); + self.kb = try a.alloc(u16, rows * width); + self.vb = try a.alloc(u16, rows * width); + self.lk = try a.alloc(u16, lanes * width); + self.lv = try a.alloc(u16, lanes * width); + self.rk = try a.alloc(u16, self.cap * width); + self.rv = try a.alloc(u16, self.cap * width); + self.anc = try a.alloc(i32, rows * anc_stride); + @memset(self.anc, -1); + + // Paths cover roots, variable depths and a two-ancestor row zero; unnamed lanes stay NaN. + for (0..rows) |row| { + const n = if (row == 0) @as(usize, 2) else @min(row, row % 4); + self.anc[row * anc_stride] = @intCast(n); + const paths = [_][3]i32{ .{ 3, 1, -1 }, .{ 2, -1, -1 }, .{ 3, 1, -1 }, .{ 4, 3, 1 } }; + const selected = paths[if (row == 0) 0 else row % 4]; + for (0..n) |j| self.anc[row * anc_stride + 1 + j] = selected[j]; + } + if (self.form.control) self.anc[0] = 1; + + for (self.q) |*x| x.* = if (fill == .stress) 0 else number(rng, 0.5); + for (self.gate) |*x| x.* = if (fill == .stress) 0 else number(rng, 4); + for (self.kb) |*x| x.* = if (fill == .stress) 0 else number(rng, 0.5); + @memset(self.lk, nan_bits); + @memset(self.lv, nan_bits); + @memset(self.rk, nan_bits); + @memset(self.rv, nan_bits); + for (0..shape.k) |j| { + const at = ((self.begin + j) % self.cap) * width; + for (0..width) |i| self.rk[at + i] = if (fill == .stress) 0 else number(rng, 0.5); + self.values(self.rv[at..][0..width], j, rng); + } + for (0..rows) |row| for (0..self.ancestors(row)) |j| { + const lane: usize = @intCast(self.anc[row * anc_stride + 1 + j]); + for (0..width) |i| self.lk[lane * width + i] = if (fill == .stress) 0 else number(rng, 0.5); + self.values(self.lv[lane * width ..][0..width], shape.k + j, rng); + }; + // Own keys are the final term, after all ancestors. + for (0..rows) |row| self.values(self.vb[row * width ..][0..width], shape.k + self.ancestors(row), rng); + + if (fill == .nonfinite) self.plantNonfinite(); + if (fill == .random) self.plantAdversarial(); + + for ([_][]const u8{ + std.mem.sliceAsBytes(self.q), std.mem.sliceAsBytes(self.gate), + std.mem.sliceAsBytes(self.kb), std.mem.sliceAsBytes(self.vb), + std.mem.sliceAsBytes(self.lk), std.mem.sliceAsBytes(self.lv), + std.mem.sliceAsBytes(self.anc), std.mem.sliceAsBytes(self.rk), + std.mem.sliceAsBytes(self.rv), + }, &self.dev) |bytes, *p| p.* = try self.rig.input(bytes); + self.out = try self.rig.output(rows * heads * hd * 2); + return true; + } + + fn number(rng: std.Random, scale: f32) u16 { + return c.toBf16((rng.float(f32) - 0.5) * scale); + } + + /// Stress values make fp32 exact under every reduction order but lower-precision sums red. + fn values(self: *const Tree, out: []u16, j: usize, rng: std.Random) void { + const stress = self.fill == .stress; + for (out, 0..) |*x, i| { + x.* = if (stress) c.toBf16(([3]f32{ 4096, 1, -4096 })[(j + i / hd) % 3]) else number(rng, 0.5); + } + } + + fn plantNonfinite(self: *Tree) void { + self.q[hd + 3] = nan_bits; // row zero, query head one + if (self.shape.k > 0) { + const at = (self.begin % self.cap) * width; + self.rk[at] = c.toBf16(std.math.inf(f32)); + self.rv[at + 7] = c.toBf16(std.math.inf(f32)); + } + self.lk[3 * width + hd + 5] = nan_bits; + self.lv[3 * width + hd + 9] = c.toBf16(-std.math.inf(f32)); + self.vb[hd + 11] = c.toBf16(std.math.inf(f32)); + } + + /// A score/value pair with exact signed-zero and representable-subnormal inputs. + fn pair(self: *Tree, j: usize, score: f32, value: f32, odd: bool) void { + const key = self.term(0, j, 0, false); + const val = self.term(0, j, 0, true); + key[0] = c.toBf16(score); + key[1] = if (odd) 0 else 0x8000; + key[2] = if (odd) 0x8001 else 0x0001; + key[3] = if (odd) 0x007f else 0x807f; + val[0] = c.toBf16(value); + val[1] = if (odd) 0 else 0x8000; + val[2] = if (odd) 0x8001 else 0x0001; + val[3] = if (odd) 0x8001 else 0x007f; + val[4] = if (odd) 0x807f else 0x007f; + } + + /// Ring maxima tie across the prefetch seam; ancestors change then tie the maximum, and the own key always runs. + fn plantAdversarial(self: *Tree) void { + const q = self.q[0..hd]; + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.terms(0)) |j| self.term(0, j, 0, false)[0] = 0; + if (self.shape.k > 0) { + self.pair(0, 16, 1, false); + self.pair(if (self.shape.k > 8) 8 else self.shape.k - 1, 16, 3, true); + } + const own = self.terms(0) - 1; + if (self.ancestors(0) >= 2) { + self.pair(self.shape.k, 16, 5, false); + self.pair(self.shape.k + 1, 32, 7, true); + self.pair(own, 32, 9, false); + } else self.pair(own, 32, 5, false); + self.gate[hd] = 0x8000; + self.gate[hd + 1] = 0x0001; + self.gate[hd + 2] = 0x8001; + self.gate[hd + 3] = 0x007f; + self.gate[hd + 4] = 0x807f; + } + + fn run(self: *Tree) !void { + var args: cuda.Args = .{}; + args.add(self.dev[0]); + args.add(self.dev[1]); + args.add(@as(c_int, gstride)); + for (self.dev[2..7]) |p| args.add(p); + args.add(@as(c_int, anc_stride)); + args.add(self.dev[7]); + args.add(self.dev[8]); + args.add(@as(c_int, heads)); + args.add(@as(c_int, kv_heads)); + args.add(@as(c_int, @intCast(self.cap))); + args.add(@as(c_longlong, @intCast(self.begin))); + args.add(@as(c_longlong, @intCast(self.begin + self.shape.k))); + args.add(self.out); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(self.shape.rows), .y = heads }, .block = .{ .x = 32 } }, self.rig.s, &args); + try self.rig.s.synchronize(); + } + + fn count(self: *const Tree) usize { + return self.shape.rows * heads * hd; + } + + fn reference(self: *Tree, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + for (0..self.shape.rows) |row| for (0..heads) |h| { + const kvh = h / (heads / kv_heads); + const scores = try a.alloc(f64, self.terms(row)); + defer a.free(scores); + for (scores, 0..) |*score, j| { + var dot: f64 = 0; + for (self.q[(row * heads + h) * hd ..][0..hd], self.term(row, j, kvh, false)) |x, k| dot += c.fromBf16(x) * c.fromBf16(k); + score.* = dot / 16; + } + const top = std.mem.max(f64, scores); + var total: f64 = 0; + for (scores) |*score| { + score.* = @exp(score.* - top); + total += score.*; + } + for (0..hd) |d| { + var sum: f64 = 0; + var most: f64 = 0; + for (scores, 0..) |weight, j| { + const v = c.fromBf16(self.term(row, j, kvh, true)[d]); + sum += weight * v; + most = @max(most, @abs(v)); + } + const gate = 1 / (1 + @exp(-c.fromBf16(self.gate[row * gstride + h * 2 * hd + hd + d]))); + const at = (row * heads + h) * hd + d; + want[at] = sum / total * gate; + mag[at] = most * gate; + } + }; + } + + fn simulate(self: *Tree, acc: c.Accum, order: g.Order, out: []f64) !void { + const a = self.rig.gpu.gpa; + for (0..self.shape.rows) |row| { + const weights = try a.alloc(f64, self.terms(row)); + defer a.free(weights); + for (0..heads) |h| for (0..hd) |d| { + for (weights, 0..) |*x, j| x.* = c.fromBf16(self.term(row, j, h / (heads / kv_heads), true)[d]); + const sum = core.contract.rows.sumIn(acc, order, weights); + const mean: f32 = @floatCast(sum / @as(f64, @floatFromInt(weights.len))); + out[(row * heads + h) * hd + d] = c.fromBf16(c.toBf16(c.fromBf16(c.toBf16(mean)) * 0.5)); + }; + } + } +}; + +/// Both actual ring forms and their planted mask controls, at stable heap addresses. +pub const Group = struct { + a: std.mem.Allocator, + mod: cuda.Module, + items: [forms.len]Tree = undefined, + made: usize = 0, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + self.* = .{ .a = a, .mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen36_mtp) }; + errdefer self.mod.unload(); + errdefer for (self.items[0..self.made]) |*item| item.deinit(); + for (forms) |form| { + self.items[self.made] = .{ + .rig = .{ .gpu = gpu, .s = s }, + .f = try self.mod.function("tf_q36m_attn_tree"), + .form = form, + .arena = .init(a), + }; + self.made += 1; + try kernels.append(a, self.items[self.made - 1].kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (self.items[0..self.made]) |*item| item.deinit(); + self.mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_qwen_vision_attn.zig b/zig/tests/cuda/contract_qwen_vision_attn.zig new file mode 100644 index 00000000000..70b2c84d001 --- /dev/null +++ b/zig/tests/cuda/contract_qwen_vision_attn.zig @@ -0,0 +1,208 @@ +//! tf_qv_attention64/72: segmented full image attention under the raw-output contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const served = [_]c.Shape{ + .{ .rows = 1, .n = 1, .k = 1 }, + .{ .rows = 1, .n = 130, .k = 130 }, + .{ .rows = 2, .n = 192, .k = 64 }, + .{ .rows = 2, .n = 196, .k = 65 }, + .{ .rows = 16, .n = 130, .k = 130 }, +}; + +fn spec(name: []const u8, hd: usize) c.Spec { + return .{ .name = name, .accum = .f32, .depth = struct { + fn depth(s: c.Shape) usize { + return s.k + 64; + } + }.depth, .ops = 6, .out = .bf16, .tiles = .{ .{}, .{ .size = 64 }, .{ .size = hd } }, .served = &served, .sums = .{ .why = attn.why } }; +} + +pub const Attention = struct { + rig: rig_.Rig, + f: cuda.Function, + name: []const u8, + hd: usize, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + qkv: std.ArrayList(u16) = .empty, + dev: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn kernel(self: *Attention) g.Kernel { + return .{ .spec = spec(self.name, self.hd), .ctx = self, .vt = &vt }; + } + const vt = g.hooks(Attention); + + pub fn deinit(self: *Attention) void { + if (self.r) |*r| r.deinit(); + self.qkv.deinit(self.rig.gpu.gpa); + self.rig.deinit(); + } + + fn at(self: *Attention, which: usize, row: usize, head: usize) []u16 { + const plane = self.shape.rows * self.shape.n * self.hd; + const offset = which * plane + (head * self.shape.n + row) * self.hd; + return self.qkv.items[offset..][0..self.hd]; + } + + pub fn prepare(self: *Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > shape.n) return false; + self.rig.reset(); + self.shape = shape; + const a = self.rig.gpu.gpa; + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, self.hd, shape.k); + try self.qkv.resize(a, 3 * self.count()); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (self.qkv.items) |*x| x.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plantNonfinite(), + .stress => try self.stress(rng), + } + if (fill == .random) self.plantAdversarial(); + for (0..3) |which| self.dev[which] = try self.rig.input(std.mem.sliceAsBytes(self.qkv.items[which * self.count() ..][0..self.count()])); + self.out = try self.rig.output(self.count() * 2); + return true; + } + + fn plantNonfinite(self: *Attention) void { + const last = self.shape.n - 1; + if (self.count() > self.hd) self.at(0, 0, 0)[3] = c.toBf16(std.math.nan(f32)); + self.at(2, last, 0)[7] = c.toBf16(std.math.inf(f32)); + self.at(2, self.shape.n / 2, 0)[9] = c.toBf16(-std.math.inf(f32)); + if (self.shape.rows > 1) self.at(1, self.shape.n / 3, 1)[5] = c.toBf16(std.math.nan(f32)); + } + + fn plantAdversarial(self: *Attention) void { + const q = self.at(0, 0, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.shape.n) |row| @memset(self.at(1, row, 0), 0); + const tile = @min(64, (self.shape.k - 1) / 2); + if (tile == 0) return; + const spots = if (self.shape.k > 65) + [3]usize{ 63, 64, @min(128, self.shape.k - 1) } + else + [3]usize{ tile - 1, tile, @min(2 * tile, self.shape.k - 1) }; + for (spots, 0..) |row, i| { + const key = self.at(1, row, 0); + key[0] = c.toBf16(if (i < 2) 16 else 32); + key[1] = if (i == 0) 0x8000 else 0; + key[2] = if (i == 0) 0x0001 else 0x8001; + key[3] = if (i == 0) 0x807f else 0x007f; + const value = self.at(2, row, 0); + value[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + value[1] = if (i == 0) 0x8000 else 0; + value[2] = if (i == 0) 0x0001 else 0x8001; + value[3] = if (i == 0) 0x8001 else 0x007f; + value[4] = if (i == 0) 0x007f else 0x807f; + } + } + + fn stress(self: *Attention, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const key = try a.alloc(u16, self.hd); + defer a.free(key); + const col = try a.alloc(f32, self.shape.k); + defer a.free(col); + for (0..self.shape.rows) |head| { + for (key) |*x| x.* = attn.normal(rng); + for (0..self.shape.n) |row| @memcpy(self.at(1, row, head), key); + var start: usize = 0; + while (start < self.shape.n) { + const len = @min(self.shape.k, self.shape.n - start); + for (0..self.hd) |e| { + attn.mirrored(rng, col[0..len]); + for (col[0..len], 0..) |x, j| self.at(2, start + j, head)[e] = c.toBf16(x); + } + start += len; + } + } + } + + pub fn run(self: *Attention) !void { + var start: usize = 0; + while (start < self.shape.n) { + const len = @min(self.shape.k, self.shape.n - start); + var args: cuda.Args = .{}; + for (self.dev) |p| args.add(p); + args.add(self.out); + for ([_]usize{ self.shape.n, self.shape.rows, start, len }) |x| args.add(@as(c_int, @intCast(x))); + args.add(@as(f32, 1.0)); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((len + 63) / 64), .y = @intCast(self.shape.rows) }, .block = .{ .x = 64 } }, self.rig.s, &args); + start += len; + } + try self.rig.s.synchronize(); + } + + pub fn count(self: *Attention) usize { + return self.shape.n * self.shape.rows * self.hd; + } + + pub fn load(self: *Attention, i: usize, hd: *attn.Head) !void { + const row = i / self.shape.rows; + const head = i % self.shape.rows; + const start = (row / self.shape.k) * self.shape.k; + const len = @min(self.shape.k, self.shape.n - start); + for (hd.q, self.at(0, row, head)) |*y, x| y.* = c.fromBf16(x); + for (0..len) |j| for (0..self.hd) |e| { + hd.k[j * self.hd + e] = c.fromBf16(self.at(1, start + j, head)[e]); + hd.v[j * self.hd + e] = c.fromBf16(self.at(2, start + j, head)[e]); + }; + hd.n = len; + } + + pub fn check(self: *Attention, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.shape.n * self.shape.rows, 1.0, try self.rig.outputBytes(), gate); + } + + pub fn reference(self: *Attention, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.shape.n * self.shape.rows, 1.0, want, mag); + } + + pub fn simulate(self: *Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.shape.n * self.shape.rows, 1.0, acc, order, out); + } +}; + +pub const Group = struct { + a: std.mem.Allocator, + mod: cuda.Module, + items: [2]Attention, + + pub fn create(a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !*Group { + const self = try a.create(Group); + errdefer a.destroy(self); + self.* = .{ .a = a, .mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen_vision), .items = undefined }; + errdefer self.mod.unload(); + const names = [2][]const u8{ "cuda qwen vision tf_qv_attention64", "cuda qwen vision tf_qv_attention72" }; + const symbols = [2][]const u8{ "tf_qv_attention64", "tf_qv_attention72" }; + for (&self.items, 0..) |*item, i| { + item.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try self.mod.function(symbols[i]), .name = names[i], .hd = if (i == 0) 64 else 72 }; + errdefer item.rig.deinit(); + try kernels.append(a, item.kernel()); + } + return self; + } + + pub fn destroy(self: *Group) void { + for (&self.items) |*item| item.deinit(); + self.mod.unload(); + self.a.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_sparse_attn.zig b/zig/tests/cuda/contract_sparse_attn.zig index 95c42bdef9c..43ab01eea2f 100644 --- a/zig/tests/cuda/contract_sparse_attn.zig +++ b/zig/tests/cuda/contract_sparse_attn.zig @@ -161,6 +161,7 @@ pub const Sparse = struct { .nonfinite => self.plant(), .stress => try self.stress(rng), } + if (fill == .random and self.plant_ == .none) self.identityPlant(); if (self.plant_ == .focused and fill != .stress) self.focus(); try self.told.resize(a, self.counts.items.len); @memcpy(self.told.items, self.counts.items); @@ -172,6 +173,23 @@ pub const Sparse = struct { return true; } + /// Finite A/B: list tiles rise through maxima 0, 1, 2 then tie; values retain signed zeros and subnormals. + fn identityPlant(self: *Sparse) void { + @memset(self.qAt(0, 0), 0); + self.qAt(0, 0)[0] = c.toBf16(1); + for (0..self.listed(0, 0)) |i| { + const t = i / 32; + self.kAt(self.entry(0, 0, i).?, 0)[0] = c.toBf16(@floatFromInt(@min(t, 2))); + const v = self.vAt(self.entry(0, 0, i).?, 0); + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = c.toBf16(if (t % 2 == 0) @as(f32, 1) else -2); + v[5] = c.toBf16(if (i % 2 == 0) @as(f32, 3) else -3); + } + } + /// Row 1: key head 0 lists nothing (NaN), key head 1 every slot, told cap + 5; key head 2 names -1 and `pool`. fn lists(self: *Sparse, full: usize) void { self.counts.items[hk] = 0; diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index 95749a81e20..2847d3a1302 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -552,6 +552,10 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { }; defer for (&contiguous) |*x| x.deinit(); for (&contiguous) |*x| try kernels.append(a, x.kernel()); + const qv_attn = try @import("contract_qwen_vision_attn.zig").Group.create(a, gpu, s, &kernels); + defer qv_attn.destroy(); + const hy4_attn = try @import("contract_hy4_attn.zig").Group.create(a, gpu, s, &kernels); + defer hy4_attn.destroy(); const mtp_rows = try @import("contract_qwen_mtp_rows.zig").Group.create(a, gpu, s, &kernels); defer mtp_rows.destroy(); const weight_only = try @import("contract_weight_only_suite.zig").Suite.create(a, gpu, s, &kernels); @@ -559,9 +563,9 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { const families = try @import("contract_family_sets.zig").Sets.init(gpu, s, a, &kernels, &affine4, cap); defer families.deinit(); var t: g.Tally = .{}; - try @import("contract_dump.zig").run(a, kernels.items); t0.* = check.now(gpu.io); @import("contract_after.zig").keep(&kernels, only); + try @import("contract_dump.zig").run(a, kernels.items); try g.runAll(a, kernels.items, 0x6b63, &t); return t; } diff --git a/zig/tests/cuda/contract_tree_attn.zig b/zig/tests/cuda/contract_tree_attn.zig index 39ad1e6d3a1..65850658e14 100644 --- a/zig/tests/cuda/contract_tree_attn.zig +++ b/zig/tests/cuda/contract_tree_attn.zig @@ -154,6 +154,7 @@ pub const Tree = struct { .nonfinite => self.plant(), .stress => try self.stress(rng, total), } + if (fill == .random) self.identityPlant(); self.scale = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(v.d)))); for ([_][]const u8{ std.mem.sliceAsBytes(self.q.items), std.mem.sliceAsBytes(self.kn.items), std.mem.sliceAsBytes(self.vn.items), std.mem.sliceAsBytes(self.cache.items), std.mem.sliceAsBytes(self.offs.items), std.mem.sliceAsBytes(self.row_stream.items), std.mem.sliceAsBytes(streams), std.mem.sliceAsBytes(self.paths.items), std.mem.sliceAsBytes(self.depths.items) }, &self.dev) |bytes, *p| p.* = try self.rig.input(bytes); self.pages = if (v.pages > 0) try self.paged(rng) else null; @@ -163,6 +164,36 @@ pub const Tree = struct { return true; } + /// Finite A/B: committed-group maxima rise 0, 1, 2 then tie; paths and V include signed zeros/subnormals. + fn identityPlant(self: *Tree) void { + const d = self.v.d; + const kv = self.v.hk * d; + const p0 = self.committed.items[0]; + const ko: usize = @intCast(self.offs.items[0]); + const vo: usize = @intCast(self.offs.items[1]); + @memset(self.q.items[0..d], 0); + self.q.items[0] = c.toBf16(1); + for (0..p0) |key| { + const t = key / tree.span; + const score: f32 = @floatFromInt(@min(t, 2)); + self.cache.items[ko + key * kv] = c.toBf16(score); + const v = self.cache.items[vo + key * kv ..][0..d]; + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = c.toBf16(if (t % 2 == 0) @as(f32, 1) else -2); + v[5] = c.toBf16(if (key % 2 == 0) @as(f32, 3) else -3); + } + self.kn.items[0] = c.toBf16(2); + self.vn.items[0] = 0x0001; + self.vn.items[1] = 0x8001; + self.vn.items[2] = 0; + self.vn.items[3] = 0x8000; + self.vn.items[4] = c.toBf16(1); + self.vn.items[5] = c.toBf16(-3); + } + /// The committed keys copied to shuffled `pages`-position pages (NaN in the rest): origin, offs and the table. fn paged(self: *Tree, rng: std.Random) !tree.Pages { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_vit_full.zig b/zig/tests/cuda/contract_vit_full.zig index 1d69c09c582..3f84164a272 100644 --- a/zig/tests/cuda/contract_vit_full.zig +++ b/zig/tests/cuda/contract_vit_full.zig @@ -80,7 +80,7 @@ pub fn Full(comptime D: usize, comptime name: []const u8, comptime served: []con self.qkv = try a.alloc(u16, L * self.stride()); for (self.qkv) |*e| e.* = attn.normal(rng); switch (fill) { - .random => {}, + .random => self.plantAdversarial(), .nonfinite => self.plant(), .stress => try self.stress(rng), } @@ -105,6 +105,35 @@ pub fn Full(comptime D: usize, comptime name: []const u8, comptime served: []con if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; } + /// Maxima tie across a 64-key tile then change; short shapes keep the sequence and special bf16 bits in Q/K/V. + fn plantAdversarial(self: *Self) void { + const q = self.at(0, 0, 0); + @memset(q, 0); + q[0] = c.toBf16(1); + q[1] = 0x8000; + q[2] = 0x0001; + q[3] = 0x8001; + q[4] = 0x007f; + q[5] = 0x807f; + for (0..self.shape.k) |row| @memset(self.at(row, 1, 0), 0); + const tile = @min(64, (self.shape.k - 1) / 2); + if (tile == 0) return; + const spots = [3]usize{ tile - 1, tile, @min(2 * tile, self.shape.k - 1) }; + for (spots, 0..) |row, i| { + const key = self.at(row, 1, 0); + key[0] = c.toBf16(if (i < 2) 16 else 32); + key[1] = if (i == 0) 0x8000 else 0; + key[2] = if (i == 0) 0x0001 else 0x8001; + key[3] = if (i == 0) 0x807f else 0x007f; + const value = self.at(row, 2, 0); + value[0] = c.toBf16(1 + 2 * @as(f32, @floatFromInt(i))); + value[1] = if (i == 0) 0x8000 else 0; + value[2] = if (i == 0) 0x0001 else 0x8001; + value[3] = if (i == 0) 0x8001 else 0x007f; + value[4] = if (i == 0) 0x007f else 0x807f; + } + } + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. fn stress(self: *Self, rng: std.Random) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_window.zig b/zig/tests/cuda/contract_window.zig index 765f4a40c55..970ab37294a 100644 --- a/zig/tests/cuda/contract_window.zig +++ b/zig/tests/cuda/contract_window.zig @@ -138,6 +138,7 @@ pub const Window = struct { .nonfinite => self.plant(), .stress => try self.stress(rng), } + if (fill == .random) self.identityPlant(); for ([_][]const u8{ std.mem.sliceAsBytes(self.q.items), std.mem.sliceAsBytes(self.kc.items), std.mem.sliceAsBytes(self.vc.items), std.mem.sliceAsBytes(self.pos.items), std.mem.sliceAsBytes(self.slot.items) }, &self.dev) |bytes, *p| p.* = try self.rig.input(bytes); if (f.pages > 0) try self.paged(rng, crow); self.scratch = if (f.prompt) 0 else try self.rig.scratch(wa.WindowAttention.scratchBytes(self.win(), n)); @@ -145,6 +146,31 @@ pub const Window = struct { return true; } + /// Reserved finite A/B: tile maxima rise 0, 1, 2 then tie; V has signed zeros and least bf16 subnormals. + fn identityPlant(self: *Window) void { + const f = self.f; + const r = self.shape.rows - 1; + const w = self.at(r); + const lo = self.first(w.p); + const tile: usize = if (f.prompt or f.d != 128) 64 else 32; + @memset(self.q.items[r * f.h * f.d ..][0..f.d], 0); + self.q.items[r * f.h * f.d] = c.toBf16(1); + for (lo..w.p + 1) |key| { + const t = key / tile - lo / tile; + const score: f32 = @floatFromInt(@min(t, 2)); + const cr = (self.cacheRow(w.base, key) * f.hk) * f.d; + const k = self.kc.items[cr..][0..f.d]; + const v = self.vc.items[cr..][0..f.d]; + k[0] = c.toBf16(score); + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = c.toBf16(if (t % 2 == 0) @as(f32, 1) else -2); + v[5] = c.toBf16(if (key % 2 == 0) @as(f32, 3) else -3); + } + } + /// The caches' rows in shuffled pages (keys, then values, a page), two spare pages; NaN in every unused slot. fn paged(self: *Window, rng: std.Random, crow: usize) !void { const a = self.rig.gpu.gpa; diff --git a/zig/tests/cuda/contract_window_rows.zig b/zig/tests/cuda/contract_window_rows.zig index d138cd5becf..1c92c9a92f8 100644 --- a/zig/tests/cuda/contract_window_rows.zig +++ b/zig/tests/cuda/contract_window_rows.zig @@ -285,6 +285,7 @@ pub const Rows = struct { .nonfinite => self.plant(q, kc, vc), .stress => try self.stress(rng, kc, vc), } + if (fill == .random) self.identityPlant(q, kc, vc); for ([_][]const u8{ std.mem.sliceAsBytes(q), std.mem.sliceAsBytes(kc), std.mem.sliceAsBytes(vc), std.mem.sliceAsBytes(pos), std.mem.sliceAsBytes(slot), std.mem.sliceAsBytes(hi) }, &self.dev) |bytes, *p| p.* = try self.rig.input(bytes); self.placed = null; if (f.pages > 0) try self.place(a, rng, kc, vc); @@ -295,6 +296,29 @@ pub const Rows = struct { return true; } + /// Finite A/B: decode/prompt maxima rise 0, 1, 2 then tie; values include signed zeros and subnormals. + fn identityPlant(self: *Rows, q: []u16, kc: []u16, vc: []u16) void { + const f = self.f; + const r = self.call.rows - 1; + const w = self.call.at(r); + const lo = self.call.first(w.p); + const tile: usize = if (f.prompt) 32 else 256; + @memset(q[r * f.h * f.d ..][0..f.d], 0); + q[r * f.h * f.d] = bfr.bits(1); + for (lo..w.last + 1) |key| { + const t = key / tile - lo / tile; + const score: f32 = @floatFromInt(@min(t, 2)); + self.cell(kc, r, key, 0)[0] = bfr.bits(score); + const v = self.cell(vc, r, key, 0); + v[0] = 0x0001; + v[1] = 0x8001; + v[2] = 0; + v[3] = 0x8000; + v[4] = bfr.bits(if (t % 2 == 0) @as(f32, 1) else -2); + v[5] = bfr.bits(if (key % 2 == 0) @as(f32, 3) else -3); + } + } + fn cell(self: *Rows, x: []u16, r: usize, key: usize, kh: usize) []u16 { const w = self.call.at(r); return x[(self.call.cacheRow(w.base, key) * self.f.hk + kh) * self.f.d ..][0..self.f.d]; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 54ad31567cf..4efa105a401 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -10,7 +10,7 @@ zig/kernels/cuda/experts.cuh 017728fef063d45f06240a88002f80ec931f967edc5fa44c31b zig/kernels/cuda/experts_pack.cu 578e9a607f678f0547aaeb312d18252ea0608bad7fe71bb2d5241d28adf31bac raw zig/kernels/cuda/experts_prefill.cu 5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc raw zig/kernels/cuda/experts_rows.cu 714b76ad72ff45715c5ebf6b57365f0f41789ad301871f07168a016412df13a7 raw -zig/kernels/cuda/flashnext_attn.cu 9731e39b67a8adb4a0a42222e9f888877932f2aa7108b1631ea61016083d3b71 raw +zig/kernels/cuda/flashnext_attn.cu 5ba89e3571d7008c5d5fd507e9c8bcee96b9816bf4ca355bcdcfe40ca0ac3805 raw zig/kernels/cuda/flashnext_batch.cu 95260b964fb633d23df28970672d87688f21cdd9073e44f92a1523b54b4ecd99 raw zig/kernels/cuda/flashnext_gdn.cu c7b9712626778d452e18234e2dfc3b26f8112618cdc492957c4b5f5454d64126 raw zig/kernels/cuda/flashnext_hc.cu 54fa2cfa22e483341835f6349cf0a8f508459ed1b65804728cb1358ac82b24f1 raw main 5c7cf5c117, d88c1ed57d (sum_rn and rms_scale shared; same SASS) @@ -18,7 +18,7 @@ zig/kernels/cuda/flashnext_mtp.cu a9c21f52cd00d9aa05e9cf1dae5b0168e5e48f87cb3a4a zig/kernels/cuda/fp8_experts.cu 156aa7337b41c67d200d8b58a24422cc96cfa032c9fd0711080f09ddc733baee raw zig/kernels/cuda/gdn.cu e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228 raw zig/kernels/cuda/glm_glue.cu 74e69a7c20827d498c190334fffaa896f2a4f05e107fdf9d2d34b09b55a1c75c raw #2722 (one added line, the include of glm_index_decode.cuh: the decode select's scan and merge) -zig/kernels/cuda/glm_glue_attn.cuh 2a0bc3c4966555fad4ae812e62b28558f41774fd5b2dbef6fa9b6d220ba260d8 raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) +zig/kernels/cuda/glm_glue_attn.cuh 62595b9314ebd99eac6c285fa3964ad9463ff098981f63cf05945c41bc55525d raw main 42735f94f0 (#2335: MLA bodies to common/mla.cuh; glm_glue SASS identical on five SMs); dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_bmm.cuh 6077ea47fc9f462f072a973d44ef4cab711526a3f374cfeb91f1cd65f5fad8f9 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh) zig/kernels/cuda/glm_glue_hc.cuh b0b2a43aebf5de0d52c37a1db7c2efe10e2515f61bc40ab2c58be230af461601 raw dependent launches: each kernel opens with glm_pdl::enter() (glm_pdl.cuh); #5164 (the pre side's bodies in common/mhc.cuh; every glm_glue function's SASS unchanged at five SMs) zig/kernels/cuda/common/mhc.cuh 24182f1c2292857d23963e1676f6be9ea12978266fa5edf6fe32a857eb20af21 raw #5164: glm_glue_hc.cuh's mHC pre-side bodies, which glm_glue's entries expand or call @@ -38,7 +38,7 @@ zig/kernels/cuda/lfm2.cu 4eab7c34951d9d97e41c9561845ef68a07decb09fddc9a104ba03d9 zig/kernels/cuda/logprob_rows.cuh ee5711c4cb8656b7aa887ab4aa2b73ec4e8e65fdb5dc5aca8ab21f5ef499a5d2 raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/mma4.cuh 52152491c8b53572952030e059106b186db1b9b535d55f0a7543fbe9c807a7a9 raw zig/kernels/cuda/modelopt_pack.cu 2ceb2ab450f5583c2007f216569d2196d800607144240591b87ccb0d43ff65d6 raw -zig/kernels/cuda/nemotron_attention.cu a8a6bc39c2620176aff6c5d436b4a93edf5c86c8dfb82f5568d54ca5aba2246e raw main 82f3dde92 (head-64 shared-window bodies, head-128 SASS unchanged), 94a9a48d6 (helpers to paged_attn.cuh, SASS unchanged) +zig/kernels/cuda/nemotron_attention.cu 15af7706f26d2232a3b514fdbc32e21b80a34f2d35eb2ed8947b4a0efa14e0e1 raw main 82f3dde92 (head-64 shared-window bodies, head-128 SASS unchanged), 94a9a48d6 (helpers to paged_attn.cuh, SASS unchanged) zig/kernels/cuda/nemotron_keyed.cu ed8bdd7012970d9896ec703bd7c3d5ec83e02f41dba4ce1f896fc39c1ee349c9 raw zig/kernels/cuda/nemotron_latent.cu 04fba97043d0948f82a3b9477f448dd76b21f6d11d1a445e020bd41cacb85c2b raw commits e40bd6eae, 8a8ff3d64; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/kernels/cuda/nemotron_mamba.cu dcaba12253d3931ae48c7ebd4e13dfb956f540ae19f4ab83130c3f21745be5ec raw commits fa2af585f, f0ef17e69; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate @@ -47,8 +47,8 @@ zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe zig/kernels/cuda/norms.cu 843caf5b21ffad7d190b263a833f684fab7ae1407158102d2ca1219a2c60af1c raw P2 of #4861 (inv_rms butterflies through tf_common::warp_sum; same SASS on sm_80/86/89/120/121) zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw -zig/kernels/cuda/prefill_attention.cu 9d9faedafd8e06afd667839a187118b6b220c794c2948532f0a849f901627a23 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (GLM-5.3-Flash's image tower reuses the head-64 vision_kernel instance; existing instances unchanged); #1508: pattn_kernel<128, 8, 4, 8> over paged caches for LFM3 (existing instances unchanged) -zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) +zig/kernels/cuda/prefill_attention.cu 776774090e4b189db61d48550b3bac5ade8e8379a3357e1c98aaebadd33c59e9 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (GLM-5.3-Flash's image tower reuses the head-64 vision_kernel instance; existing instances unchanged); #1508: pattn_kernel<128, 8, 4, 8> over paged caches for LFM3 (existing instances unchanged) +zig/kernels/cuda/prefill_attention_rows.cuh 294a34df6c472570a836dbfa53775e976310485009fcd0463a55ccfa6ec1411b raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fcc9b177a210 raw glm-pdl-order's slow writer, planted early reader and glm_pdl::enter() reader zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt zig/kernels/cuda/qmm.cu a55a9d00d9097c5f5bd88c8c538a0481fe13b37badd2e3faf4cdde9c86c9f93d raw @@ -58,7 +58,7 @@ zig/kernels/cuda/common/router_mma.cuh 3aca244a38f2e4b4f28bf74f333f384b1060b764c zig/kernels/cuda/qmm_group.cu 8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0 raw zig/kernels/cuda/qmm_prefill.cu e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6 raw #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel zig/kernels/cuda/qmmf.cu 7096b7eeae729f35b33b59cc40121e8f0034deb7b68a3e66fe71f2bf8f56070e raw main ec76abd45 (128-row BF16 prompt tile, bytes unchanged), c3acc3466 (K32 staging, bytes unchanged), e32de56c6 (#2721: tf_qmmf_native_fp4_check and the e2m1 pair decode behind -Dnative-fp-decode; default builds byte-identical); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fused instances at row tiles 16 and 32; off keeps main's kernels); #4515 (opt-in grouped same-input projections preserving each split-K and K-slice order; device gate unchecked); #4533 TF_QMMF_HALF_BN adds FP4/FP8/FP8G 32-column instances, default off; #3131 (grouped NVFP4 QKVG and gate/up decode launches) -zig/kernels/cuda/qwen_vision.cu eeab10300aae424fd957856e4ddba77a3543e9a86bc61701dd09687d7e3b5ea5 raw +zig/kernels/cuda/qwen_vision.cu 40f88a7117fa0787c620f725a90844430112a9d9fb62d21df75acaee2d59fae5 raw zig/kernels/cuda/rank_sum.cu 3781c3a4441cfef903c1d0712240ad4d7ab4aaf2d3fb18b323597bcec3587909 raw zig/kernels/cuda/route_rows.cu a2bf267f360cb57257aaef9765d4dca93f68523338b0881d710bbfcb01917dad raw zig/kernels/cuda/sample.cu 99a645b43a1df043ffc4be67b29d6c8165cf6d3cd992f7cf382f3334687227a0 raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #4099 (the fallback shortlist sized to top_k, same tokens); #3713 radix-search nucleus extension; GB10 CUDA parity and performance qualification pending