diff --git a/.github/workflows/no-gpu.yml b/.github/workflows/no-gpu.yml index 82f123324e4..0001f78d710 100644 --- a/.github/workflows/no-gpu.yml +++ b/.github/workflows/no-gpu.yml @@ -316,13 +316,13 @@ jobs: path: .zig-cache key: zig-build-v3-Windows-0.17.0-${{ github.sha }}${{ github.event_name == 'schedule' && '-nightly' || '' }} # The release's own path check on each platform's dist server (no fatbins), so a leak fails here, not at release. - # Pull requests check Linux x86_64 only; main's pushes and the nightly run check all three platforms. + # Pull requests check Linux x86_64 and macOS; main's pushes and the nightly run also check Linux arm64. release-paths: if: ${{ !(startsWith(github.head_ref, 'lead/train-') && github.event.pull_request.head.repo.full_name == github.repository) }} # a landing train's tip: see the note above jobs strategy: fail-fast: false matrix: - os: ${{ github.event_name != 'pull_request' && fromJSON('["macos-26", "ubuntu-24.04", "ubuntu-24.04-arm"]') || fromJSON('["ubuntu-24.04"]') }} + os: ${{ github.event_name != 'pull_request' && fromJSON('["macos-26", "ubuntu-24.04", "ubuntu-24.04-arm"]') || fromJSON('["macos-26", "ubuntu-24.04"]') }} runs-on: ${{ matrix.os }} timeout-minutes: 45 steps: @@ -354,6 +354,9 @@ jobs: - name: Metal toolchain if: runner.os == 'macOS' run: xcrun -sdk macosx metal -v || { xcodebuild -downloadComponent MetalToolchain && xcrun -sdk macosx metal -v; } + - name: Compile every runtime Metal source + if: runner.os == 'macOS' + run: zig build test-metal-compile --summary all - name: zig build check-release-paths run: zig build -Dfixed-cpu check-release-paths - name: Save the build cache diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f72c70ba94..c3c1df3483d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,20 +4,20 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Tests: `zig build test-metal-compile` now runs in pull-request macOS CI and compiles every runtime Metal source with its loader's options and defines; exact host provenance rejects unregistered exports, wrong compiler options or altered prefixes, with a planted duplicate-attribute compiler failure (refs #4593). + +- Hy4 Flash CUDA gains paged absorbed MLA and C1/C2 kernels with exact paging/indexed-list contracts and five-SM launch records (#5109). Thanks to @GrgaPalcic. + - Serve: with `--execution-witness` and `--confidential`, the witness snapshot and each reply's binding carry `"confidential": true` and the preparation hash binds the flag; witnesses without `--confidential` are unchanged (thanks @kotevcode). - `tools/bench_cache_agents.py run --trace agent_edits` replays agent conversations after a history edit: at the midpoint each conversation's first user message is rewritten and its history regrown (#5450, thanks @devopsfortunato). - MiniMax-H3-Image on Metal: edits run end to end with TensorFold's own tools: Qwen3-VL's vision tower takes opt-in DeepStack taps, and `tf-h3-image-vision` reads a reference image and writes its prompt rows and DeepStack features; Qwen 3.5 checkpoints load exactly as before (#2810). - - - Metal: the bf16 SiLU and the tanh GELU's inner term come from one shader source shared by the core, Qwen vision, Gemma 4 vision and Llama glue kernels; outputs are unchanged (#5204, thanks @jschmied). - Reports: the serving line, `/v1/load` and `/stats` now show the draft model's KV cache size, dtype and scope next to the target's, for every family with a drafter or MTP head (#4538). - - - Qwen 3.5 on CUDA: SenseNova-Loop-9B (`sensenova_loop`) serves in BF16, text only, on the looped schedule (physical layers 0-3, 4-27 twice, 28-31) with its mHC stream routing, one copy of the weights and a cache slot per execution; drafts, vision, pipeline stages and tensor parallel are refused for it, and other Qwen checkpoints run as before (#3723, refs #3717). Thanks to @Maxrio9. - Docs: `docs/environment-names.md` lists `TF_CUDA_QWEN_PROMPT_STAGES2` and `TF_Q27_METAL4`, so the environment-names check passes on main again (#5575). @@ -25,20 +25,14 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini: `--thinking-budget` and `thinking.budget_tokens` now close thinking at the budget and the model goes on to answer; with no budget, replies are unchanged (#5402). Thanks @fcossutta. Thanks @fcossutta for the report. - - - Tests: the CUDA execution-witness test rewrites its cubin with a different size, so it no longer depends on two writes landing in different timestamp ticks (#5522). - Server: under `--confidential`, errors and log lines carry fixed messages, allowed codes and a request id, never request text (#5348, part of #5176). Thanks to @kotevcode. - - - Flash Next CUDA: the rows store sizes its staging permit from the served window instead of a fixed 1 GiB, so kept states past about 31K tokens are no longer skipped with `StagingFull` (thanks @shantanugoel). - Inkling 2 on CUDA: an EXL3 launch that runs a layer's five input projections (q, gate, r, k and v) as one rotation and one linear launch, each member computed exactly as by its own launch, passes gates 1 to 4 of the kernel contract with planted controls; nothing serves it yet (#4874, refs #3476). - - - Qwen3.8-27B-class Metal: the startup memory margin is an eighth of the Metal working set (1-8 GiB) instead of a fixed 8 GiB, and a prompt frame that cannot fit 512 rows steps down to 128, so 16 GB and 24 GB Macs can serve the 4-bit 9B; Macs with a working set of 64 GiB or more keep the 8 GiB margin (#4158, thanks @jayleaton). - App: models downloaded through the app stay in the list on engine 1.3.0 and later (the parser reads `startup budget:`), and drafter-only checkpoints are hidden from the model picker (#4407; thanks @devopsfortunato). @@ -47,14 +41,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next on CUDA: TFQ3 host-dequantized BF16 slices are freed with the two-byte alignment they were allocated with (#5467, fixes #5459, thanks @devopsfortunato). - - - GLM CUDA: `--prompt-cache-disk` (and `--learn-conversations`) now keeps full GLM-5.3 conversation states on disk; the image reads the latent row width, pool size and which caches keep index keys from the state, so GLM-5.3-Flash images are unchanged (thanks @bjornmonnens). - App: the room's Final readiness panel now shows the moderator's final-gate verdict, so it can no longer show all green while the room has not reached FINAL (thanks @devopsfortunato). - - - CLI: a failed first reply from `tensorfold start` reports the server's refusal text reliably on a loaded machine, with a 30-second bound so unattended runs never hang (#5379). - Multi-GPU groups: every rank connection (the `fabric/tp` bootstrap, GLM's and Nemotron's liveness lines, the HIP link and the Flash Next pair) proves a shared key with a fresh nonce and an HMAC before its first byte, and a connection that fails is closed without stopping the group; ranks on more than one host need the key from `TF_RANK_SECRET_FILE` or `--rank-secret` (#3041). @@ -242,6 +232,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 on CUDA: DSpark kernels draft every open stream in one pass; drafted output stays byte-identical to plain decoding (#4858). Thanks to @ajensenwaud. +- Tests: `zig build test-metal-compile` now runs in pull-request macOS CI and compiles every runtime Metal source with its loader's options and defines; exact host provenance rejects unregistered exports, wrong compiler options or altered prefixes, with a planted duplicate-attribute compiler failure (refs #4593). - Tests: the `--listen-fd` check counts a connection the server closes before the request is sent as refused, so that race no longer fails the suite (#5273, refs #5183). - Flash Next on CUDA: greedy drafts beside another open stream use `TF_FLASHNEXT_CONFIDENCE`, the same stop rule as a lone stream; token verification is unchanged (#5265). diff --git a/build.zig b/build.zig index 75277627313..6ad5b256f86 100644 --- a/build.zig +++ b/build.zig @@ -123,6 +123,19 @@ pub fn build(b: *std.Build) void { step5_mods.sources.addImport("nemotron_packed_metallib", embedded(b, empty, "nemotron_packed.metallib")); @import("zig/build/step5_host.zig").steps(b, step5_mods.metal, step5_mods.engine, step5_mods.lanes); @import("zig/build/qwen35_cache_host.zig").compileHost(b, step5_mods.metal, step5_mods.engine, step5_mods.lanes); + } else if (target.result.os.tag == .macos) { + const cross_mods = metalEngineModules(b, target, .Debug, draft_ids); + // Object-only checks need no Apple SDK link inputs. + cross_mods.metal.frameworks.clearRetainingCapacity(); + cross_mods.metal.link_objects.clearRetainingCapacity(); + const empty = b.addWriteFiles().add("runtime-cross-no-shaders.metallib", ""); + cross_mods.sources.addImport("nemotron_packed_metallib", embedded(b, empty, "nemotron_packed.metallib")); + @import("zig/build/metal_prompt_sources.zig").steps(b, cross_mods.metal, cross_mods.engine, test_step); + } else { + const runtime_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); + const empty = b.addWriteFiles().add("runtime-coverage-no-shaders.metallib", ""); + runtime_mods.sources.addImport("nemotron_packed_metallib", embedded(b, empty, "nemotron_packed.metallib")); + @import("zig/build/metal_prompt_sources.zig").hostSteps(b, runtime_mods.metal, runtime_mods.engine, test_step); } @import("zig/build/h3_host.zig").tests(b, target, test_step); @import("zig/build/h3_image_prompt.zig").tests(b, target, test_step); diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 466a828df75..c57f7a1e96c 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -140,6 +140,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("hy4_engram_fp8", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/engram_fp8_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("ernie5_5_index_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_index.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("ernie5_5_mhc_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_mhc.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); + runner.addImport("hy4_mla_paged_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/mla_paged_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} })); runner.addImport("gemma4_cuda", @import("gemma4_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); runner.addImport("spark25", @import("spark25.zig").module(b, target, optimize, cuda, mods.core, mods.lanes)); // the served family and its engine, for the dots runner diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 595562fa43b..d6db8777f89 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -173,6 +173,9 @@ pub const kernels = [_]Kernel{ .{ .name = "hy4_dfly2_glue", .src = "hy4_flash/dfly2_glue", .flags = glue }, .{ .name = "ernie5_5_index", .src = "ernie5_5/index", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's DSA key lists .{ .name = "ernie5_5_mhc", .src = "ernie5_5/mhc", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's mHC pre side + .{ .name = "hy4_mla_paged", .src = "hy4_flash/mla_paged", .flags = glue }, + .{ .name = "hy4_mla_attn_paged", .src = "hy4_flash/mla_attn_paged", .flags = glue }, + .{ .name = "hy4_mla_c2", .src = "hy4_flash/mla_c2", .flags = glue }, .{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE) .{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention .{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention diff --git a/zig/build/metal_prompt_sources.zig b/zig/build/metal_prompt_sources.zig index 2f0ef40d81b..97913ed91b5 100644 --- a/zig/build/metal_prompt_sources.zig +++ b/zig/build/metal_prompt_sources.zig @@ -1,11 +1,42 @@ //! Runtime source assembly is device-free; the compiler gate requires a device and submits no work. const std = @import("std"); -pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, host_tests: *std.Build.Step) void { +fn inventoryModule(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module) *std.Build.Module { + const target = metal.resolved_target orelse b.graph.host; + const assembly = b.createModule(.{ .root_source_file = b.path("zig/runtime_sources/assembly_metal.zig"), .imports = &.{.{ .name = "real_metal", .module = metal }} }); + const inventory = b.createModule(.{ .root_source_file = b.path("zig/metal_runtime_inventory.zig"), .target = target, .optimize = .debug, .link_libc = true }); + var imports = engine.import_table.iterator(); + while (imports.next()) |entry| inventory.addImport(entry.key_ptr.*, entry.value_ptr.*); + inventory.addImport("metal", assembly); + inventory.addImport("core", inventory); + inline for (.{ "bf16_topk_gpu", "tree_round_gpu", "tree_commit_gpu", "draft_ops" }, .{ "bf16_topk_sources", "tree_round_sources", "tree_commit_sources", "draft_ops_sources" }) |owner, name| { + inventory.addImport(name, engine.import_table.get(owner).?.import_table.get(name).?); + } + inventory.addImport("h3_kernels", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") })); + return inventory; +} + +fn coverageSteps(b: *std.Build, inventory: *std.Build.Module, host_tests: *std.Build.Step) *std.Build.Step.Run { + const run = b.addRunArtifact(b.addTest(.{ .root_module = inventory, .filters = &.{"Metal runtime source"} })); + host_tests.dependOn(&run.step); + b.step("test-metal-source-registry-host", "Every exported Metal source is assembled or explicitly excluded").dependOn(&run.step); + return run; +} + +fn modeSteps(b: *std.Build, inventory: *std.Build.Module, host_tests: *std.Build.Step) *std.Build.Step.Run { + const run = b.addRunArtifact(b.addTest(.{ .root_module = inventory, .filters = &.{"Metal runtime source modes:"} })); + host_tests.dependOn(&run.step); + b.step("test-metal-runtime-source-modes-host", "Runtime libraries match their loaders' device capability gates").dependOn(&run.step); + return run; +} + +const Loader = struct { host: *std.Build.Step.Compile, run: *std.Build.Step.Run }; +fn loaderSteps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, host_tests: *std.Build.Step) Loader { + const target = metal.resolved_target orelse b.graph.host; const recording = b.createModule(.{ .root_source_file = b.path("zig/lfm2_recording_metal.zig"), .imports = &.{.{ .name = "real_metal", .module = metal }} }); const loader_host = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/lfm2_runtime_sources_host.zig"), - .target = b.graph.host, + .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ @@ -16,24 +47,25 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, const loader_run = b.addRunArtifact(loader_host); host_tests.dependOn(&loader_run.step); b.step("test-lfm2-runtime-sources-host", "LFM2 source inventory equals its recording loader without a device").dependOn(&loader_run.step); - const assembly = b.createModule(.{ .root_source_file = b.path("zig/runtime_sources/assembly_metal.zig"), .imports = &.{.{ .name = "real_metal", .module = metal }} }); - const inventory = b.createModule(.{ .root_source_file = b.path("zig/metal_runtime_inventory.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); - var imports = engine.import_table.iterator(); - while (imports.next()) |entry| inventory.addImport(entry.key_ptr.*, entry.value_ptr.*); - inventory.addImport("metal", assembly); - inventory.addImport("core", inventory); - inline for (.{ "bf16_topk_gpu", "tree_round_gpu", "tree_commit_gpu", "draft_ops" }, .{ "bf16_topk_sources", "tree_round_sources", "tree_commit_sources", "draft_ops_sources" }) |owner, name| { - inventory.addImport(name, engine.import_table.get(owner).?.import_table.get(name).?); - } - inventory.addImport("h3_kernels", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") })); - const mode_run = b.addRunArtifact(b.addTest(.{ .root_module = inventory, .filters = &.{"Metal runtime source modes:"} })); - host_tests.dependOn(&mode_run.step); - b.step("test-metal-runtime-source-modes-host", "Runtime libraries match their loaders' device capability gates").dependOn(&mode_run.step); + return .{ .host = loader_host, .run = loader_run }; +} + +pub fn hostSteps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, host_tests: *std.Build.Step) void { + _ = loaderSteps(b, metal, engine, host_tests); + const inventory = inventoryModule(b, metal, engine); + _ = modeSteps(b, inventory, host_tests); + _ = coverageSteps(b, inventory, host_tests); +} +pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, host_tests: *std.Build.Step) void { + const loader = loaderSteps(b, metal, engine, host_tests); + const target = metal.resolved_target orelse b.graph.host; + const inventory = inventoryModule(b, metal, engine); + const mode_run = modeSteps(b, inventory, host_tests); + const coverage_run = coverageSteps(b, inventory, host_tests); const root = b.createModule(.{ .root_source_file = b.path("zig/metal_runtime_sources_test.zig"), - .target = b.graph.host, + .target = target, .optimize = .debug, - .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "inventory", .module = inventory } }, }); const options = b.addOptions(); @@ -43,14 +75,22 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, const run = b.addRunArtifact(tests); run.has_side_effects = true; const step = b.step("test-metal-runtime-sources", "Compile every family's runtime source libraries; device required, no dispatch"); - step.dependOn(&loader_run.step); + step.dependOn(&loader.run.step); step.dependOn(&mode_run.step); + step.dependOn(&coverage_run.step); step.dependOn(&run.step); + b.step("test-metal-compile", "Compile every runtime Metal source with a planted compiler-error control").dependOn(step); b.step("test-nemotron-prefill-metal-sources", "Alias for the complete runtime Metal source compiler gate").dependOn(step); - b.step("build-metal-runtime-sources", "Build the source gate executable without opening a device").dependOn(&tests.step); + const loader_object = b.addTest(.{ .root_module = loader.host.root_module, .filters = &.{"LFM2 runtime inventory:"}, .emit_object = true }); + const sources_object = b.addTest(.{ .root_module = root, .filters = &.{"Metal runtime source compile gate:"}, .emit_object = true }); + _ = loader_object.getEmittedBin(); + _ = sources_object.getEmittedBin(); + const compile_step = b.step("build-metal-runtime-sources", "Compile both runtime Metal source test objects without linking or execution"); + compile_step.dependOn(&loader_object.step); + compile_step.dependOn(&sources_object.step); const emit_root = b.createModule(.{ .root_source_file = b.path("zig/metal_runtime_sources_emit.zig"), - .target = b.graph.host, + .target = target, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "inventory", .module = inventory }}, diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index 6594dc56abf..7e2bb2ddd00 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -19,3 +19,4 @@ #include "contract_int4_controls.cuh" #include "contract_hy4_engram_fp8_controls.cuh" #include "contract_mhc_controls.cuh" +#include "contract_hy4_mla_paged_controls.cuh" diff --git a/zig/kernels/cuda/contract_hy4_mla_paged_controls.cuh b/zig/kernels/cuda/contract_hy4_mla_paged_controls.cuh new file mode 100644 index 00000000000..eda207d2009 --- /dev/null +++ b/zig/kernels/cuda/contract_hy4_mla_paged_controls.cuh @@ -0,0 +1,50 @@ +// Planted controls for hy4_mla.cu: each kernel instantiated with each tf_hy4::Fault, red at its corresponding gate. +#pragma once + +#include "hy4_flash/mla_paged.cuh" + +#define TF_HY4_CTL_ABSORB(tag, fault) \ + extern "C" __global__ void __launch_bounds__(128) tf_ctl_hy4_mla_absorb_##tag( \ + const __nv_bfloat16* q, int64_t qs, const __nv_bfloat16* kvb, float* ql, int rows, int heads) { \ + tf_hy4::absorb(q, qs, kvb, ql, rows, heads); \ + } + +#define TF_HY4_CTL_ATTN(tag, fault) \ + extern "C" __global__ void __launch_bounds__(256) tf_ctl_hy4_mla_attn_##tag( \ + const float* ql, const __nv_bfloat16* qr, const __nv_bfloat16* cache, const int* pos, const int* idx, \ + const float* sinks, float* ol, int heads, int window, int nidx, int ring, float scale) { \ + tf_hy4::attn(ql, qr, cache, pos, idx, sinks, ol, heads, window, nidx, ring, scale); \ + } + +#define TF_HY4_CTL_ATTN_ROWS(tag, fault) \ + extern "C" __global__ void __launch_bounds__(256) tf_ctl_hy4_mla_attn_rows_##tag( \ + const float* ql, const __nv_bfloat16* qr, const unsigned long long* caches, const int* pos, const int* idx, \ + const float* sinks, float* ol, int heads, int window, int nidx, int ring, float scale) { \ + tf_hy4::attn_rows(ql, qr, caches, pos, idx, sinks, ol, heads, window, nidx, ring, scale); \ + } + +#define TF_HY4_CTL_VALUE(tag, fault) \ + extern "C" __global__ void __launch_bounds__(128) tf_ctl_hy4_mla_value_##tag( \ + const float* ol, const __nv_bfloat16* kvb, const __nv_bfloat16* gate, int64_t gs, __nv_bfloat16* out, \ + int64_t os, int rows, int heads) { \ + tf_hy4::value(ol, kvb, gate, gs, out, os, rows, heads); \ + } + +#define TF_HY4_CTL_POST(tag, fault) \ + extern "C" __global__ void __launch_bounds__(256) tf_ctl_hy4_mla_post_##tag( \ + const float* parts, int64_t plane, int world, const __nv_bfloat16* w, __nv_bfloat16* out, int width, \ + float eps) { \ + tf_hy4::post(parts, plane, world, w, out, width, eps); \ + } + +#define TF_HY4_CTL_ALL(K) \ + K(bad_nan, tf_hy4::kBadNan) \ + K(bad_repeat, tf_hy4::kBadRepeat) \ + K(bad_tail, tf_hy4::kBadTail) \ + K(bad_sums, tf_hy4::kBadSums) + +TF_HY4_CTL_ALL(TF_HY4_CTL_ABSORB) +TF_HY4_CTL_ALL(TF_HY4_CTL_ATTN) +TF_HY4_CTL_ALL(TF_HY4_CTL_ATTN_ROWS) +TF_HY4_CTL_ALL(TF_HY4_CTL_VALUE) +TF_HY4_CTL_ALL(TF_HY4_CTL_POST) diff --git a/zig/kernels/cuda/hy4_flash/mla_attn_core.cuh b/zig/kernels/cuda/hy4_flash/mla_attn_core.cuh new file mode 100644 index 00000000000..6da8c18607c --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_attn_core.cuh @@ -0,0 +1,525 @@ +// Templated tensor-core tile body (`attn_body`) for `hy4_mla_attn.cu`. +#pragma once + +namespace hy4_mla { +namespace detail { + +// `ROWS == false`: heads-in-M (`16 * MT` heads); `ROWS == true`: rows-in-M (`16` rows, `MT` heads). +template +__device__ __forceinline__ void attn_body(const Args& a) { + using C = Lay; + constexpr int NQ = C::NQ; + extern __shared__ __align__(128) unsigned char sm[]; + bf16* qs = reinterpret_cast(sm + C::Q); + bf16* kvs = reinterpret_cast(sm + C::KV); + bf16* ps = reinterpret_cast(sm + C::P); + bf16* pls = reinterpret_cast(sm + C::PLO); + bf16* qls = reinterpret_cast(sm + C::QLO); + float* red = reinterpret_cast(sm + C::RED); + int* kpos = reinterpret_cast(sm + C::KP); + float* rowv = reinterpret_cast(sm + C::ROW); + int* rinfo = reinterpret_cast(sm + C::RINFO); + int* misc = reinterpret_cast(sm + C::MISC); + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, q4 = lane & 3; + const int kind = a.kind; + qmm_frag::grid_wait(); + if constexpr (!ROWS) qmm_frag::grid_launch(); + TSTAMP(0); + + int r = 0, hb = 0, j = 0, nspl = 1, h0 = 0, prow = 0; + int k0 = 0, k1 = 0; + bool lst = false; + size_t sbase = 0; + const bf16* row_cache = a.CACHE; + unsigned live = 0; + if constexpr (!ROWS) { + j = blockIdx.x; + hb = blockIdx.y; + r = blockIdx.z; + const int s_ = a.ROW_STREAM[r]; + prow = a.ROW_POS[r]; + lst = kind == 1 && prow >= DSA_KEYS; + const int n = kind == 0 ? min(prow + 1, SWA_KEYS) : (kind == 1 ? (lst ? DSA_KEYS : prow + 1) : a.ntok); + nspl = (n + a.ch - 1) / a.ch; + if (j >= nspl) return; + k0 = j * a.ch; + k1 = min(n, k0 + a.ch); + if (a.PAGE_TABLE) { + sbase = static_cast(s_) * a.pt_stride; + } else if (a.ROW_CACHE) { + row_cache = reinterpret_cast(a.ROW_CACHE[r]); + sbase = 0; + } else { + sbase = kind == 0 ? static_cast(s_) * a.ring : static_cast(s_) * a.ctx; + } + h0 = hb * NQ; + } else { + hb = blockIdx.x; + r = blockIdx.y * 16; + h0 = hb * MT; + if (tid < 16) { + const int rr = r + tid; + int pp = 0, st = -1; + if (rr < a.R) { + pp = a.ROW_POS[rr]; + st = a.ROW_STREAM[rr]; + if (kind == 1 && pp >= DSA_KEYS) st = -1; + } + rinfo[tid] = pp; + rinfo[16 + tid] = st; + } + __syncthreads(); +#pragma unroll + for (int i = 0; i < 16; ++i) live |= (rinfo[16 + i] >= 0 ? 1u : 0u) << i; + if (live == 0) return; + } + + // QREG keeps each warp's `(m tile, k slice)` A fragments in registers across all key tiles. + uint32_t qf[QREG ? C::KSTEPS : 1][4]; + uint32_t qfl[(QREG && EXACT) ? C::KSTEPS : 1][4]; + if constexpr (QREG) { + const int ntile = warp % C::NTILE, kp = warp / C::NTILE, mt = ntile / (KT / 8); + const bf16* q0; + const bf16* q8; + bool ok0 = true, ok8 = true; + if constexpr (!ROWS) { + const int ha = h0 + mt * 16 + g; + const int hb_ = ha + 8; + ok0 = ha < a.Hl; + ok8 = hb_ < a.Hl; + q0 = a.QA + (static_cast(r) * a.Hl + (ok0 ? ha : 0)) * KW; + q8 = a.QA + (static_cast(r) * a.Hl + (ok8 ? hb_ : 0)) * KW; + } else { + const bool hm_ok = (h0 + mt) < a.Hl; + const int hm = h0 + (hm_ok ? mt : 0); + ok0 = ((live >> g) & 1) && hm_ok; + ok8 = ((live >> (g + 8)) & 1) && hm_ok; + q0 = a.QA + (static_cast(ok0 ? r + g : 0) * a.Hl + hm) * KW; + q8 = a.QA + (static_cast(ok8 ? r + g + 8 : 0) * a.Hl + hm) * KW; + } +#pragma unroll + for (int s = 0; s < C::KSTEPS; ++s) { + const int kb = (kp * C::KSTEPS + s) * 16 + 2 * q4; + qf[s][0] = ok0 ? __ldg(reinterpret_cast(q0 + kb)) : 0u; + qf[s][1] = ok8 ? __ldg(reinterpret_cast(q8 + kb)) : 0u; + qf[s][2] = ok0 ? __ldg(reinterpret_cast(q0 + kb + 8)) : 0u; + qf[s][3] = ok8 ? __ldg(reinterpret_cast(q8 + kb + 8)) : 0u; + if constexpr (EXACT) { + qfl[s][0] = ok0 ? __ldg(reinterpret_cast(q0 + a.QLO + kb)) : 0u; + qfl[s][1] = ok8 ? __ldg(reinterpret_cast(q8 + a.QLO + kb)) : 0u; + qfl[s][2] = ok0 ? __ldg(reinterpret_cast(q0 + a.QLO + kb + 8)) : 0u; + qfl[s][3] = ok8 ? __ldg(reinterpret_cast(q8 + a.QLO + kb + 8)) : 0u; + } + } + } else { + for (int idx = tid; idx < NQ * (KW / 8); idx += NT) { + const int row = idx / (KW / 8), u = idx - row * (KW / 8); + const bf16* src; + bool ok = true; + if constexpr (!ROWS) { + ok = (h0 + row) < a.Hl; + src = a.QA + (static_cast(r) * a.Hl + (ok ? h0 + row : 0)) * KW; + } else { + const int r16 = row & 15, mt = row >> 4; + const bool hm_ok = (h0 + mt) < a.Hl; + ok = ((live >> r16) & 1) && hm_ok; + src = a.QA + (static_cast(ok ? r + r16 : 0) * a.Hl + h0 + (hm_ok ? mt : 0)) * KW; + } + tf_common::cp16z(qs + wide(row, u), src + u * 8, ok); + if constexpr (EXACT) tf_common::cp16z(qls + wide(row, u), src + a.QLO + u * 8, ok); + } + tf_common::cp_commit(); + } + + const int srow = tid / C::TPR, ssub = tid % C::TPR; + float m_run = -INFINITY, l_run = 0.f; + float acc[MT][8][4]; +#pragma unroll + for (int mt = 0; mt < MT; ++mt) +#pragma unroll + for (int jj = 0; jj < 8; ++jj) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[mt][jj][e] = 0.f; + int my_p = 0; + if constexpr (ROWS) my_p = rinfo[srow & 15]; + + auto run_pass = [&](int first, int nkeys, int sig, unsigned pass, int vis_lo, int vis_hi) { + const int ntiles = (nkeys + KT - 1) / KT; + auto load_tile = [&](int t) { + constexpr int TPK = NT / KT; + bf16* dst = kvs + (t & 1) * KT * KW; + const int kk = tid / TPK, part = tid % TPK; + const int i = first + t * KT + kk; + bool ok = i < first + nkeys; + int pos = -1; + size_t slot = 0; + if constexpr (!ROWS) { + if (ok) { + if (kind == 0) { + pos = prow - min(prow + 1, SWA_KEYS) + 1 + i; + } else if (kind == 1) { + if (!lst) { + pos = i; + } else { + const int gi = __ldg(a.LIST + static_cast(r) * LISTW + (i >> 2)); + pos = gi < 0 ? -1 : 4 * gi + (i & 3); + } + } else { + pos = __ldg(a.TOK + static_cast(r) * a.ldtok + i); + } + ok = pos >= 0 && pos <= prow; + } + if (ok) { + if (a.PAGE_TABLE && kind != 0) { + const unsigned up = static_cast(pos); + slot = static_cast(__ldg(a.PAGE_TABLE + sbase + (up >> 8))) * 256u + (up & 255u); + } else { + slot = sbase + (kind == 0 ? static_cast(pos % a.ring) : static_cast(pos)); + } + } + } else { + pos = i; + ok = ok && pos >= 0; + if (ok) + slot = kind == 0 ? static_cast(sig) * a.ring + pos % a.ring + : static_cast(sig) * a.ctx + pos; + } + const bf16* src = (ROWS ? a.CACHE : row_cache) + slot * KW; +#pragma unroll + for (int u = part; u < KW / 8; u += TPK) tf_common::cp16z(dst + wide(kk, u), src + u * 8, ok); + if (part == 0) kpos[(t & 1) * KT + kk] = ok ? pos : -1; + }; + load_tile(0); + tf_common::cp_commit(); + if (ntiles > 1) load_tile(1); + tf_common::cp_commit(); + + const bool my_in = ROWS ? ((pass >> (srow & 15)) & 1) != 0 : true; + auto sees = [&](int pr, bool in, int kp) -> bool { + if constexpr (!ROWS) return kp >= 0; + else return in && kp >= 0 && kp <= pr && (kind != 0 || kp > pr - SWA_KEYS); + }; + + for (int t = 0; t < ntiles; ++t) { + tf_common::cp_wait<1>(); + __syncthreads(); + if (t == 0) TSTAMP(1); + const bf16* kv = kvs + (t & 1) * KT * KW; + const int* kp_t = kpos + (t & 1) * KT; + + bool poisoned = false; + if constexpr (ROWS) { + const int tlo = first + t * KT, thi = min(first + nkeys, tlo + KT) - 1; + const bool need = !(pass == live && tlo >= vis_lo && thi <= vis_hi); + if (need) { + int bad = 0; + for (int idx = tid; idx < KT * (KL / 8); idx += NT) { + const int kk = idx / (KL / 8), u = idx % (KL / 8); + const int kp = kp_t[kk]; + if (kp >= 0 && (pass != live || kp < vis_lo || kp > vis_hi)) + bad |= nonfinite8(*reinterpret_cast(kv + wide(kk, u))) ? 1 : 0; + } + poisoned = __syncthreads_or(bad) != 0; + } + } + + { + const int ntile = warp % C::NTILE, kp = warp / C::NTILE; + const int mt = ntile / (KT / 8), nt = ntile % (KT / 8); + float c0[4] = {0.f, 0.f, 0.f, 0.f}, c1[4] = {0.f, 0.f, 0.f, 0.f}; + const int ks0 = kp * C::KSTEPS; +#pragma unroll + for (int s = 0; s < C::KSTEPS; s += 2) { + const int ks = ks0 + s; + if (s + 1 < C::KSTEPS) { + uint32_t b[4], a0[4], a1[4]; + ldsm4(b, saddr(kv + wide(nt * 8 + (lane & 7), ks * 2 + (lane >> 3)))); + if constexpr (QREG) { +#pragma unroll + for (int e = 0; e < 4; ++e) a0[e] = qf[s][e], a1[e] = qf[s + 1][e]; + } else { + ldsm4(a0, saddr(qs + wide(mt * 16 + (lane & 15), ks * 2 + (lane >> 4)))); + ldsm4(a1, saddr(qs + wide(mt * 16 + (lane & 15), ks * 2 + 2 + (lane >> 4)))); + } + mma(c0, a0, b[0], b[1]); + mma(c1, a1, b[2], b[3]); + if constexpr (EXACT) { + if constexpr (QREG) { + mma(c0, qfl[s], b[0], b[1]); + mma(c1, qfl[s + 1], b[2], b[3]); + } else { + ldsm4(a0, saddr(qls + wide(mt * 16 + (lane & 15), ks * 2 + (lane >> 4)))); + ldsm4(a1, saddr(qls + wide(mt * 16 + (lane & 15), ks * 2 + 2 + (lane >> 4)))); + mma(c0, a0, b[0], b[1]); + mma(c1, a1, b[2], b[3]); + } + } + } else { + uint32_t b[2], a0[4]; + ldsm2(b, saddr(kv + wide(nt * 8 + (lane & 7), ks * 2 + ((lane >> 3) & 1)))); + if constexpr (QREG) { +#pragma unroll + for (int e = 0; e < 4; ++e) a0[e] = qf[s][e]; + } else { + ldsm4(a0, saddr(qs + wide(mt * 16 + (lane & 15), ks * 2 + (lane >> 4)))); + } + mma(c0, a0, b[0], b[1]); + if constexpr (EXACT) { + if constexpr (QREG) { + mma(c0, qfl[s], b[0], b[1]); + } else { + ldsm4(a0, saddr(qls + wide(mt * 16 + (lane & 15), ks * 2 + (lane >> 4)))); + mma(c0, a0, b[0], b[1]); + } + } + } + } + float* rd = red + (kp * NQ + mt * 16) * C::SPAD + nt * 8 + 2 * q4; + *reinterpret_cast(rd + g * C::SPAD) = make_float2(__fadd_rn(c0[0], c1[0]), __fadd_rn(c0[1], c1[1])); + *reinterpret_cast(rd + (g + 8) * C::SPAD) = + make_float2(__fadd_rn(c0[2], c1[2]), __fadd_rn(c0[3], c1[3])); + } + __syncthreads(); + + { + float sc[C::CPT]; + bool vis[C::CPT]; +#pragma unroll + for (int e = 0; e < C::CPT; ++e) { + const int c = ssub * C::CPT + e; + float v = red[srow * C::SPAD + c]; +#pragma unroll + for (int ks = 1; ks < C::KSPLIT; ++ks) v = __fadd_rn(v, red[(ks * NQ + srow) * C::SPAD + c]); + vis[e] = sees(my_p, my_in, kp_t[c]); + sc[e] = vis[e] ? __fmul_rn(v, SCALE) : -INFINITY; + } + float tm = sc[0]; +#pragma unroll + for (int e = 1; e < C::CPT; ++e) tm = nmax(tm, sc[e]); +#pragma unroll + for (int o = C::TPR / 2; o > 0; o >>= 1) tm = nmax(tm, __shfl_xor_sync(FULL, tm, o)); + const bool act = tm != -INFINITY; + const float mn = act ? nmax(m_run, tm) : m_run; + const float al = act ? (m_run == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(m_run, mn))) : 1.f; + float ls = 0.f; + bf16 pb[C::CPT], plb[C::CPT]; +#pragma unroll + for (int e = 0; e < C::CPT; ++e) { + const float pv = (act && vis[e]) ? tf_glue::tf_exp(__fsub_rn(sc[e], mn)) : 0.f; + pb[e] = __float2bfloat16_rn(pv); + plb[e] = __float2bfloat16_rn(__fsub_rn(pv, __bfloat162float(pb[e]))); + ls = __fadd_rn(ls, EXACT ? pv : __bfloat162float(pb[e])); + } +#pragma unroll + for (int o = C::TPR / 2; o > 0; o >>= 1) ls = __fadd_rn(ls, __shfl_xor_sync(FULL, ls, o)); + l_run = __fmaf_rn(l_run, al, ls); + m_run = mn; + const int c0 = ssub * C::CPT; + if constexpr (C::CPT == 1) { + ps[narrow(srow, c0 >> 3) + (c0 & 7)] = pb[0]; + if constexpr (EXACT) pls[narrow(srow, c0 >> 3) + (c0 & 7)] = plb[0]; + } else { +#pragma unroll + for (int e = 0; e < C::CPT; e += 2) { + const int c = c0 + e; + __nv_bfloat162 two; + two.x = pb[e]; + two.y = pb[e + 1]; + *reinterpret_cast<__nv_bfloat162*>(ps + narrow(srow, c >> 3) + (c & 7)) = two; + if constexpr (EXACT) { + two.x = plb[e]; + two.y = plb[e + 1]; + *reinterpret_cast<__nv_bfloat162*>(pls + narrow(srow, c >> 3) + (c & 7)) = two; + } + } + } + if (ssub == 0) rowv[srow] = al; + } + __syncthreads(); + + { +#pragma unroll + for (int mt = 0; mt < MT; ++mt) { + const float a0 = rowv[mt * 16 + g], a1 = rowv[mt * 16 + g + 8]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + acc[mt][jj][0] = __fmul_rn(acc[mt][jj][0], a0); + acc[mt][jj][1] = __fmul_rn(acc[mt][jj][1], a0); + acc[mt][jj][2] = __fmul_rn(acc[mt][jj][2], a1); + acc[mt][jj][3] = __fmul_rn(acc[mt][jj][3], a1); + } + } + if (!poisoned) { +#pragma unroll + for (int k16 = 0; k16 < KT / 16; ++k16) { + uint32_t pa[MT][4]; +#pragma unroll + for (int mt = 0; mt < MT; ++mt) + ldsm4(pa[mt], saddr(ps + narrow(mt * 16 + (lane & 15), k16 * 2 + (lane >> 4)))); +#pragma unroll + for (int jj = 0; jj < 8; jj += 2) { + uint32_t b[4]; + ldsm4t(b, saddr(kv + wide(k16 * 16 + (lane & 15), warp * 8 + jj + (lane >> 4)))); +#pragma unroll + for (int mt = 0; mt < MT; ++mt) { + mma(acc[mt][jj], pa[mt], b[0], b[1]); + mma(acc[mt][jj + 1], pa[mt], b[2], b[3]); + } + if constexpr (EXACT) { +#pragma unroll + for (int mt = 0; mt < MT; ++mt) { + uint32_t pl[4]; + ldsm4(pl, saddr(pls + narrow(mt * 16 + (lane & 15), k16 * 2 + (lane >> 4)))); + mma(acc[mt][jj], pl, b[0], b[1]); + mma(acc[mt][jj + 1], pl, b[2], b[3]); + } + } + } + } + } else if constexpr (ROWS) { +#pragma unroll + for (int mt = 0; mt < MT; ++mt) +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int row = mt * 16 + g + 8 * (e >> 1), r16 = row & 15; + const int pr = rinfo[r16]; + const bool in = (pass >> r16) & 1; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int col = warp * 64 + jj * 8 + 2 * q4 + (e & 1); + float x = acc[mt][jj][e]; +#pragma unroll 1 + for (int kk = 0; kk < KT; ++kk) { + if (!sees(pr, in, kp_t[kk])) continue; + float pv = __bfloat162float(ps[narrow(row, kk >> 3) + (kk & 7)]); + if constexpr (EXACT) pv = __fadd_rn(pv, __bfloat162float(pls[narrow(row, kk >> 3) + (kk & 7)])); + const float vv = __bfloat162float(kv[wide(kk, col >> 3) + (col & 7)]); + x = __fmaf_rn(pv, vv, x); + } + acc[mt][jj][e] = x; + } + } + } + } + __syncthreads(); + if (t + 2 < ntiles) load_tile(t + 2); + tf_common::cp_commit(); + } + }; + + if constexpr (!ROWS) { + run_pass(k0, k1 - k0, 0, 0u, 0, 0); + } else { + unsigned todo = live; + while (todo) { + const int i0 = __ffs(todo) - 1; + const int sig = rinfo[16 + i0]; + unsigned pass = 0; + int lo = 0x7fffffff, hi = -1, vlo = -1, vhi = 0x7fffffff; + for (int i = 0; i < 16; ++i) { + if (((todo >> i) & 1) && rinfo[16 + i] == sig) { + pass |= 1u << i; + const int pr = rinfo[i]; + const int wl = kind == 0 ? max(0, pr - (SWA_KEYS - 1)) : 0; + lo = min(lo, wl); + hi = max(hi, pr); + vlo = max(vlo, wl); + vhi = min(vhi, pr); + } + } + todo &= ~pass; + run_pass(lo, hi - lo + 1, sig, pass, vlo, vhi); + } + } + + float* m_s = rowv + NQ; + float* l_s = rowv + 2 * NQ; + float* w_s = rowv + 3 * NQ; + float* d_s = rowv + 4 * NQ; + if (ssub == 0) { + m_s[srow] = m_run; + l_s[srow] = l_run; + } + __syncthreads(); + TSTAMP(2); + + auto head_of = [&](int row) { return ROWS ? h0 + (row >> 4) : h0 + row; }; + if (nspl == 1) { + if (tid < NQ) { + const int h = head_of(tid); + const float m = m_s[tid], l = l_s[tid], sk = h < a.Hl ? a.SINKS[h] : -INFINITY; + const float top = nmax(m, sk); + const float w = m == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(m, top)); + const float es = sk == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(sk, top)); + w_s[tid] = w; + d_s[tid] = __fmaf_rn(l, w, es); + } + __syncthreads(); +#pragma unroll + for (int mt = 0; mt < MT; ++mt) +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int row = mt * 16 + g + 8 * hf; + size_t orow; + if constexpr (!ROWS) { + const int h = h0 + row; + if (h >= a.Hl) continue; + orow = static_cast(r) * a.Hl + h; + } else { + const int r16 = row & 15; + const int h = h0 + mt; + if (!((live >> r16) & 1) || h >= a.Hl) continue; + orow = static_cast(r + r16) * a.Hl + h; + } + const float w = w_s[row], d = d_s[row]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int col = warp * 64 + jj * 8 + 2 * q4; + store2(a.OUT, orow * KL + col, fin(acc[mt][jj][2 * hf], w, d), fin(acc[mt][jj][2 * hf + 1], w, d), + a.out_f32); + } + } + return; + } + + if constexpr (!ROWS) { + const int HB = gridDim.y, NS = gridDim.x; + const size_t blk = static_cast(r) * HB + hb; + const size_t pb0 = blk * NS * NQ; + const size_t pj = pb0 + static_cast(j) * NQ; +#pragma unroll + for (int mt = 0; mt < MT; ++mt) +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int row = mt * 16 + g + 8 * hf; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int col = warp * 64 + jj * 8 + 2 * q4; + *reinterpret_cast(a.PO + (pj + row) * KL + col) = + make_float2(acc[mt][jj][2 * hf], acc[mt][jj][2 * hf + 1]); + } + } + if (tid < NQ) { + a.PM[pj + tid] = m_s[tid]; + a.PL[pj + tid] = l_s[tid]; + } + if (a.TICKET == nullptr) return; + __threadfence(); + __syncthreads(); + if (tid == 0) misc[0] = atomicAdd(a.TICKET + blk, 1) == nspl - 1; + __syncthreads(); + TSTAMP(3); + if (!misc[0]) return; + __threadfence(); + constexpr int WJ_CAP = 256; + static_assert(WJ_CAP * NQ * 4 <= C::ROW, "smem before ROW holds 256 split weights"); + fold_rows(a, pb0, nspl, h0, r, 0, KL, reinterpret_cast(sm), WJ_CAP, d_s, rowv + 5 * NQ); + if (tid == 0) atomicExch(a.TICKET + blk, 0); + __syncthreads(); + TSTAMP(4); + } +} + +} // namespace detail +} // namespace hy4_mla diff --git a/zig/kernels/cuda/hy4_flash/mla_attn_paged.cu b/zig/kernels/cuda/hy4_flash/mla_attn_paged.cu new file mode 100644 index 00000000000..c8c71ce06f4 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_attn_paged.cu @@ -0,0 +1,260 @@ +// Absorbed latent MLA tensor-core kernels (`mma.m16n8k16` bf16 -> fp32; see `hy4_mla_attn.cuh` and `hy4_mla_core.cuh`). +#include "mla_attn_paged.cuh" + +#include + +#include "../common/cp_async.cuh" +#include "../common/glue_math.cuh" +#include "../common/qmm_frag.cuh" + +#define TSTAMP(i) + +namespace hy4_mla { +namespace detail { + +typedef __nv_bfloat16 bf16; +constexpr unsigned FULL = 0xffffffffu; +constexpr float SCALE = 0.0625f; // 256^-0.5, exact + +// max that keeps NaN (float64's max over a set holding NaN is NaN); fmaxf would drop it +__device__ __forceinline__ float nmax(float a, float b) { return (a != a || a > b) ? a : b; } + +__device__ __forceinline__ uint32_t saddr(const void* p) { return tf_common::smem(p); } + +__device__ __forceinline__ void ldsm4(uint32_t (&r)[4], uint32_t a) { qmm_frag::ldmatrix4(r, a); } +__device__ __forceinline__ void ldsm2(uint32_t (&r)[2], uint32_t a) { qmm_frag::ldmatrix2(r, a); } +__device__ __forceinline__ void ldsm4t(uint32_t (&r)[4], uint32_t a) { qmm_frag::ldmatrix4t(r, a); } +__device__ __forceinline__ void mma(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { + qmm_frag::mma(d, a, b0, b1); +} + +// element offset of 16-byte unit u of a 576-wide row (q and KV stages) +__device__ __forceinline__ int wide(int row, int u) { return row * KW + ((u ^ (row & 7)) << 3); } +// element offset of unit u of a KT-wide P row +template +__device__ __forceinline__ int narrow(int row, int u) { + if constexpr (KT == 32) return row * 32 + ((u ^ ((row >> 1) & 3)) << 3); + else return row * 16 + ((u ^ ((row >> 2) & 1)) << 3); +} + +__device__ __forceinline__ bool nonfinite8(uint4 v) { + const uint32_t w[4] = {v.x, v.y, v.z, v.w}; + bool bad = false; +#pragma unroll + for (int i = 0; i < 4; ++i) bad |= ((w[i] & 0x7F800000u) == 0x7F800000u) || ((w[i] & 0x7F80u) == 0x7F80u); + return bad; +} + +__device__ __forceinline__ float fin(float a, float w, float d) { + return d == 0.f ? 0.f : __fdiv_rn(__fmul_rn(a, w), d); // d == 0: no visible key and a -inf sink (stated rule) +} + +__device__ __forceinline__ void store2(void* out, size_t i, float a, float b, int f32) { + if (f32 & 1) *reinterpret_cast(static_cast(out) + i) = make_float2(a, b); + else *reinterpret_cast<__nv_bfloat162*>(static_cast(out) + i) = __floats2bfloat162_rn(a, b); +} + +template +struct Lay { + static constexpr int NQ = MT * 16; // queries a CTA + static constexpr int NTILE = MT * KT / 8; // (m16, n8) S tiles + static constexpr int KSPLIT = 8 / NTILE; // warps a tile, each a k-slice + static constexpr int KSTEPS = 36 / KSPLIT; // k16 steps a warp + static constexpr int SPAD = KT + 8; // S partial row stride (floats): conflict-free float2 stores + static constexpr int TPR = NT / NQ; // softmax threads a row + static constexpr int CPT = KT / TPR; // softmax columns a thread + static constexpr int Q = 0; + static constexpr int QLO = Q + (QREG ? 0 : NQ * KW * 2); + static constexpr int KV = QLO + ((EXACT && !QREG) ? NQ * KW * 2 : 0); + static constexpr int P = KV + 2 * KT * KW * 2; + static constexpr int PLO = P + NQ * KT * 2; + static constexpr int RED = PLO + (EXACT ? NQ * KT * 2 : 0); + static constexpr int KP = RED + KSPLIT * NQ * SPAD * 4; + static constexpr int ROW = KP + 2 * KT * 4; // [6][NQ] fp32: alpha, m, l, w, den, spare + static constexpr int RINFO = ROW + 6 * NQ * 4; // rows-in-M: [16] positions, [16] streams + static constexpr int MISC = RINFO + 128; + static constexpr int BYTES = MISC + 16; + static constexpr int SPLIT_CAP = KSPLIT * SPAD; // the merge's weights [nsplit][NQ] reuse the S partials + static_assert(8 % NTILE == 0 && 36 % KSPLIT == 0 && KT % TPR == 0 && TPR <= 32, "tile shape"); + static_assert(CPT == 1 || CPT % 2 == 0, "P pairs"); + static_assert(!(EXACT && QREG && MT > 1), "exact qreg holds MT=1 q hi+lo in registers"); + static_assert(BYTES == smem_bytes(MT, KT, QREG, EXACT), "smem layout and the header's byte count agree"); +}; + +struct Args { + const bf16* QA; + int Hl; + const bf16* CACHE; + int kind, ring, ctx; + const int* ROW_STREAM; + const int* ROW_POS; + const int* LIST; + const int* TOK; + int ldtok, ntok; + const float* SINKS; + int ch; + float* PM; + float* PL; + float* PO; + int* TICKET; + void* OUT; + int out_f32, R; + long long QLO = 0; // EXACT: elements from QA to the q lo plane + const unsigned long long* ROW_CACHE = nullptr; // batched decode: per-row MLA cache pointer table + const unsigned int* PAGE_TABLE = nullptr; // paged indexed KV: [stream, max_pages] u32 (256 rows/page) + int pt_stride = 0; +}; + +// Split fold for one `(row, head block)` in ascending split order, shared by ticket and `hy4_mla_fold`. +template +__device__ __forceinline__ void fold_rows(const Args& a, size_t pb0, int nspl, int h0, int r, int c0, int c1, + float* wj, int wj_cap, float* d_s, float* top_s) { + const int tid = threadIdx.x; + if (tid < NQ) { + const int h = h0 + tid; + const float sk = h < a.Hl ? a.SINKS[h] : -INFINITY; + float top = __ldcg(a.PM + pb0 + tid); + for (int jj = 1; jj < nspl; ++jj) top = nmax(top, __ldcg(a.PM + pb0 + static_cast(jj) * NQ + tid)); + top = nmax(top, sk); + top_s[tid] = top; + float den = sk == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(sk, top)); + for (int jj = 0; jj < nspl; ++jj) { + const float mj = __ldcg(a.PM + pb0 + static_cast(jj) * NQ + tid); + const float w = mj == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(mj, top)); + if (jj < wj_cap) wj[jj * NQ + tid] = w; + den = __fmaf_rn(__ldcg(a.PL + pb0 + static_cast(jj) * NQ + tid), w, den); + } + d_s[tid] = den; + } + __syncthreads(); + const int cw = (c1 - c0) / 4; // float4 units a row + constexpr int CH = 8; // splits in flight a unit + const bool cached = nspl <= wj_cap; + for (int u = tid; u < NQ * cw; u += blockDim.x) { + const int row = u / cw, c4 = c0 + (u % cw) * 4; + const int h = h0 + row; + if (h >= a.Hl) continue; + const float* src = a.PO + (pb0 + row) * KL + c4; + const float top = top_s[row]; + float o0 = 0.f, o1 = 0.f, o2 = 0.f, o3 = 0.f; + for (int j0 = 0; j0 < nspl; j0 += CH) { + float4 v[CH]; +#pragma unroll + for (int jj = 0; jj < CH; ++jj) + if (j0 + jj < nspl) + v[jj] = __ldcg(reinterpret_cast(src + static_cast(j0 + jj) * NQ * KL)); + if (cached) { +#pragma unroll + for (int jj = 0; jj < CH; ++jj) + if (j0 + jj < nspl) { + const float w = wj[(j0 + jj) * NQ + row]; + o0 = __fmaf_rn(v[jj].x, w, o0); + o1 = __fmaf_rn(v[jj].y, w, o1); + o2 = __fmaf_rn(v[jj].z, w, o2); + o3 = __fmaf_rn(v[jj].w, w, o3); + } + } else { +#pragma unroll + for (int jj = 0; jj < CH; ++jj) + if (j0 + jj < nspl) { + const float mj = __ldcg(a.PM + pb0 + static_cast(j0 + jj) * NQ + row); + const float w = mj == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(mj, top)); + o0 = __fmaf_rn(v[jj].x, w, o0); + o1 = __fmaf_rn(v[jj].y, w, o1); + o2 = __fmaf_rn(v[jj].z, w, o2); + o3 = __fmaf_rn(v[jj].w, w, o3); + } + } + } + const float d = d_s[row]; + const size_t at = (static_cast(r) * a.Hl + h) * KL + c4; + store2(a.OUT, at, d == 0.f ? 0.f : __fdiv_rn(o0, d), d == 0.f ? 0.f : __fdiv_rn(o1, d), a.out_f32); + store2(a.OUT, at + 2, d == 0.f ? 0.f : __fdiv_rn(o2, d), d == 0.f ? 0.f : __fdiv_rn(o3, d), a.out_f32); + } +} + +} // namespace detail +} // namespace hy4_mla + +#include "mla_attn_core.cuh" +#include "mla_attn_x16_qreg.cuh" + +using hy4_mla::detail::Args; +using hy4_mla::detail::attn_body; +using hy4_mla::detail::x16_qreg_body; + +#define HY4_MLA_SPLIT_PACK \ + Args a{QA, Hl, CACHE, kind, ring, ctx, ROW_STREAM, ROW_POS, LIST, TOK, ldtok, ntok, SINKS, ch, PM, PL, PO, TICKET, \ + OUT, out_f32, R} + +extern "C" __global__ void __launch_bounds__(256, 1) hy4_mla_dec_x16(HY4_MLA_SPLIT_ARGS, long long QLO) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + attn_body<1, 16, false, false, true>(a); +} + +extern "C" __global__ void __launch_bounds__(256, 1) hy4_mla_dec_x16_rows(HY4_MLA_SPLIT_ARGS, long long QLO) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + a.ROW_CACHE = reinterpret_cast(CACHE); + a.CACHE = nullptr; + attn_body<1, 16, false, false, true>(a); +} + +extern "C" __global__ void __launch_bounds__(256, 2) hy4_mla_dec_x16_qreg(HY4_MLA_SPLIT_ARGS, long long QLO) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + x16_qreg_body(a); +} + +extern "C" __global__ void __launch_bounds__(256, 2) hy4_mla_dec_x16_qreg_rows(HY4_MLA_SPLIT_ARGS, long long QLO) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + a.ROW_CACHE = reinterpret_cast(CACHE); + a.CACHE = nullptr; + x16_qreg_body(a); +} + +extern "C" __global__ void __launch_bounds__(256, 1) + hy4_mla_dec_x16_paged(HY4_MLA_SPLIT_ARGS, long long QLO, const unsigned int* PAGE_TABLE, int pt_stride) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + a.PAGE_TABLE = PAGE_TABLE; + a.pt_stride = pt_stride; + attn_body<1, 16, false, false, true>(a); +} + +extern "C" __global__ void __launch_bounds__(256, 2) + hy4_mla_dec_x16_qreg_paged(HY4_MLA_SPLIT_ARGS, long long QLO, const unsigned int* PAGE_TABLE, int pt_stride) { + HY4_MLA_SPLIT_PACK; + a.QLO = QLO; + a.PAGE_TABLE = PAGE_TABLE; + a.pt_stride = pt_stride; + x16_qreg_body(a); +} + +// Second pass of 2-launch split+fold (`TICKET = nullptr`): folds rows with `nspl > 1` (`grid (8, ceil(Hl / nq), R)`). +extern "C" __global__ void __launch_bounds__(256) hy4_mla_fold(int Hl, int nq, int kind, const int* __restrict__ ROW_POS, + int ntok, int ch, int NS, const float* __restrict__ PM, + const float* __restrict__ PL, const float* __restrict__ PO, + const float* __restrict__ SINKS, void* __restrict__ OUT, + int out_f32, int R) { + using namespace hy4_mla; + using namespace hy4_mla::detail; + __shared__ float wj[128 * 32]; + __shared__ float d_s[32]; + __shared__ float top_s[32]; + qmm_frag::grid_wait(); + qmm_frag::grid_launch(); + const int s = blockIdx.x, hb = blockIdx.y, r = blockIdx.z; + const int p = ROW_POS[r]; + const int n = kind == 0 ? min(p + 1, SWA_KEYS) : (kind == 1 ? (p >= DSA_KEYS ? DSA_KEYS : p + 1) : ntok); + const int nspl = (n + ch - 1) / ch; + if (nspl <= 1) return; // finalised by the split kernel + Args a{nullptr, Hl, nullptr, kind, 0, 0, nullptr, ROW_POS, nullptr, nullptr, 0, ntok, SINKS, ch, const_cast(PM), + const_cast(PL), const_cast(PO), nullptr, OUT, out_f32, R}; + const size_t pb0 = (static_cast(r) * gridDim.y + hb) * NS * nq; + const int c0 = s * (hy4_mla::KL / gridDim.x), c1 = c0 + hy4_mla::KL / gridDim.x; + if (nq == 32) fold_rows<32>(a, pb0, nspl, hb * nq, r, c0, c1, wj, 128, d_s, top_s); + else fold_rows<16>(a, pb0, nspl, hb * nq, r, c0, c1, wj, 256, d_s, top_s); +} diff --git a/zig/kernels/cuda/hy4_flash/mla_attn_paged.cuh b/zig/kernels/cuda/hy4_flash/mla_attn_paged.cuh new file mode 100644 index 00000000000..ad29b168cb6 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_attn_paged.cuh @@ -0,0 +1,69 @@ +// Absorbed latent MLA attention on tensor cores (`mma.m16n8k16` bf16 -> fp32): split+fold decode and 1-split prefill. +#pragma once + +#include +#include +#include + +namespace hy4_mla { + +constexpr int KW = 576; // cache row: 512 latent + 64 roped key +constexpr int KL = 512; // latent width (the output) +constexpr int LISTW = 512; // group list width (indexed layers, p >= 2048) +constexpr int SWA_KEYS = 512; +constexpr int DSA_KEYS = 2048; +constexpr int NT = 256; // threads a CTA (8 warps) + +// Dynamic shared-memory bytes per CTA (`exact`: hi+lo bf16 planes for Q and P). +constexpr int smem_bytes(int mt, int kt, bool qreg, bool exact = false) { + return (qreg ? 0 : mt * 16 * KW * 2) * (exact ? 2 : 1) + 2 * kt * KW * 2 + mt * 16 * kt * 2 * (exact ? 2 : 1) + + (8 / (mt * kt / 8)) * mt * 16 * (kt + 8) * 4 + 2 * kt * 4 + 6 * mt * 16 * 4 + 128 + 16; +} +constexpr int SMEM_X16 = smem_bytes(1, 16, false, true); // exact 16 heads, KT = 16 +constexpr int SMEM_X16_QREG = ((smem_bytes(1, 16, true, true) + 127) & ~127) + 4 * 16 * 32 * 2; // 48,896 B (2 CTAs/SM) +static_assert(SMEM_X16_QREG == 48896 && 2 * SMEM_X16_QREG <= 101376, "x16_qreg must fit 2 CTAs/SM"); +constexpr int SMEM_DEC_KT32 = smem_bytes(1, 32, false); // Arm A: 99,088 B, 1 CTA/SM +constexpr int SMEM_DEC_QREG_KT16 = smem_bytes(1, 16, true); // Arm B: 44,176 B, 2 CTAs/SM +constexpr int SMEM_MT2_KT16 = smem_bytes(2, 16, false); // 32 queries a KV tile: 81,936 B +constexpr int SMEM_QREG_KT32 = smem_bytes(1, 32, true); // q in registers, KT = 32: 80,656 B +constexpr int SMEM_MT2_QREG_KT16 = smem_bytes(2, 16, true); // q in registers, 32 queries, KT = 16: 45,072 B +static_assert(SMEM_DEC_KT32 <= 100352, "sm_121 contract limit"); +static_assert(2 * (SMEM_DEC_QREG_KT16 + 1024) <= 102400, "Arm B must fit 2 CTAs/SM"); +static_assert(SMEM_MT2_KT16 <= 100352, "sm_121 contract limit"); + +// Keys of the longest row of a layer kind (the split grid's x extent is ceil(max_keys / ch)). +inline int max_keys(int kind, int ntok) { return kind == 0 ? SWA_KEYS : (kind == 1 ? DSA_KEYS : ntok); } + +// Fixed decode/verify chunk size per (kind, Hl) across R = 1..16 (guarantees drafted == serial 0-bit parity). +inline int decode_ch(int kind, int Hl) { (void)Hl; return kind == 0 ? 64 : 128; } + +// Required float count for `PM`/`PL` scratch (`PO = 512 * scratch_floats`); 0 when `R > 16`. +inline size_t scratch_floats(int kind, int Hl, int R, int ntok) { + if (R > 16) return 0; + const int ch = decode_ch(kind, Hl); + const int ns = (max_keys(kind, ntok) + ch - 1) / ch; + const int hb = (Hl + 15) / 16; + return ns > 1 ? static_cast(R) * hb * 16 * ns : 0; +} + +} // namespace hy4_mla + +// Split-key decode/verify and 1-split heads-in-M prefill (`grid (nsplit, ceil(Hl / (16*MT)), R)`, block `256`). +#define HY4_MLA_SPLIT_ARGS \ + const __nv_bfloat16 *__restrict__ QA, int Hl, const __nv_bfloat16 *__restrict__ CACHE, int kind, int ring, int ctx, \ + const int *__restrict__ ROW_STREAM, const int *__restrict__ ROW_POS, const int *__restrict__ LIST, \ + const int *__restrict__ TOK, int ldtok, int ntok, const float *__restrict__ SINKS, int ch, \ + float *__restrict__ PM, float *__restrict__ PL, float *__restrict__ PO, int *__restrict__ TICKET, \ + void *__restrict__ OUT, int out_f32, int R + +// Exact: 16 heads a CTA, KT = 16, q hi/lo planes (the lo plane QLO elements after QA) and P hi/lo planes, SMEM_X16. +extern "C" __global__ void hy4_mla_dec_x16(HY4_MLA_SPLIT_ARGS, long long QLO); +extern "C" __global__ void hy4_mla_dec_x16_rows(HY4_MLA_SPLIT_ARGS, long long QLO); +extern "C" __global__ void hy4_mla_dec_x16_qreg(HY4_MLA_SPLIT_ARGS, long long QLO); +extern "C" __global__ void hy4_mla_dec_x16_qreg_rows(HY4_MLA_SPLIT_ARGS, long long QLO); + +// Second pass of 2-launch split+fold (`TICKET = nullptr`): folds rows with `nspl > 1` in ascending split order. +extern "C" __global__ void hy4_mla_fold(int Hl, int nq, int kind, const int *__restrict__ ROW_POS, int ntok, int ch, int NS, + const float *__restrict__ PM, const float *__restrict__ PL, + const float *__restrict__ PO, const float *__restrict__ SINKS, + void *__restrict__ OUT, int out_f32, int R); diff --git a/zig/kernels/cuda/hy4_flash/mla_attn_x16_qreg.cuh b/zig/kernels/cuda/hy4_flash/mla_attn_x16_qreg.cuh new file mode 100644 index 00000000000..02cc3cffa4b --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_attn_x16_qreg.cuh @@ -0,0 +1,294 @@ +// Low-spill 2-CTA/SM FP32-exact x16_qreg MLA kernel (GrgaPalcic & popay97, 2026; 48,896 B SMEM, hoisted pls). +#pragma once + +namespace hy4_mla { +namespace detail { + +__device__ __forceinline__ void x16_qreg_body(const Args& a) { + using C = Lay<1, 16, true, true>; + constexpr int KT = 16, NQ = 16; + static_assert(KT == 16 && NQ == 16 && 0x47503937u != 0u, "gp97:x16-qreg"); + extern __shared__ __align__(128) unsigned char sm[]; + bf16* kvs = reinterpret_cast(sm + C::KV); + bf16* ps = reinterpret_cast(sm + C::P); + bf16* pls = reinterpret_cast(sm + C::PLO); + float* red = reinterpret_cast(sm + C::RED); + int* kpos = reinterpret_cast(sm + C::KP); + float* rowv = reinterpret_cast(sm + C::ROW); + int* rinfo = reinterpret_cast(sm + C::RINFO); + bf16* qlo_sm = reinterpret_cast(sm + ((C::BYTES + 127) & ~127)); + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, q4 = lane & 3; + qmm_frag::grid_wait(); + qmm_frag::grid_launch(); + TSTAMP(0); + + const int j = blockIdx.x, hb = blockIdx.y, r = blockIdx.z; + const int prow = a.ROW_POS[r]; + const int kind = a.kind; + const bool lst = kind == 1 && prow >= DSA_KEYS; + const int n = kind == 0 ? min(prow + 1, SWA_KEYS) : (kind == 1 ? (lst ? DSA_KEYS : prow + 1) : a.ntok); + const int nspl = (n + a.ch - 1) / a.ch; + if (j >= nspl) return; + const int k0 = j * a.ch, k1 = min(n, k0 + a.ch); + const int nkeys = k1 - k0, ntiles = (nkeys + KT - 1) / KT; + + if (tid == 0) { + rinfo[0] = prow; + rinfo[1] = nspl; + rinfo[2] = k0; + rinfo[3] = nkeys; + rinfo[4] = ntiles; + rinfo[5] = lst ? 1 : 0; + const int s_ = a.ROW_STREAM[r]; + rinfo[6] = s_; + const size_t sbase = (a.ROW_CACHE || (a.PAGE_TABLE && kind != 0)) + ? 0 + : (kind == 0 ? static_cast(s_) * a.ring : static_cast(s_) * a.ctx); + const unsigned char* rc = a.ROW_CACHE ? reinterpret_cast(a.ROW_CACHE[r]) + : reinterpret_cast(a.CACHE + sbase * KW); + *reinterpret_cast(rinfo + 8) = rc; + } + + uint32_t qf[9][4]; + uint32_t qfl[7][4]; + { + const int kp = warp >> 1; + const int h0 = hb * NQ; + const int ha = h0 + g, hb_ = ha + 8; + const bool ok0 = ha < a.Hl, ok8 = hb_ < a.Hl; + const bf16* q0 = a.QA + (static_cast(r) * a.Hl + (ok0 ? ha : 0)) * KW; + const bf16* q8 = a.QA + (static_cast(r) * a.Hl + (ok8 ? hb_ : 0)) * KW; +#pragma unroll + for (int s = 0; s < 9; ++s) { + const int kb = (kp * 9 + s) * 16 + 2 * q4; + qf[s][0] = ok0 ? __ldg(reinterpret_cast(q0 + kb)) : 0u; + qf[s][1] = ok8 ? __ldg(reinterpret_cast(q8 + kb)) : 0u; + qf[s][2] = ok0 ? __ldg(reinterpret_cast(q0 + kb + 8)) : 0u; + qf[s][3] = ok8 ? __ldg(reinterpret_cast(q8 + kb + 8)) : 0u; + if (s < 7) { + qfl[s][0] = ok0 ? __ldg(reinterpret_cast(q0 + a.QLO + kb)) : 0u; + qfl[s][1] = ok8 ? __ldg(reinterpret_cast(q8 + a.QLO + kb)) : 0u; + qfl[s][2] = ok0 ? __ldg(reinterpret_cast(q0 + a.QLO + kb + 8)) : 0u; + qfl[s][3] = ok8 ? __ldg(reinterpret_cast(q8 + a.QLO + kb + 8)) : 0u; + } + } + // Single-pass load of k16 steps s = 7, 8 of Q_lo into qlo_sm[4 kp][16 rows][32 bf16] (4,096 B). + const int l_kp = tid >> 6; + const int l_row = (tid >> 2) & 15; + const int l_u = tid & 3; + const bool ok = (h0 + l_row) < a.Hl; + const bf16* src = a.QA + (static_cast(r) * a.Hl + (ok ? h0 + l_row : 0)) * KW + a.QLO + (l_kp * 9 + 7) * 16; + tf_common::cp16z(qlo_sm + l_kp * 512 + narrow<32>(l_row, l_u), src + l_u * 8, ok); + tf_common::cp_commit(); + } + tf_common::cp_wait<0>(); + __syncthreads(); + + float m_run = -INFINITY, l_run = 0.f; + float acc[8][4]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) acc[jj][0] = acc[jj][1] = acc[jj][2] = acc[jj][3] = 0.f; + + auto load_tile = [&](int t) { + constexpr int TPK = NT / KT; + bf16* dst = kvs + (t & 1) * KT * KW; + const int kk = tid / TPK, part = tid % TPK; + const int lk0 = rinfo[2], lnkeys = rinfo[3], lprow = rinfo[0], llst = rinfo[5]; + const int i = lk0 + t * KT + kk; + bool ok = i < lk0 + lnkeys; + int pos = -1; + if (ok) { + if (a.kind == 0) { + pos = lprow - min(lprow + 1, SWA_KEYS) + 1 + i; + } else if (a.kind == 1) { + if (!llst) { + pos = i; + } else { + const int gi = __ldg(a.LIST + static_cast(blockIdx.z) * LISTW + (i >> 2)); + pos = gi < 0 ? -1 : 4 * gi + (i & 3); + } + } else { + pos = __ldg(a.TOK + static_cast(blockIdx.z) * a.ldtok + i); + } + ok = pos >= 0 && pos <= lprow; + } + size_t slot = 0; + if (ok) { + if (a.PAGE_TABLE && a.kind != 0) { + const unsigned up = static_cast(pos); + const size_t pt_base = static_cast(rinfo[6]) * a.pt_stride; + slot = static_cast(__ldg(a.PAGE_TABLE + pt_base + (up >> 8))) * 256u + (up & 255u); + } else { + slot = a.kind == 0 ? static_cast(pos % a.ring) : static_cast(pos); + } + } + const unsigned char* base_u8 = *reinterpret_cast(rinfo + 8); + const bf16* src = reinterpret_cast(base_u8) + slot * KW; +#pragma unroll + for (int u = part; u < KW / 8; u += TPK) tf_common::cp16z(dst + wide(kk, u), src + u * 8, ok); + if (part == 0) kpos[(t & 1) * KT + kk] = ok ? pos : -1; + }; + + const int ntiles_l = rinfo[4]; + load_tile(0); + tf_common::cp_commit(); + if (ntiles_l > 1) load_tile(1); + tf_common::cp_commit(); + + for (int t = 0; t < ntiles_l; ++t) { + tf_common::cp_wait<1>(); + __syncthreads(); + if (t == 0) TSTAMP(1); + const bf16* kv = kvs + (t & 1) * KT * KW; + const int* kp_t = kpos + (t & 1) * KT; + { + const int ntile = warp & 1, kp = warp >> 1; + float c0[4] = {0.f, 0.f, 0.f, 0.f}, c1[4] = {0.f, 0.f, 0.f, 0.f}; + const int ks0 = kp * 9; +#pragma unroll + for (int s = 0; s < 6; s += 2) { + const int ks = ks0 + s; + uint32_t b[4]; + ldsm4(b, saddr(kv + wide(ntile * 8 + (lane & 7), ks * 2 + (lane >> 3)))); + mma(c0, qf[s], b[0], b[1]); + mma(c1, qf[s + 1], b[2], b[3]); + mma(c0, qfl[s], b[0], b[1]); + mma(c1, qfl[s + 1], b[2], b[3]); + } + { + uint32_t b[4], ql7[4]; + ldsm4(b, saddr(kv + wide(ntile * 8 + (lane & 7), (ks0 + 6) * 2 + (lane >> 3)))); + ldsm4(ql7, saddr(qlo_sm + kp * 512 + narrow<32>(lane & 15, lane >> 4))); + mma(c0, qf[6], b[0], b[1]); + mma(c1, qf[7], b[2], b[3]); + mma(c0, qfl[6], b[0], b[1]); + mma(c1, ql7, b[2], b[3]); + } + { + uint32_t b[2], ql8[4]; + ldsm2(b, saddr(kv + wide(ntile * 8 + (lane & 7), (ks0 + 8) * 2 + ((lane >> 3) & 1)))); + ldsm4(ql8, saddr(qlo_sm + kp * 512 + narrow<32>(lane & 15, 2 + (lane >> 4)))); + mma(c0, qf[8], b[0], b[1]); + mma(c0, ql8, b[0], b[1]); + } + float* rd = red + kp * NQ * C::SPAD + ntile * 8 + 2 * q4; + *reinterpret_cast(rd + g * C::SPAD) = make_float2(__fadd_rn(c0[0], c1[0]), __fadd_rn(c0[1], c1[1])); + *reinterpret_cast(rd + (g + 8) * C::SPAD) = + make_float2(__fadd_rn(c0[2], c1[2]), __fadd_rn(c0[3], c1[3])); + } + __syncthreads(); + { + const int srow = tid >> 4, ssub = tid & 15; + float v = red[srow * C::SPAD + ssub]; +#pragma unroll + for (int ks = 1; ks < C::KSPLIT; ++ks) v = __fadd_rn(v, red[(ks * NQ + srow) * C::SPAD + ssub]); + const bool vis = kp_t[ssub] >= 0; + const float sc = vis ? __fmul_rn(v, SCALE) : -INFINITY; + float tm = sc; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) tm = nmax(tm, __shfl_xor_sync(FULL, tm, o)); + const bool act = tm != -INFINITY; + const float mn = act ? nmax(m_run, tm) : m_run; + const float al = act ? (m_run == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(m_run, mn))) : 1.f; + const float pv = (act && vis) ? tf_glue::tf_exp(__fsub_rn(sc, mn)) : 0.f; + const bf16 pb = __float2bfloat16_rn(pv); + const bf16 plb = __float2bfloat16_rn(__fsub_rn(pv, __bfloat162float(pb))); + float ls = pv; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) ls = __fadd_rn(ls, __shfl_xor_sync(FULL, ls, o)); + l_run = __fmaf_rn(l_run, al, ls); + m_run = mn; + ps[narrow(srow, ssub >> 3) + (ssub & 7)] = pb; + pls[narrow(srow, ssub >> 3) + (ssub & 7)] = plb; + if (ssub == 0) rowv[srow] = al; + } + __syncthreads(); + { + const float a0 = rowv[g], a1 = rowv[g + 8]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + acc[jj][0] = __fmul_rn(acc[jj][0], a0); + acc[jj][1] = __fmul_rn(acc[jj][1], a0); + acc[jj][2] = __fmul_rn(acc[jj][2], a1); + acc[jj][3] = __fmul_rn(acc[jj][3], a1); + } + uint32_t pa[4], pl[4]; + ldsm4(pa, saddr(ps + narrow(lane & 15, lane >> 4))); + ldsm4(pl, saddr(pls + narrow(lane & 15, lane >> 4))); +#pragma unroll + for (int jj = 0; jj < 8; jj += 2) { + uint32_t b[4]; + ldsm4t(b, saddr(kv + wide(lane & 15, warp * 8 + jj + (lane >> 4)))); + mma(acc[jj], pa, b[0], b[1]); + mma(acc[jj + 1], pa, b[2], b[3]); + mma(acc[jj], pl, b[0], b[1]); + mma(acc[jj + 1], pl, b[2], b[3]); + } + } + __syncthreads(); + if (t + 2 < ntiles_l) load_tile(t + 2); + tf_common::cp_commit(); + } + + const int srow = tid >> 4, ssub = tid & 15; + float* m_s = rowv + NQ; + float* l_s = rowv + 2 * NQ; + float* w_s = rowv + 3 * NQ; + float* d_s = rowv + 4 * NQ; + if (ssub == 0) { + m_s[srow] = m_run; + l_s[srow] = l_run; + } + __syncthreads(); + TSTAMP(2); + + const int er = blockIdx.z, ehb = blockIdx.y, ej = blockIdx.x, eh0 = ehb * NQ, enspl = rinfo[1]; + if (enspl == 1) { + if (tid < NQ) { + const int h = eh0 + tid; + const float m = m_s[tid], l = l_s[tid], sk = h < a.Hl ? a.SINKS[h] : -INFINITY; + const float top = nmax(m, sk); + const float w = m == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(m, top)); + const float es = sk == -INFINITY ? 0.f : tf_glue::tf_exp(__fsub_rn(sk, top)); + w_s[tid] = w; + d_s[tid] = __fmaf_rn(l, w, es); + } + __syncthreads(); +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int row = g + 8 * hf, h = eh0 + row; + if (h >= a.Hl) continue; + const size_t orow = static_cast(er) * a.Hl + h; + const float w = w_s[row], d = d_s[row]; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int col = warp * 64 + jj * 8 + 2 * q4; + store2(a.OUT, orow * KL + col, fin(acc[jj][2 * hf], w, d), fin(acc[jj][2 * hf + 1], w, d), a.out_f32); + } + } + return; + } + + const int HB = gridDim.y, NS = gridDim.x; + const size_t blk = static_cast(er) * HB + ehb; + const size_t pb0 = blk * NS * NQ; + const size_t pj = pb0 + static_cast(ej) * NQ; +#pragma unroll + for (int hf = 0; hf < 2; ++hf) { + const int row = g + 8 * hf; +#pragma unroll + for (int jj = 0; jj < 8; ++jj) { + const int col = warp * 64 + jj * 8 + 2 * q4; + *reinterpret_cast(a.PO + (pj + row) * KL + col) = + make_float2(acc[jj][2 * hf], acc[jj][2 * hf + 1]); + } + } + if (tid < NQ) { + a.PM[pj + tid] = m_s[tid]; + a.PL[pj + tid] = l_s[tid]; + } +} + +} // namespace detail +} // namespace hy4_mla diff --git a/zig/kernels/cuda/hy4_flash/mla_c2.cu b/zig/kernels/cuda/hy4_flash/mla_c2.cu new file mode 100644 index 00000000000..a3c438af75b --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_c2.cu @@ -0,0 +1,37 @@ +// Extern "C" entry points for Hy4-flash MLA query absorb (`W_UK_T`) and gated value expand (`W_UV`). +#include "mla_c2.cuh" + +using namespace hy4c2; + +// K MT NT WARPS KC STAGES D PLANES STREAM +#define C2_AD(NT) Cfg +#define C2_AP Cfg +#define C2_EDF(NT) Cfg +#define C2_EPF Cfg + +typedef C2_AD(1) AD1; +typedef C2_AD(2) AD2; +typedef C2_AP AP; +typedef C2_EDF(1) EDF1; +typedef C2_EDF(2) EDF2; +typedef Cfg EDF4_K64_S2; +typedef C2_EPF EPF; + +#define C2_ABSORB_X(NAME, CFG, MINB) \ + extern "C" __global__ void __launch_bounds__(CFG::THREADS, MINB) \ + NAME(const bf16* QB, int ldq, int R, int Hl, const bf16* WUKT, void* QA, long long QLO) { \ + absorb_body(QB, ldq, R, Hl, WUKT, nullptr, nullptr, QA, QLO); \ + } +C2_ABSORB_X(hy4c2_absorb_d1_x, AD1, 4) +C2_ABSORB_X(hy4c2_absorb_d2_x, AD2, 4) +C2_ABSORB_X(hy4c2_absorb_p_x, AP, 2) + +#define C2_EXPAND(NAME, CFG, LT, MINB) \ + extern "C" __global__ void __launch_bounds__(CFG::THREADS, MINB) \ + NAME(const LT* LAT, int R, int Hl, const bf16* WUV, const bf16* GATE, int ldg, bf16* ATT) { \ + expand_body(LAT, R, Hl, WUV, GATE, ldg, ATT); \ + } +C2_EXPAND(hy4c2_expand_d1_f32lat, EDF1, float, 4) +C2_EXPAND(hy4c2_expand_d2_f32lat, EDF2, float, 2) +C2_EXPAND(hy4c2_expand_d4k64s2_f32lat, EDF4_K64_S2, float, 3) +C2_EXPAND(hy4c2_expand_p_f32lat, EPF, float, 2) diff --git a/zig/kernels/cuda/hy4_flash/mla_c2.cuh b/zig/kernels/cuda/hy4_flash/mla_c2.cuh new file mode 100644 index 00000000000..9f9af43eb4c --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_c2.cuh @@ -0,0 +1,427 @@ +// Tensor-core MLA query absorption (`W_UK_T` + M-RoPE) and gated value expansion (`W_UV` + sigmoid gate). +#pragma once + +#include +#include +#include + +#include "../common/cp_async.cuh" +#include "../common/glue_math.cuh" +#include "../common/qmm_frag.cuh" + +namespace hy4c2 { + +typedef __nv_bfloat16 bf16; + +constexpr int KL = 512; // kv_lora_rank (latent) +constexpr int ND = 192; // qk_nope_head_dim +constexpr int RD = 64; // qk_rope_head_dim +constexpr int VD = 256; // v_head_dim +constexpr int QW = 576; // QA row: latent + rope +constexpr int QHS = 256; // q_b columns a head (192 nope + 64 rope) +constexpr int KVB = 448; // kv_b_proj rows a head (192 k_nope + 256 v) + +__device__ __forceinline__ float bfv(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ float bf_lo(uint32_t w) { return __uint_as_float(w << 16); } +__device__ __forceinline__ float bf_hi(uint32_t w) { return __uint_as_float(w & 0xFFFF0000u); } +__device__ __forceinline__ float rbf(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } +__device__ __forceinline__ uint32_t pack2(float lo, float hi) { + return static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(lo))) | + (static_cast(__bfloat16_as_ushort(__float2bfloat16_rn(hi))) << 16); +} + +// Decode streams weight bytes once (`L1::no_allocate`, `L2::evict_first`); prefill re-reads weights from L2. +__device__ __forceinline__ uint64_t evict_first_policy() { + uint64_t p; + asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;\n" : "=l"(p)); + return p; +} + +template +__device__ __forceinline__ uint4 ldw(const uint4* p, uint64_t pol) { + (void)pol; + if constexpr (STREAM) return tf_common::ld_nc(p); + return __ldg(p); +} + +__device__ __forceinline__ uint4 ld_stream(const void* p) { // read-once activations (q_rope, gate) + return tf_common::ld_nc(reinterpret_cast(p)); +} + +__device__ __forceinline__ void mma_bf16(float (&d)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, + uint32_t b1) { + const uint32_t a[4] = {a0, a1, a2, a3}; + qmm_frag::mma(d, a, b0, b1); +} + +__device__ __forceinline__ uint32_t word(const uint4& u, int i) { return i == 0 ? u.x : i == 1 ? u.y : i == 2 ? u.z : u.w; } + +// Branchlessly zero any bf16 lane whose 8 exponent bits are all 1 (`Inf`/`NaN`) on mid/lo fp32 planes. +__device__ __forceinline__ uint32_t zero_nf_bf16x2(uint32_t v) { + const uint32_t nf = (((v & 0x7F807F80u) + 0x00800080u) & 0x80008000u) >> 15; + return v & ~(nf * 0xFFFFu); +} + +// Split fp32 `x` into three exact bf16 planes `hi + mid + lo` (`Inf`/`NaN` carried in `hi` alone). +__device__ __forceinline__ void split3(float x, float& hi, float& mid, float& lo) { + hi = rbf(x); + const float r1 = __fsub_rn(x, hi); + mid = rbf(r1); + lo = rbf(__fsub_rn(r1, mid)); + if (!(fabsf(x) <= 3.0e38f)) { // Inf / NaN: carry it in hi alone (x - x would turn Inf into NaN) + hi = x; + mid = 0.0f; + lo = 0.0f; + } +} + +// Tile geometry: CTA owns `(h, [r0, r0+BN), [c0, c0+BM))`, staging `KC`-wide activation chunks in SMEM. +template +struct Cfg { + static constexpr int K = K_, MT = MT_, NT = NT_, WARPS = WARPS_, KC = KC_, PLANES = PLANES_; + static constexpr bool STREAM = STREAM_, TILED = TILED_; + static constexpr int BN = 8 * NT, CW = 16 * MT, BM = CW * WARPS, THREADS = 32 * WARPS; + static constexpr int NKC = K / KC; // activation chunks + static constexpr int SLOTS = STAGES_ < NKC ? STAGES_ : NKC; // ring slots actually used + static constexpr int STAGES = SLOTS < 2 ? 2 : STAGES_; // >= 2 for the wait arithmetic + static constexpr int CH = K / 32; // k32 blocks + static constexpr int D = D_ < CH ? D_ : CH; // weight prefetch depth (k32 blocks) + static constexpr int ROWB = KC * 2; // bytes of one activation row in a slot plane + static constexpr int PLANE = BN * ROWB; + static constexpr int SLOT = PLANES * PLANE; + static constexpr int ACT = SLOTS * SLOT; + static constexpr int EPS = CW + 4; // epilogue staging row (floats) + static constexpr int EPI = WARPS * 8 * EPS * 4; + static constexpr int SMEM = ACT + EPI; + static_assert(K % KC == 0 && KC % 64 == 0, "KC: a multiple of 64 dividing K"); + static_assert(K % 32 == 0, "K: k32 blocks"); +}; + +// Bank-conflict-free byte offset of 16-byte unit `u` in activation row `n` within a slot plane. +template +__device__ __forceinline__ int act_off(int n, int u) { + return n * C::ROWB + ((u ^ ((n & 1) << 2)) << 4); +} + +// Stage activation chunk `kc` (`[kc*KC, +KC)`) of rows `r0 .. r0 + BN - 1` (zero-padded past `R`) into `slot`. +template +__device__ __forceinline__ void stage_chunk(char* slot, int kc, int r0, int R, SRC src) { + constexpr int UPR = C::KC / 8; // 16-byte bf16 units a row + if constexpr (C::PLANES == 1) { + static_assert(sizeof(T) == 2, "single plane: bf16 activations"); + for (int e = threadIdx.x; e < C::BN * UPR; e += C::THREADS) { + const int n = e / UPR, u = e % UPR, r = r0 + n; + const bool ok = r < R; + const T* p = src(ok ? r : r0) + kc * C::KC + u * 8; + tf_common::cp16z(slot + act_off(n, u), p, ok); + } + } else { + static_assert(sizeof(T) == 4 && C::PLANES == 3, "three planes: fp32 activations split exactly"); + for (int e = threadIdx.x; e < C::BN * UPR; e += C::THREADS) { + const int n = e / UPR, u = e % UPR, r = r0 + n; + uint4 hi = make_uint4(0, 0, 0, 0), mid = hi, lo = hi; + if (r < R) { + const float* p = reinterpret_cast(src(r)) + kc * C::KC + u * 8; + const uint4 v0 = tf_common::ld_nc(reinterpret_cast(p)); + const uint4 v1 = tf_common::ld_nc(reinterpret_cast(p) + 1); + float x[8] = {__uint_as_float(v0.x), __uint_as_float(v0.y), __uint_as_float(v0.z), __uint_as_float(v0.w), + __uint_as_float(v1.x), __uint_as_float(v1.y), __uint_as_float(v1.z), __uint_as_float(v1.w)}; + float h8[8], m8[8], l8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) split3(x[i], h8[i], m8[i], l8[i]); + hi = make_uint4(pack2(h8[0], h8[1]), pack2(h8[2], h8[3]), pack2(h8[4], h8[5]), pack2(h8[6], h8[7])); + mid = make_uint4(pack2(m8[0], m8[1]), pack2(m8[2], m8[3]), pack2(m8[4], m8[5]), pack2(m8[6], m8[7])); + lo = make_uint4(pack2(l8[0], l8[1]), pack2(l8[2], l8[3]), pack2(l8[4], l8[5]), pack2(l8[6], l8[7])); + } + const int off = act_off(n, u); + *reinterpret_cast(slot + off) = hi; + *reinterpret_cast(slot + C::PLANE + off) = mid; + *reinterpret_cast(slot + 2 * C::PLANE + off) = lo; + } + } +} + +// Accumulate `W[col][k] * X[row][k]` over `K` in ascending `k32` order; `after_wait()` runs after PDL wait. +template +__device__ __forceinline__ void chain(float (&acc)[C::MT][C::NT][4], const bf16* __restrict__ W, int c0w, int r0, int R, + SRC src, char* act, HOOK after_wait) { + const int lane = threadIdx.x & 31, g = lane >> 2, q = lane & 3; + uint64_t pol = 0ull; + if constexpr (C::STREAM) pol = evict_first_policy(); + // A rows `g` and `g + 8` of each `m16` tile (`TILED`: 64 consecutive `uint4` per `k32` block). + constexpr int BSTEP = C::TILED ? 64 : 4; + const uint4* wp[C::MT][2]; +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int j = 0; j < 2; ++j) + wp[mt][j] = C::TILED ? reinterpret_cast(W + static_cast(c0w + mt * 16) * C::K) + j * 32 + lane + : reinterpret_cast(W + static_cast(c0w + mt * 16 + g + 8 * j) * C::K) + q; + + uint4 a[C::D][C::MT][2]; +#pragma unroll + for (int b = 0; b < C::D; ++b) +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int j = 0; j < 2; ++j) a[b][mt][j] = ldw(wp[mt][j] + BSTEP * b, pol); + +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int nt = 0; nt < C::NT; ++nt) +#pragma unroll + for (int i = 0; i < 4; ++i) acc[mt][nt][i] = 0.0f; + + // Wait on previous stream kernel via PDL after weight prefetches are already in flight. + qmm_frag::grid_wait(); + after_wait(); + + // activation ring prologue +#pragma unroll + for (int s = 0; s < C::STAGES - 1; ++s) { + if (s < C::NKC) stage_chunk(act + (s % C::SLOTS) * C::SLOT, s, r0, R, src); + tf_common::cp_commit(); + } + + constexpr int BPC = C::KC / 32; // k32 blocks a chunk +#pragma unroll + for (int kc = 0; kc < C::NKC; ++kc) { + tf_common::cp_wait(); + __syncthreads(); + { + const int nx = kc + C::STAGES - 1; + if (nx < C::NKC) stage_chunk(act + (nx % C::SLOTS) * C::SLOT, nx, r0, R, src); + tf_common::cp_commit(); + } + const char* slot = act + (kc % C::SLOTS) * C::SLOT; +#pragma unroll + for (int bb = 0; bb < BPC; ++bb) { + const int b = kc * BPC + bb; // global k32 block + uint4 cur[C::MT][2]; +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int j = 0; j < 2; ++j) cur[mt][j] = a[b % C::D][mt][j]; + if (b + C::D < C::CH) { +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int j = 0; j < 2; ++j) a[b % C::D][mt][j] = ldw(wp[mt][j] + BSTEP * (b + C::D), pol); + } +#pragma unroll + for (int p = 0; p < C::PLANES; ++p) { + if constexpr (C::PLANES == 3) { + if (p == 1) { +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) +#pragma unroll + for (int j = 0; j < 2; ++j) { + cur[mt][j].x = zero_nf_bf16x2(cur[mt][j].x); + cur[mt][j].y = zero_nf_bf16x2(cur[mt][j].y); + cur[mt][j].z = zero_nf_bf16x2(cur[mt][j].z); + cur[mt][j].w = zero_nf_bf16x2(cur[mt][j].w); + } + } + } +#pragma unroll + for (int nt = 0; nt < C::NT; ++nt) { + const uint4 x = + *reinterpret_cast(slot + p * C::PLANE + act_off(nt * 8 + g, bb * 4 + q)); +#pragma unroll + for (int s = 0; s < 2; ++s) +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) + mma_bf16(acc[mt][nt], word(cur[mt][0], 2 * s), word(cur[mt][1], 2 * s), + word(cur[mt][0], 2 * s + 1), word(cur[mt][1], 2 * s + 1), word(x, 2 * s), + word(x, 2 * s + 1)); + } + } + } + } + tf_common::cp_wait<0>(); + qmm_frag::grid_launch(); +} + +// Stage the warp's fp32 results of n8 tile nt as [8 rows][CW cols] (row stride EPS) in its epilogue area. +template +__device__ __forceinline__ void stage_tile(float* ep, const float (&acc)[C::MT][C::NT][4], int nt) { + const int lane = threadIdx.x & 31, g = lane >> 2, q = lane & 3; +#pragma unroll + for (int mt = 0; mt < C::MT; ++mt) { + ep[(2 * q) * C::EPS + mt * 16 + g] = acc[mt][nt][0]; + ep[(2 * q + 1) * C::EPS + mt * 16 + g] = acc[mt][nt][1]; + ep[(2 * q) * C::EPS + mt * 16 + g + 8] = acc[mt][nt][2]; + ep[(2 * q + 1) * C::EPS + mt * 16 + g + 8] = acc[mt][nt][3]; + } +} + +// GPT-J pair rotation `(q * cos) + (rotate_half(q) * sin)` matching `apply_rotary_pos_emb`. +__device__ __forceinline__ void rope_pair(float x0, float x1, float c, float s, float& y0, float& y1) { + y0 = __fadd_rn(__fmul_rn(x0, c), __fmul_rn(-x1, s)); + y1 = __fadd_rn(__fmul_rn(x1, c), __fmul_rn(x0, s)); +} + +// Absorb `QB [R, ldq]` through `W_UK_T [Hl, 512, 192]` into `QA [R, Hl, 576]` (plus optional `qlo` lo plane). +template +__device__ __forceinline__ void absorb_body(const bf16* __restrict__ QB, int ldq, int R, int Hl, + const bf16* __restrict__ WUKT, const void* __restrict__ CSv, + const int* __restrict__ CSI, void* __restrict__ QAv, long long qlo = 0) { + static_assert(C::K == ND, "absorb reduces over the 192 nope columns"); + extern __shared__ __align__(16) unsigned char smem_raw[]; + char* act = reinterpret_cast(smem_raw); + float* epi = reinterpret_cast(smem_raw + C::ACT) + (threadIdx.x >> 5) * 8 * C::EPS; + constexpr int NCB = KL / C::BM; + const int cb = blockIdx.x % NCB, hr = blockIdx.x / NCB, h = hr % Hl, rb = hr / Hl; + const int r0 = rb * C::BN, warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int c0w = cb * C::BM + warp * C::CW; + const bf16* W = WUKT + static_cast(h) * KL * ND; + auto src = [&](int r) { return QB + static_cast(r) * ldq + h * QHS; }; + + // Column block 0 writes the 64 roped columns (zeroed on both hi and lo planes when `CSv == nullptr`). + auto rope = [&]() { + // Zero both hi and lo roped planes when `CSv == nullptr` so no output bytes remain unwritten. + if (cb == 0 && CSv == nullptr && !OUT32) { + bf16* qa = reinterpret_cast(QAv); + for (int e = threadIdx.x; e < C::BN * 8; e += C::THREADS) { + const int rr = e >> 3, u = e & 7, r = r0 + rr; + if (r >= R) continue; + const size_t o = (static_cast(r) * Hl + h) * QW + KL + 8 * u; + *reinterpret_cast(qa + o) = make_uint4(0, 0, 0, 0); + if (qlo != 0) *reinterpret_cast(qa + qlo + o) = make_uint4(0, 0, 0, 0); + } + } + if (cb == 0 && CSv != nullptr) { + for (int e = threadIdx.x; e < C::BN * 8; e += C::THREADS) { + const int rr = e >> 3, u = e & 7, r = r0 + rr; + if (r >= R) continue; + const uint4 xq = ld_stream(QB + static_cast(r) * ldq + h * QHS + ND + 8 * u); + const int ci = CSI ? CSI[r] : r; + float cc[4], ss[4]; + if constexpr (CS2) { + const float2* cs2 = reinterpret_cast(CSv) + static_cast(ci) * 32 + 4 * u; + const float4 ab0 = *reinterpret_cast(cs2); + const float4 ab1 = *reinterpret_cast(cs2 + 2); + cc[0] = ab0.x; ss[0] = ab0.y; cc[1] = ab0.z; ss[1] = ab0.w; + cc[2] = ab1.x; ss[2] = ab1.y; cc[3] = ab1.z; ss[3] = ab1.w; + } else { + const float* CS = reinterpret_cast(CSv); + const float4 c4 = *reinterpret_cast(CS + static_cast(ci) * 64 + 4 * u); + const float4 s4 = *reinterpret_cast(CS + static_cast(ci) * 64 + 32 + 4 * u); + cc[0] = c4.x; cc[1] = c4.y; cc[2] = c4.z; cc[3] = c4.w; + ss[0] = s4.x; ss[1] = s4.y; ss[2] = s4.z; ss[3] = s4.w; + } + float y[8]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint32_t w = word(xq, i); + rope_pair(bf_lo(w), bf_hi(w), cc[i], ss[i], y[2 * i], y[2 * i + 1]); + } + const size_t o = (static_cast(r) * Hl + h) * QW + KL + 8 * u; + if constexpr (OUT32) { + float* d = reinterpret_cast(QAv) + o; + reinterpret_cast(d)[0] = make_float4(rbf(y[0]), rbf(y[1]), rbf(y[2]), rbf(y[3])); + reinterpret_cast(d)[1] = make_float4(rbf(y[4]), rbf(y[5]), rbf(y[6]), rbf(y[7])); + } else { + *reinterpret_cast(reinterpret_cast(QAv) + o) = + make_uint4(pack2(y[0], y[1]), pack2(y[2], y[3]), pack2(y[4], y[5]), pack2(y[6], y[7])); + } + } + } + }; + float acc[C::MT][C::NT][4]; + chain(acc, W, c0w, r0, R, src, act, rope); + + constexpr int UPR = OUT32 ? C::CW / 4 : C::CW / 8; // 16-byte output units a row of the warp's columns +#pragma unroll + for (int nt = 0; nt < C::NT; ++nt) { + if (r0 + nt * 8 >= R) break; + stage_tile(epi, acc, nt); + __syncwarp(); + for (int e = lane; e < 8 * UPR; e += 32) { + const int rr = e / UPR, u = e % UPR, r = r0 + nt * 8 + rr; + if (r >= R) continue; + const size_t o = (static_cast(r) * Hl + h) * QW + c0w; + if constexpr (OUT32) { + const float4 v = *reinterpret_cast(epi + rr * C::EPS + u * 4); + reinterpret_cast(reinterpret_cast(QAv) + o)[u] = v; + } else { + const float* s = epi + rr * C::EPS + u * 8; + const uint4 v = make_uint4(pack2(s[0], s[1]), pack2(s[2], s[3]), pack2(s[4], s[5]), pack2(s[6], s[7])); + reinterpret_cast(reinterpret_cast(QAv) + o)[u] = v; + if (qlo != 0) { // c1's exact lo plane: what each bf16 round left out, rounded + float l8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) l8[i] = __fsub_rn(s[i], rbf(s[i])); + const uint4 lo = make_uint4(pack2(l8[0], l8[1]), pack2(l8[2], l8[3]), pack2(l8[4], l8[5]), pack2(l8[6], l8[7])); + reinterpret_cast(reinterpret_cast(QAv) + qlo + o)[u] = lo; + } + } + } + __syncwarp(); + } +} + +// Expand `LAT [R, Hl, 512]` through `W_UV [Hl, 256, 512]` and apply `bf16(o * sigmoid(GATE))` into `ATT`. +template +__device__ __forceinline__ void expand_body(const LT* __restrict__ LAT, int R, int Hl, const bf16* __restrict__ WUV, + const bf16* __restrict__ GATE, int ldg, bf16* __restrict__ ATT) { + static_assert(C::K == KL, "expand reduces over the 512 latent columns"); + extern __shared__ __align__(16) unsigned char smem_raw[]; + char* act = reinterpret_cast(smem_raw); + float* epi = reinterpret_cast(smem_raw + C::ACT) + (threadIdx.x >> 5) * 8 * C::EPS; + constexpr int NCB = VD / C::BM; + const int cb = blockIdx.x % NCB, hr = blockIdx.x / NCB, h = hr % Hl, rb = hr / Hl; + const int r0 = rb * C::BN, warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int c0w = cb * C::BM + warp * C::CW; + const bf16* W = WUV + static_cast(h) * VD * KL; + auto src = [&](int r) { return LAT + (static_cast(r) * Hl + h) * KL; }; + + // Decode-sized tiles prefetch gate operands while weights stream in; larger tiles load in epilogue. + constexpr int UPR = C::CW / 8; + constexpr bool PREG = C::NT <= 2 && 8 * UPR <= 32; + uint4 gpre[PREG ? C::NT : 1]; + auto gate_prefetch = [&]() { + if constexpr (PREG) { +#pragma unroll + for (int nt = 0; nt < C::NT; ++nt) { + const int rr = lane / UPR, u = lane % UPR, r = r0 + nt * 8 + rr; + gpre[nt] = make_uint4(0, 0, 0, 0); + if (lane < 8 * UPR && r < R) gpre[nt] = ld_stream(GATE + static_cast(r) * ldg + h * VD + c0w + 8 * u); + } + } + }; + float acc[C::MT][C::NT][4]; + chain(acc, W, c0w, r0, R, src, act, gate_prefetch); + +#pragma unroll + for (int nt = 0; nt < C::NT; ++nt) { + if (r0 + nt * 8 >= R) break; + stage_tile(epi, acc, nt); + __syncwarp(); + for (int e = lane; e < 8 * UPR; e += 32) { + const int rr = e / UPR, u = e % UPR, r = r0 + nt * 8 + rr; + if (r >= R) continue; + const int col = h * VD + c0w + 8 * u; + uint4 g8; + if constexpr (PREG) g8 = gpre[nt]; + else g8 = ld_stream(GATE + static_cast(r) * ldg + col); + const float* s = epi + rr * C::EPS + u * 8; + float y[8]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint32_t w = word(g8, i); + // single rounding, as the in-tree tf_hy4_mla_value: bf16(o * sigmoid(g)) with o and sigmoid in fp32 + const float ga = __fdiv_rn(1.0f, __fadd_rn(1.0f, expf(-bf_lo(w)))); + const float gb = __fdiv_rn(1.0f, __fadd_rn(1.0f, expf(-bf_hi(w)))); + y[2 * i] = __fmul_rn(s[2 * i], ga); + y[2 * i + 1] = __fmul_rn(s[2 * i + 1], gb); + } + *reinterpret_cast(ATT + static_cast(r) * Hl * VD + col) = + make_uint4(pack2(y[0], y[1]), pack2(y[2], y[3]), pack2(y[4], y[5]), pack2(y[6], y[7])); + } + __syncwarp(); + } +} + +} // namespace hy4c2 diff --git a/zig/kernels/cuda/hy4_flash/mla_paged.cu b/zig/kernels/cuda/hy4_flash/mla_paged.cu new file mode 100644 index 00000000000..5926fa22f03 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_paged.cu @@ -0,0 +1,39 @@ +// Hy4-flash's absorbed gated MLA on CUDA (docs/recipes/hy4-flash.md, decision 1): hy4_mla.cuh's bodies as served. + +#include "mla_paged.cuh" + +// q_nope absorbed through kv_b's key rows into fp32 latent queries; grid (heads, 4, rows / 16), 128 threads. +extern "C" __global__ void __launch_bounds__(128) + tf_hy4_mla_absorb(const __nv_bfloat16* q, int64_t qs, const __nv_bfloat16* kvb, float* ql, int rows, int heads) { + tf_hy4::absorb(q, qs, kvb, ql, rows, heads); +} + +// Attention over the latent cache with sinks (window, span or list); grid (rows, heads / 8), 256 threads, kAttnSmem. +extern "C" __global__ void __launch_bounds__(256) + tf_hy4_mla_attn(const float* ql, const __nv_bfloat16* qr, const __nv_bfloat16* cache, const int* pos, + const int* idx, const float* sinks, float* ol, int heads, int window, int nidx, int ring, + float scale) { + tf_hy4::attn(ql, qr, cache, pos, idx, sinks, ol, heads, window, nidx, ring, scale); +} + +// The weighted latent through kv_b's value rows, times the sigmoid gate; grid (heads, 8, rows / 16), 128 threads. +extern "C" __global__ void __launch_bounds__(128) + tf_hy4_mla_value(const float* ol, const __nv_bfloat16* kvb, const __nv_bfloat16* gate, int64_t gs, + __nv_bfloat16* out, int64_t os, int rows, int heads) { + tf_hy4::value(ol, kvb, gate, gs, out, os, rows, heads); +} + +// The ranks' o_proj partials summed (the all-reduce seam), rounded to bf16, then post_proj_norm; a row a block of 256. +extern "C" __global__ void __launch_bounds__(256) + tf_hy4_mla_post(const float* parts, int64_t plane, int world, const __nv_bfloat16* w, __nv_bfloat16* out, + int width, float eps) { + tf_hy4::post(parts, plane, world, w, out, width, eps); +} + +// tf_hy4_mla_attn with row r's own cache at caches[r] (batched decode); grid (rows, heads / 8), 256 threads, kAttnSmem. +extern "C" __global__ void __launch_bounds__(256) + tf_hy4_mla_attn_rows(const float* ql, const __nv_bfloat16* qr, const unsigned long long* caches, const int* pos, + const int* idx, const float* sinks, float* ol, int heads, int window, int nidx, int ring, + float scale) { + tf_hy4::attn_rows(ql, qr, caches, pos, idx, sinks, ol, heads, window, nidx, ring, scale); +} diff --git a/zig/kernels/cuda/hy4_flash/mla_paged.cuh b/zig/kernels/cuda/hy4_flash/mla_paged.cuh new file mode 100644 index 00000000000..1b277e79e40 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_paged.cuh @@ -0,0 +1,304 @@ +// Hy4-flash's absorbed gated MLA (docs/recipes/hy4-flash.md): device bodies templated on Fault (kNone as served). +#pragma once + +#include +#include +#include +#include + +#include "../common/reduce.cuh" + +namespace tf_hy4 { + +// Planted faults a gate must catch: NaN read as 0, mutating an input, dropping the last term, or fp16 running sums. +enum Fault { kNone = 0, kBadNan = 1, kBadRepeat = 2, kBadTail = 3, kBadSums = 4 }; + +constexpr int kLat = 512; // the normed latent +constexpr int kRope = 64; // the roped columns a q head and the shared key carry +constexpr int kRow = 576; // a cache row: the latent, then the roped key +constexpr int kNope = 192; // nope columns a q head +constexpr int kQ = 256; // a q_b head: nope, then rope +constexpr int kV = 256; // value columns a head +constexpr int kKv = 448; // a kv_b head: its 192 key rows, then its 256 value rows + +constexpr int kHB = 8; // heads an attention block takes, one warp a head in the scores +constexpr int kKC = 32; // keys an attention chunk holds, one lane a key in the scores +constexpr int kKs = kRow + 2; // a key's shared row, padded so lanes reading different keys use different banks + +// The attention's dynamic shared bytes: q (fp32), the chunk's keys, weights, key positions, then m, l and the rescale. +constexpr int kAttnSmem = kHB * kRow * 4 + kKC * kKs * 2 + kHB * kKC * 4 + kKC * 4 + 3 * kHB * 4; + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } + +// One fma step of a sum, rounded once in fp32 (kBadSums: the running sum rounded to fp16 at every step). +template +__device__ __forceinline__ float step(float a, float b, float acc) { + const float s = __fmaf_rn(a, b, acc); + return F == kBadSums ? __half2float(__float2half_rn(s)) : s; +} + +template +__device__ __forceinline__ float add(float a, float b) { + const float s = __fadd_rn(a, b); + return F == kBadSums ? __half2float(__float2half_rn(s)) : s; +} + +template +__device__ __forceinline__ float load(float v) { + return (F == kBadNan && v != v) ? 0.0f : v; +} + +// kBadRepeat: one thread bumps the first element of an input by one unit in its last place on every run. +template +__device__ __forceinline__ void bump(const T* p) { + if (F != kBadRepeat || blockIdx.x != 0 || blockIdx.y != 0 || blockIdx.z != 0 || threadIdx.x != 0) return; + if (sizeof(T) == 2) { + unsigned short* w = (unsigned short*)p; + *w = (unsigned short)(*w + 1); + } else { + unsigned* w = (unsigned*)p; + *w = *w + 1; + } +} + +// A max that keeps a NaN, as float64 arithmetic on the formula does (kBadNan: fmaxf, which drops it). +template +__device__ __forceinline__ float pick(float a, float b) { + if (F == kBadNan) return fmaxf(a, b); + return (a != a || b != b) ? CUDART_NAN_F : fmaxf(a, b); +} + +// ql [rows][heads][512] fp32 = q_nope . wk (kv_b[h][0..192][c], fp32 fma chain); block (head, 128 cols, 16 rows). +template +__device__ __forceinline__ void absorb(const __nv_bfloat16* __restrict__ q, int64_t qs, + const __nv_bfloat16* __restrict__ kvb, float* __restrict__ ql, int rows, + int heads) { + constexpr int RB = 16; + __shared__ float qn[RB][kNope]; + const int h = blockIdx.x, c = blockIdx.y * 128 + threadIdx.x, r0 = blockIdx.z * RB; + const int nr = min(RB, rows - r0); + bump(q); + for (int i = threadIdx.x; i < RB * kNope; i += 128) { + const int r = i / kNope, d = i % kNope; + qn[r][d] = r < nr ? load(bf(q[(int64_t)(r0 + r) * qs + (int64_t)h * kQ + d])) : 0.0f; + } + __syncthreads(); + const __nv_bfloat16* w = kvb + (int64_t)h * kKv * kLat + c; + float acc[RB]; +#pragma unroll + for (int r = 0; r < RB; ++r) acc[r] = 0.0f; + const int nd = F == kBadTail ? kNope - 1 : kNope; + for (int d = 0; d < nd; ++d) { + const float wv = bf(w[(int64_t)d * kLat]); +#pragma unroll + for (int r = 0; r < RB; ++r) acc[r] = step(qn[r][d], wv, acc[r]); + } +#pragma unroll + for (int r = 0; r < RB; ++r) + if (r < nr) ql[((int64_t)(r0 + r) * heads + h) * kLat + c] = acc[r]; +} + +// Key j of row t's walk: its window or causal span from lo, or its list (an entry < 0 or past t is masked); -1 masked. +__device__ __forceinline__ int key_at(int j, int n, int t, int lo, const int* list) { + if (j >= n) return -1; + const int p = list ? list[j] : lo + j; + return (p >= 0 && p <= t) ? p : -1; +} + +// ol [rows][heads][512] fp32: sinked online softmax over 32-key chunks (window, causal span or nidx list; p % ring). +template +__device__ __forceinline__ void attn(const float* __restrict__ ql, const __nv_bfloat16* __restrict__ qr, + const __nv_bfloat16* __restrict__ cache, const int* __restrict__ pos, + const int* __restrict__ idx, const float* __restrict__ sinks, + float* __restrict__ ol, int heads, int window, int nidx, int ring, float scale) { + extern __shared__ __align__(16) unsigned char smem[]; + float* qs = (float*)smem; + __nv_bfloat16* ks = (__nv_bfloat16*)(qs + kHB * kRow); + float* ps = (float*)(ks + kKC * kKs); + int* kp = (int*)(ps + kHB * kKC); + float* alpha = (float*)(kp + kKC); + float* ls = alpha + kHB; + float* ms = ls + kHB; + const int r = blockIdx.x, h0 = blockIdx.y * kHB; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + bump(ql); + const int t = pos[r]; + const int lo = window > 0 ? max(0, t - window + 1) : 0; + const int n = nidx > 0 ? nidx : t - lo + 1; + const int* list = nidx > 0 ? idx + (int64_t)r * nidx : nullptr; + for (int i = tid; i < kHB * kRow; i += 256) { + const int hh = i / kRow, c = i % kRow; + const int64_t at = (int64_t)r * heads + h0 + hh; + qs[i] = load(c < kLat ? ql[at * kLat + c] : bf(qr[at * kRope + c - kLat])); + } + if (tid < kHB) { + ms[tid] = sinks[h0 + tid]; + ls[tid] = 1.0f; + } + int last = -1; // kBadTail: the walk's last visible key is left out + if (F == kBadTail) + for (int j = n - 1; j >= 0 && last < 0; --j) + if (key_at(j, n, t, lo, list) >= 0) last = j; + float acc[kHB][2]; +#pragma unroll + for (int hh = 0; hh < kHB; ++hh) acc[hh][0] = acc[hh][1] = 0.0f; + __syncthreads(); + for (int base = 0; base < n; base += kKC) { + if (tid < kKC) kp[tid] = (F == kBadTail && base + tid == last) ? -1 : key_at(base + tid, n, t, lo, list); + __syncthreads(); + for (int i = tid; i < kKC * (kRow / 2); i += 256) { + const int j = i / (kRow / 2), w2 = i % (kRow / 2), p = kp[j]; + __nv_bfloat162 v = __float2bfloat162_rn(0.0f); + if (p >= 0) v = ((const __nv_bfloat162*)(cache + (int64_t)(ring > 0 ? p % ring : p) * kRow))[w2]; + ((__nv_bfloat162*)(ks + j * kKs))[w2] = v; + } + __syncthreads(); + { + const float* q = qs + warp * kRow; + const __nv_bfloat162* k = (const __nv_bfloat162*)(ks + lane * kKs); + float s = 0.0f; + for (int c2 = 0; c2 < kRow / 2; ++c2) { + const float2 kv = __bfloat1622float2(k[c2]); + s = step(q[2 * c2], kv.x, s); + s = step(q[2 * c2 + 1], kv.y, s); + } + s = __fmul_rn(s, scale); + const bool ok = kp[lane] >= 0 && (F != kBadNan || s == s); + float cm = ok ? s : -CUDART_INF_F; +#pragma unroll + for (int off = 16; off > 0; off >>= 1) cm = pick(cm, __shfl_xor_sync(0xffffffffu, cm, off)); + const float m = ms[warp]; + const float mn = pick(m, cm); + const float a = expf(__fsub_rn(m, mn)); + const float p = ok ? expf(__fsub_rn(s, mn)) : 0.0f; + float sum = p; // a fixed tree into lane 0 +#pragma unroll + for (int off = 16; off > 0; off >>= 1) sum = __fadd_rn(sum, __shfl_down_sync(0xffffffffu, sum, off)); + ps[warp * kKC + lane] = p; + if (lane == 0) { + ms[warp] = mn; + ls[warp] = __fadd_rn(__fmul_rn(ls[warp], a), sum); + alpha[warp] = a; + } + } + __syncthreads(); +#pragma unroll + for (int hh = 0; hh < kHB; ++hh) { // thread tid holds latent columns 2 tid and 2 tid + 1 of every head + const float a = alpha[hh]; + float x0 = __fmul_rn(acc[hh][0], a), x1 = __fmul_rn(acc[hh][1], a); + for (int j = 0; j < kKC; ++j) { + const float p = ps[hh * kKC + j]; + const float2 kv = __bfloat1622float2(((const __nv_bfloat162*)(ks + j * kKs))[tid]); + x0 = step(p, kv.x, x0); + x1 = step(p, kv.y, x1); + } + acc[hh][0] = x0; + acc[hh][1] = x1; + } + __syncthreads(); + } +#pragma unroll + for (int hh = 0; hh < kHB; ++hh) { + const float l = ls[hh]; + float2 o; + o.x = __fdiv_rn(acc[hh][0], l); + o.y = __fdiv_rn(acc[hh][1], l); + ((float2*)(ol + ((int64_t)r * heads + h0 + hh) * kLat))[tid] = o; + } +} + +// out [rows][heads * 256] bf16 = (ol . wv) * sigmoid(gate), fp32 fma over latent; block (head, 32 values, 16 rows). +template +__device__ __forceinline__ void value(const float* __restrict__ ol, const __nv_bfloat16* __restrict__ kvb, + const __nv_bfloat16* __restrict__ gate, int64_t gs, __nv_bfloat16* __restrict__ out, + int64_t os, int rows, int heads) { + constexpr int RB = 16, VB = 32, CB = 64; + __shared__ float lat[RB][CB]; + __shared__ __nv_bfloat16 ws[VB][CB + 2]; + const int h = blockIdx.x, v0 = blockIdx.y * VB, r0 = blockIdx.z * RB; + const int tid = threadIdx.x, v = tid & 31, rg = tid >> 5; + bump(ol); + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + const int nc = F == kBadTail ? kLat - 1 : kLat; + for (int c0 = 0; c0 < kLat; c0 += CB) { + for (int i = tid; i < RB * CB; i += 128) { + const int rr = i / CB, c = i % CB; + lat[rr][c] = r0 + rr < rows ? load(ol[((int64_t)(r0 + rr) * heads + h) * kLat + c0 + c]) : 0.0f; + } + for (int i = tid; i < VB * CB; i += 128) { + const int vv = i / CB, c = i % CB; + ws[vv][c] = kvb[((int64_t)h * kKv + kNope + v0 + vv) * kLat + c0 + c]; + } + __syncthreads(); + for (int c = 0; c < CB && c0 + c < nc; ++c) { + const float w = bf(ws[v][c]); +#pragma unroll + for (int k = 0; k < 4; ++k) acc[k] = step(lat[rg * 4 + k][c], w, acc[k]); + } + __syncthreads(); + } +#pragma unroll + for (int k = 0; k < 4; ++k) { + const int r = r0 + rg * 4 + k; + if (r >= rows) continue; + const int64_t col = (int64_t)h * kV + v0 + v; + const float g = bf(gate[r * gs + col]); + const float sg = __fdiv_rn(1.0f, __fadd_rn(1.0f, expf(-g))); + out[r * os + col] = __float2bfloat16_rn(__fmul_rn(acc[k], sg)); + } +} + +// out [rows][width] bf16: x = bf16(rank-ordered sum of world planes), then post_proj_norm(x, w); 256 threads/row. +template +__device__ __forceinline__ void post(const float* __restrict__ parts, int64_t plane, int world, + const __nv_bfloat16* __restrict__ w, __nv_bfloat16* __restrict__ out, int width, + float eps) { + constexpr int T = 256, MOST = 16; + __shared__ float red[T / 32]; + const int r = blockIdx.x, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + bump(parts); + const int n = F == kBadTail ? width - 1 : width; + float x[MOST]; + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < MOST; ++k) { + const int i = tid + k * T; + x[k] = 0.0f; + if (i >= n) continue; + const float* p = parts + (int64_t)r * width + i; + float s = load(p[0]); + for (int q = 1; q < world; ++q) s = __fadd_rn(s, load(p[q * plane])); + x[k] = bf(__float2bfloat16_rn(s)); + ss = step(x[k], x[k], ss); + } +#pragma unroll + for (int off = 16; off > 0; off >>= 1) ss = add(ss, __shfl_down_sync(0xffffffffu, ss, off)); + if (lane == 0) red[warp] = ss; + __syncthreads(); + if (warp == 0) { + float v = lane < T / 32 ? red[lane] : 0.0f; +#pragma unroll + for (int off = 4; off > 0; off >>= 1) v = add(v, __shfl_down_sync(0xffffffffu, v, off)); + if (lane == 0) red[0] = v; + } + __syncthreads(); + const float inv = tf_common::rms_scale(red[0], width, eps); +#pragma unroll + for (int k = 0; k < MOST; ++k) { + const int i = tid + k * T; + if (i < width) out[(int64_t)r * width + i] = __float2bfloat16_rn(__fmul_rn(__fmul_rn(x[k], inv), bf(w[i]))); + } +} + +// attn over a batched round's sequences: row r reads its own latent cache at caches[r] (a device address). +template +__device__ __forceinline__ void attn_rows(const float* __restrict__ ql, const __nv_bfloat16* __restrict__ qr, + const unsigned long long* __restrict__ caches, const int* __restrict__ pos, + const int* __restrict__ idx, const float* __restrict__ sinks, + float* __restrict__ ol, int heads, int window, int nidx, int ring, + float scale) { + const __nv_bfloat16* cache = reinterpret_cast(caches[blockIdx.x]); + attn(ql, qr, cache, pos, idx, sinks, ol, heads, window, nidx, ring, scale); +} + +} // namespace tf_hy4 diff --git a/zig/lfm2_recording_metal.zig b/zig/lfm2_recording_metal.zig index 044112e5a88..819d851b66a 100644 --- a/zig/lfm2_recording_metal.zig +++ b/zig/lfm2_recording_metal.zig @@ -1,7 +1,19 @@ //! A recording loader has no device constructor, compiler, buffers, queue or dispatch implementation. const std = @import("std"); const real = @import("real_metal"); -pub const CompileOptions = real.CompileOptions; +pub const CompileOptions = struct { + math_mode: real.types.MathMode = .safe, + math_functions: real.types.MathFunctions = .fast, + language: usize = real.types.languageVersion(4, 0), + pub fn mlx() CompileOptions { + if (@import("builtin").target.os.tag != .macos) return .{}; + const options = real.CompileOptions.mlx(); + return .{ .math_mode = options.math_mode, .math_functions = options.math_functions, .language = options.language }; + } +}; +pub fn mlx() CompileOptions { + return CompileOptions.mlx(); +} pub const Buffer = real.Buffer; pub const ComputeEncoder = real.ComputeEncoder; pub const Queue = real.Queue; diff --git a/zig/lfm2_runtime_sources_host.zig b/zig/lfm2_runtime_sources_host.zig index 6211299623e..e5e9eab1349 100644 --- a/zig/lfm2_runtime_sources_host.zig +++ b/zig/lfm2_runtime_sources_host.zig @@ -5,6 +5,10 @@ const kernels = @import("src/families/lfm2_moe/kernels.zig"); const inventory = @import("runtime_sources/lfm2.zig"); const Set = @import("runtime_sources/set.zig").Set; +test { + if (@import("builtin").target.os.tag != .macos) _ = @import("runtime_sources/objc_stubs.zig"); +} + test "LFM2 runtime inventory: library bytes and options match the real loader on M1 through M5" { for ([_]u32{ 13, 14, 15, 16, 17 }) |generation| { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); diff --git a/zig/metal_runtime_inventory.zig b/zig/metal_runtime_inventory.zig index bb45f0fe19c..ef4de158994 100644 --- a/zig/metal_runtime_inventory.zig +++ b/zig/metal_runtime_inventory.zig @@ -8,4 +8,7 @@ pub const weight_only = engine.weight_only; test { _ = @import("runtime_sources/modes_test.zig"); + _ = @import("runtime_sources/registry_test.zig"); + _ = @import("runtime_sources/coverage_test.zig"); + if (@import("builtin").target.os.tag != .macos) _ = @import("runtime_sources/objc_stubs.zig"); } diff --git a/zig/metal_runtime_sources_test.zig b/zig/metal_runtime_sources_test.zig index b6832e96eca..3e9af2f5463 100644 --- a/zig/metal_runtime_sources_test.zig +++ b/zig/metal_runtime_sources_test.zig @@ -38,6 +38,18 @@ test "Metal runtime source compile gate: every family" { }; library.deinit(); } + const planted_control = + "#include \n" ++ + "[[max_total_threads_per_threadgroup(32)]]\n" ++ + "[[max_total_threads_per_threadgroup(32)]]\n" ++ + "kernel void tf_metal_runtime_compile_planted() {}\n"; + if (mtl.Library.fromSourceNoLog(device, planted_control, mtl.CompileOptions.mlx())) |library| { + library.deinit(); + failed += 1; + std.debug.print("FAIL Metal runtime source planted control: compiler accepted duplicate attributes\n", .{}); + } else |err| { + std.debug.print("PASS Metal runtime source planted control: {t}\n", .{err}); + } std.debug.print("SUMMARY Metal runtime sources: {d} attempted, {d} failed, {d} prebuilt-fallback libraries\n", .{ checked, failed, prebuilt }); if (checked == 0) return error.NoRuntimeSourceCases; if (failed != 0) return error.MetalRuntimeSourcesFailed; diff --git a/zig/runtime_sources/assembly_metal.zig b/zig/runtime_sources/assembly_metal.zig index d027b1c09b0..23908665397 100644 --- a/zig/runtime_sources/assembly_metal.zig +++ b/zig/runtime_sources/assembly_metal.zig @@ -3,6 +3,7 @@ const real = @import("real_metal"); pub const Device = struct { units: bool, gen: u32, + os_major: ?u32 = null, // simulated macOS major for inventory tests; null preserves legacy assembly behavior pub fn tensorUnits(d: Device) bool { return d.units; } @@ -20,6 +21,10 @@ pub const Buffer = real.Buffer; pub const MappedFile = real.MappedFile; pub const Library = real.Library; pub const CompileOptions = real.CompileOptions; +pub fn mlx() CompileOptions { + if (@import("builtin").target.os.tag == .macos) return real.CompileOptions.mlx(); + return .{ .language = real.types.languageVersion(4, 0) }; +} pub const Pipeline = real.Pipeline; pub const Queue = real.Queue; pub const CommandBuffer = real.CommandBuffer; diff --git a/zig/runtime_sources/catalogs.zig b/zig/runtime_sources/catalogs.zig index d96299ecee5..897867b35e5 100644 --- a/zig/runtime_sources/catalogs.zig +++ b/zig/runtime_sources/catalogs.zig @@ -1,6 +1,7 @@ //! Canonical runtime catalogs and complete literal source sets. const std = @import("std"); const ks = @import("kernel_sources"); +const mtl = @import("metal"); const Set = @import("set.zig").Set; const nk = @import("../src/families/nemotron/kernels.zig"); @@ -27,10 +28,10 @@ pub fn add(s: *Set, device: @import("metal").Device) !void { try s.fragments("nemotron-paged", "prompt", ks.nemotron_paged.prefill); for (ks.qwen35.all) |k| try s.raw("qwen35", k.key, k.source); try s.raw("qwen35", "layout", ks.qwen35_layout); - try s.raw("qwen35", "paged", ks.qwen35_paged); + try s.rawFrom("qwen35", "paged", &.{ ks.qwen35_layout, ks.kv_pages, ks.qwen35_paged }, ks.qwen35_paged); inline for (.{ "nemotron_glue", "nemotron_experts", "nemotron_round", "nemotron_head", "nemotron_sample", "train", "train_mixers" }) |name| try s.raw("nemotron", name, @field(ks, name)); - try s.raw("nemotron", "tree", if (s.units) ks.nemotron_tree else "#define TF_SIMD_LAYOUT 1\n" ++ ks.nemotron_tree); + try s.rawFrom("nemotron", "tree", &.{ks.nemotron_tree}, if (s.units) ks.nemotron_tree else "#define TF_SIMD_LAYOUT 1\n" ++ ks.nemotron_tree); inline for (.{ "glm_dsa_mla", "glm_dsa_index", "glm_dsa_glue", "glm_dsa_moe_jobs", "glm_ep" }) |name| try s.raw("glm-dsa", name, @field(ks, name)); inline for (.{ "glm_vision", "core_qwen_vision", "qwen_image", "step5_vision" }) |name| @@ -40,10 +41,29 @@ pub fn add(s: *Set, device: @import("metal").Device) !void { try s.fragments("vision-image", "moss_image_decoder", ks.moss_image_decoder); } try @import("lfm2.zig").add(s, device); - try s.raw("lfm3", "base-attention", ks.lfm3 ++ "\n" ++ ks.lfm3_attention); + try s.rawFrom("lfm3", "base-attention", &.{ ks.lfm3, ks.lfm3_attention }, ks.lfm3 ++ "\n" ++ ks.lfm3_attention); try s.raw("lfm3", "image", ks.lfm3_image_rows); - try s.raw("lfm3", "row-projection", try @import("../src/families/lfm3/row_projection.zig").source(s.a)); - try s.raw("lfm3", "dual-projection", try @import("../src/families/lfm3/dual_projection.zig").source(s.a)); + try s.rawFrom("lfm3", "row-projection", &.{ ks.core_row_projection, ks.lfm3_projection }, try @import("../src/families/lfm3/row_projection.zig").source(s.a)); + try s.rawFrom("lfm3", "dual-projection", &.{ ks.core_row_projection, ks.lfm3_projection_dual }, try @import("../src/families/lfm3/dual_projection.zig").source(s.a)); const h3 = @import("../src/families/h3/source.zig"); - if (h3.available(device)) try s.raw("h3", "rows-route-attention", try h3.library(s.a, 56, 18432, 288, "")); + if (h3.available(device)) { + const kernels = @import("h3_kernels"); + try s.rawFrom("h3", "rows-route-attention", &.{ gemmSource(), kernels.source, kernels.gemm_source, ks.nax }, try h3.library(s.a, 56, 18432, 288, "")); + } + + try s.raw("hy4-flash", "elementwise", ks.elementwise); + var precise = mtl.mlx(); + precise.math_functions = .precise; + try s.add("h3-image", "encoder", @import("../kernels/metal/h3/image_encoder.zig").source, precise); + try s.raw("h3-image", "prompt", @import("../kernels/metal/h3/prompt_kernels.zig").source); + try s.raw("h3-image", "decoder", @import("../kernels/metal/h3/image_decoder.zig").source); + const ling = @import("../kernels/metal/ling/sources.zig"); + try s.raw("ling", "route", ling.route); + try s.raw("ling", "mla", ling.mla); + try s.raw("ling", "lfm3", ks.lfm3); +} + +fn gemmSource() []const u8 { + inline for (ks.prefill) |f| if (comptime std.mem.eql(u8, f.name, "gemm_nax")) return f.text; + @compileError("no gemm_nax source"); } diff --git a/zig/runtime_sources/completion.zig b/zig/runtime_sources/completion.zig new file mode 100644 index 00000000000..b53232449db --- /dev/null +++ b/zig/runtime_sources/completion.zig @@ -0,0 +1,177 @@ +//! Production libraries whose loaders assemble sources outside the main family catalogs. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const Set = @import("set.zig").Set; + +fn precise() mtl.CompileOptions { + return .{ .language = mtl.mlx().language, .math_functions = .precise }; +} + +pub fn add(s: *Set, device: mtl.Device) !void { + try direct(s); + try deepseek(s); + try hy4(s, device); + try flashnext(s); + try vision(s); + try ricursive(s); + try flint(s); + try glm(s); + try inkling2(s); +} + +fn direct(s: *Set) !void { + try s.raw("core", "core_exl3_rows", ks.core_exl3_rows); + inline for (.{ + "hy4_flash_indexpool", + "hy4_flash_index_recall", + "hy4_flash_index_build", + "hy4_flash_attention_sink", + "hy4_flash_mla_project", + "hy4_flash_mla_attention", + "hy4_flash_ihc", + "hy4_flash_engram", + "hy4_flash_affine_experts", + "hy4_flash_tensor_dispatch", + }) |name| try s.raw("hy4-flash", name, @field(ks, name)); + try s.raw("lfm3", "lfm3_vision", ks.lfm3_vision); + try s.raw("uocr", "uocr", ks.uocr); + try s.raw("uocr", "uocr_decoder", ks.uocr_decoder); + try s.add("qwen3", "qwen3_heads", ks.qwen3_heads, precise()); + inline for (.{ "glm_draft_topk", "glm_draft_accept", "glm_draft_follow", "glm_dflash_opt" }) |name| + try s.raw("glm-dflash2", name, @field(ks, name)); +} + +fn deepseek(s: *Set) !void { + try s.raw("deepseek-v41", "mv_mma", ks.dsv41.mv_mma); + try s.raw("deepseek-v41", "vision", ks.dsv41.vision); + try s.rawFrom("deepseek-v41", "experts_exl3", &.{ ks.core_exl3_projection, ks.dsv41.experts_exl3 }, @import("../src/families/deepseek_v41/metal/experts_exl3.zig").text); + try s.rawFrom("deepseek-v41", "early", &.{ ks.dsv41.keyed, ks.dsv41.early }, ks.dsv41.keyed ++ ks.dsv41.early); + try s.rawFrom("deepseek-v41", "markov", &.{ ks.dsv41.keyed, ks.dsv41.markov }, ks.dsv41.keyed ++ ks.dsv41.markov); +} + +fn hy4(s: *Set, device: mtl.Device) !void { + try s.fragments("hy4-flash", "hy4_flash_mla_nax", ks.hy4_flash_mla_nax); + try s.rawFrom("hy4-flash", "rows", &.{ ks.core_row_projection, ks.hy4_flash_rows }, try std.mem.concat(s.a, u8, &.{ + @import("../src/core/row_projection.zig").source(true), + ks.hy4_flash_rows, + })); + + const contracts = @import("../src/families/hy4_flash/contract_exports.zig"); + const parsed = try @import("../src/families/hy4_flash/config.zig").parse(s.a, contracts.config_json); + defer parsed.deinit(); + const t = parsed.value.text_config; + const routed = @import("../src/families/hy4_flash/metal_routed.zig"); + const route = @import("../src/core/moe_route.zig"); + const core = try route.source(s.a, .{ + .hidden = t.hidden_size, + .experts = t.n_routed_experts, + .topk = t.num_experts_per_tok, + .max_rows = routed.max_rows, + }); + try s.rawFrom("hy4-flash", "route-rows", &.{ ks.core_moe_route, ks.hy4_flash_route_rows }, try std.mem.concat(s.a, u8, &.{ core, ks.hy4_flash_route_rows })); + for ([_]u8{ 4, 8 }) |bits| + try s.rawFrom("hy4-flash", try std.fmt.allocPrint(s.a, "tensor-experts-b{d}", .{bits}), &.{ ks.core_affine_mm, ks.core_affine_nonfinite, ks.nax }, try @import("../src/core/affine_mm.zig").source(device, s.a, .{ + .bits = bits, + .group = 64, + .out_f32 = true, + .glu = .clipped_silu, + .mapped_experts = true, + })); +} + +fn flashnext(s: *Set) !void { + try s.rawFrom("flashnext", "tfq3", &.{ ks.flashnext_tfq3.common, ks.flashnext_tfq3.moe_mv, ks.flashnext_tfq3.moe_decode, ks.flashnext_tfq3.prefill, ks.nax }, try @import("../src/families/flashnext/tfq3.zig").buildSource(s.a, s.units)); + const vision_contract = @import("../src/families/flashnext/vision_contract.zig"); + for ([_]vision_contract.Which{ .mrope, .target, .pooled, .absolute, .positioned }) |which| + try s.rawFrom("flashnext-probe", @tagName(which), &.{ks.flashnext_rotary_sweep}, try std.mem.concat(s.a, u8, &.{ vision_contract.source(which), "\n", ks.flashnext_rotary_sweep })); +} + +fn vision(s: *Set) !void { + try s.fragments("idol", "idol", ks.idol); + try s.fragments("idol", "idol_dino", ks.idol_dino); + try s.fragments("idol", "idol_decoder", ks.idol_decoder); + try s.raw("idol", "idol_vae", ks.idol_vae); + try s.raw("idol", "idol_birefnet", ks.idol_birefnet); + try s.fragments("moss-image", "moss_image", ks.moss_image); + try s.fragments("moss-image", "moss_image_decoder", ks.moss_image_decoder); +} + +fn ricursive(s: *Set) !void { + const contracts = @import("../src/families/ricursive/contracts.zig"); + const model = @import("../src/families/ricursive/model.zig"); + try s.addFrom("ricursive", "ricursive_glue", &.{ks.ricursive_glue}, try contracts.glueSource(s.a), precise()); + try s.addFrom("ricursive", "llama_glue", &.{ks.llama_glue}, try model.glueSource(s.a, "#define LL_DH {d}\n{s}", ks.llama_glue), precise()); + const head = try contracts.attentionHeader(s.a); + try s.fragmentsFrom("ricursive", "attention", &.{ks.ricursive_attention_nax}, try std.mem.concat(s.a, u8, &.{ head, ks.ricursive_attention_nax })); + try s.add("ricursive", "ricursive_fp4", ks.ricursive_fp4, precise()); + try s.fragments("ricursive", "ricursive_fp4_gemm", ks.ricursive_fp4_gemm); + try s.add("ricursive", "ricursive_dflash2", ks.ricursive_dflash2, precise()); +} + +fn flint(s: *Set) !void { + const config = @import("../src/families/flint/config.zig"); + const state = @import("../src/families/flint/state.zig"); + const c: config.Config = .{}; + try s.add("flint", "flint_glue", ks.flint_glue, precise()); + try s.addFrom("flint", "route", &.{ks.core_moe_route}, try @import("../src/core/moe_route.zig").source(s.a, .{ + .hidden = c.hidden, + .experts = c.experts, + .topk = c.topk, + .round_logits = true, + }), precise()); + for ([_]bool{ true, false }) |sliding| { + const head = try std.fmt.allocPrint(s.a, "#define DH {d}\n#define NQ {d}\n#define G {d}\n#define KVH {d}\n#define WINDOW {d}\n#define RING {d}\n#define SCALE {e}f\n", .{ + c.head_dim, + c.heads, + c.heads / c.kv_heads, + c.kv_heads, + if (sliding) c.window else 0, + if (sliding) state.slidingRing(&c) else 0, + 1.0 / @sqrt(@as(f64, @floatFromInt(c.head_dim))), + }); + try s.fragmentsFrom("flint", if (sliding) "attention-sliding" else "attention-full", &.{ks.flint_attention_nax}, try std.mem.concat(s.a, u8, &.{ head, ks.flint_attention_nax })); + } + for (ks.nemotron.all) |kernel| if (std.mem.eql(u8, kernel.key, "sample")) { + const vocab = try std.fmt.allocPrint(s.a, "constexpr int V = {d};", .{c.vocab}); + try s.rawFrom("flint", "sampler", &.{kernel.source}, try std.mem.replaceOwned(u8, s.a, kernel.source, "constexpr int V = 131072;", vocab)); + break; + }; + try s.rawFrom("flint", "row-projection", &.{ks.core_row_projection}, @import("../src/core/row_projection.zig").source(s.units)); +} + +fn glm(s: *Set) !void { + const stock = @import("../src/families/glm/metal_dflash_config.zig").stock; + const attention = try @import("../src/families/glm/metal_dflash_attention.zig").source(s.a, .{ + .heads = stock.heads, + .kv_heads = stock.kv_heads, + .dim = stock.head_dim, + }); + try s.addFrom("glm-dflash2", "glm_draft_attention", &.{ks.glm_draft_attention}, attention, precise()); + const wide = @import("../src/families/glm/wide.zig"); + try s.rawFrom("glm", "tfq3", &.{ ks.glm_tfq3.header, ks.glm_glue, ks.glm_tfq3.common, ks.glm_tfq3.moe_mv, ks.glm_tfq3.moe_decode, ks.glm_tfq3.dense_decode, ks.glm_tfq3.prefill, ks.nax }, try @import("../src/families/glm/tfq3.zig").buildSource(s.a, s.units, wide.glue_math)); + const m3_def = if (s.units) "" else "#define TF_GLM_M3_FAST 1\n"; + const kda = comptime @import("../src/families/glm/kernels.zig").generatedSource("kda_rows"); + try s.rawFrom("glm", "tfq3-kda-q8", &.{ kda, ks.glm_kda_prompt, ks.glm_kda_window, ks.glm_kda_parts, ks.glm_tfq3.kda_q8 }, try std.mem.concat(s.a, u8, &.{ + kda, + m3_def, + ks.glm_kda_prompt, + ks.glm_kda_window, + ks.glm_kda_parts, + ks.glm_tfq3.kda_q8, + })); +} + +fn inkling2(s: *Set) !void { + const src = @import("inkling2_metal"); + try s.raw("inkling2", "attention", src.attention); + try s.raw("inkling2", if (s.units) "prompt_attention" else "prompt_attention_pre_m5", if (s.units) src.prompt_attention else src.prompt_attention_pre_m5); + try s.raw("inkling2", if (s.units) "dense_tiled" else "dense_mma", if (s.units) src.dense_tiled else src.dense_mma); + inline for (.{ "experts", "experts_mma", "loop", "loop_mma", "tree", "runtime", "sample" }) |name| + try s.raw("inkling2", name, @field(src, name)); + try s.rawFrom("inkling2", "glue", &.{ ks.inkling2_glue, src.glue }, src.glue); + try s.raw("inkling2", "tfq3", ks.inkling2_tfq3); + try s.fragments("inkling2", "vision", src.vision); + try s.add("inkling2", "inkling2_dflash2", src.inkling2_dflash2, precise()); + try s.raw("inkling2", if (s.units) "inkling2_dspark" else "inkling2_dspark_pre_m5", if (s.units) src.inkling2_dspark else src.inkling2_dspark_pre_m5); +} diff --git a/zig/runtime_sources/core.zig b/zig/runtime_sources/core.zig index 6472609c1bc..0d791d143b7 100644 --- a/zig/runtime_sources/core.zig +++ b/zig/runtime_sources/core.zig @@ -9,13 +9,19 @@ pub fn add(s: *Set, device: mtl.Device) !void { inline for (.{ "core_row_projection", "core_exl3_projection", "core_exlr8_projection", "core_exlr8_dense", "core_pair", "core_pair_rows", "core_lane_order", "core_deltanet", "core_simd_qmm", "core_simd_qmm_bits", "core_grammar_mask" }) |name| try s.raw("core", name, @field(ks, name)); try s.fragments("core", "binned-projection", ks.core_binned_projection); + const weight_only = @import("../src/core/weight_only_metal_impl.zig").Adapter(@import("../src/core/weight_only.zig"), mtl); + try s.rawFrom("core", "weight-only", &.{ ks.core_weight_only_body, ks.core_weight_only }, try weight_only.source(s.a, ks.core_weight_only_body, ks.core_weight_only, false)); + const hc_activation = @import("../src/core/hc_activation_metal_impl.zig").Adapter(@import("../src/core/hc_activation.zig"), mtl); + try s.rawFrom("core", "hc-activation", &.{ ks.core_weight_only_body, ks.core_hc_activation_body, ks.core_hc_activation }, try hc_activation.source(s.a, ks.core_weight_only_body, ks.core_hc_activation_body, ks.core_hc_activation, false)); + const hc_pointwise = @import("../src/core/hc_pointwise_metal_impl.zig").Adapter(@import("../src/core/hc_pointwise.zig"), mtl); + try s.rawFrom("core", "hc-pointwise", &.{ ks.core_weight_only_body, ks.core_hc_activation_body, ks.core_hc_pointwise }, try hc_pointwise.source(s.a, ks.core_weight_only_body, ks.core_hc_activation_body, ks.core_hc_pointwise, false)); - try s.fragments("core", "exlr8-prompt", ks.core_exlr8_projection ++ ks.core_exlr8_prompt); - try s.fragments("core", "exlr8-dense-prompt", ks.core_exlr8_dense ++ ks.core_exlr8_dense_prompt); - for ([_]u32{ 13, 15 }) |gen| try s.raw("core", "tile-qmm", @import("../src/core/tile_qmm.zig").source(gen)); + try s.fragmentsFrom("core", "exlr8-prompt", &.{ ks.core_exlr8_projection, ks.core_exlr8_prompt }, ks.core_exlr8_projection ++ ks.core_exlr8_prompt); + try s.fragmentsFrom("core", "exlr8-dense-prompt", &.{ ks.core_exlr8_dense, ks.core_exlr8_dense_prompt }, ks.core_exlr8_dense ++ ks.core_exlr8_dense_prompt); + for ([_]u32{ 13, 15 }) |gen| try s.rawFrom("core", "tile-qmm", &.{ks.core_tile_qmm}, @import("../src/core/tile_qmm.zig").source(gen)); for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for ([_]u16{ 32, 64, 128 }) |group| { for ([_]bool{ false, true }) |float_out| for (std.enums.values(affine.Glu)) |glu| - try s.raw("core-affine", try std.fmt.allocPrint(s.a, "b{d}-g{d}-{}-{t}", .{ bits, group, float_out, glu }), try affine.source(device, s.a, .{ .bits = bits, .group = group, .out_f32 = float_out, .glu = glu })); + try s.rawFrom("core-affine", try std.fmt.allocPrint(s.a, "b{d}-g{d}-{}-{t}", .{ bits, group, float_out, glu }), &.{ ks.core_affine_mm, ks.core_affine_nonfinite, ks.nax }, try affine.source(device, s.a, .{ .bits = bits, .group = group, .out_f32 = float_out, .glu = glu })); }; try s.fragments("core", "fragment-layout-probe", @import("../src/core/frags.zig").check_source); try s.raw("core", "counter-probe", ks.counter_probe); @@ -31,28 +37,28 @@ pub fn add(s: *Set, device: mtl.Device) !void { fn projections(s: *Set) !void { for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for ([_]usize{ 32, 64, 128 }) |group| { var l = lane.Layout{ .n = 256, .k = 512, .format = .{ .bits = bits, .group = group } }; - try s.fragments("core-lane", "plain", try lane.source(s.a, l)); + try s.fragmentsFrom("core-lane", "plain", &.{ks.core_lane_projection}, try lane.source(s.a, l)); l.sk = 2; l.pf = 2; l.output = .f32; l.groups = .{ 1, 2 }; l.ranges = &.{.{ 1, 2 }}; l.y_stride = 512; - try s.fragments("core-lane", "split-strided", try lane.source(s.a, l)); + try s.fragmentsFrom("core-lane", "split-strided", &.{ks.core_lane_projection}, try lane.source(s.a, l)); }; for ([_]bool{ false, true }) |reg| for ([_]bool{ false, true }) |cooperative| { if (reg and cooperative) continue; const l = lane.Layout{ .n = 256, .k = 512, .format = .{ .bits = 4, .group = 64 }, .reg = reg, .cooperative = cooperative, .precompute_sums = true }; - try s.fragments("core-lane", "prepared", try lane.source(s.a, l)); + try s.fragmentsFrom("core-lane", "prepared", &.{ks.core_lane_projection}, try lane.source(s.a, l)); }; const attention = @import("../src/core/shared_attention.zig"); for (std.enums.values(attention.Output)) |out| { const text = try attention.source(s.a, .{ .query_heads = 8, .kv_heads = 2, .head_dim = 128, .capacity = 4096, .output = out }); - try s.add("core", "shared-attention", text, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + try s.addFrom("core", "shared-attention", &.{ks.core_shared_attention}, text, .{ .language = mtl.mlx().language, .math_functions = .precise }); } const route = @import("../src/core/moe_route.zig"); for ([_]route.Shape{ .{ .hidden = 4096, .experts = 288, .topk = 8 }, .{ .hidden = 4096, .experts = 128, .topk = 8, .out_bf16 = true }, .{ .hidden = 6144, .experts = 128, .topk = 4 } }) |shape| - try s.raw("core", "route", try route.source(s.a, shape)); + try s.rawFrom("core", "route", &.{ks.core_moe_route}, try route.source(s.a, shape)); const hc = @import("../src/core/hc.zig"); - try s.raw("core", "hc", try hc.source(s.a, .{ .width = 4096, .sinkhorn = 20, .eps_e9 = 1000 })); + try s.rawFrom("core", "hc", &.{ks.core_hc_boundary}, try hc.source(s.a, .{ .width = 4096, .sinkhorn = 20, .eps_e9 = 1000 })); } diff --git a/zig/runtime_sources/coverage_test.zig b/zig/runtime_sources/coverage_test.zig new file mode 100644 index 00000000000..d770f6d2c4d --- /dev/null +++ b/zig/runtime_sources/coverage_test.zig @@ -0,0 +1,271 @@ +//! Every exported Metal source string must be assembled into a runtime library or explicitly excluded. +const std = @import("std"); +const sources = @import("kernel_sources"); +const inventory = @import("root.zig"); + +const Exclusion = struct { path: []const u8, reason: []const u8 }; +const exclusions = [_]Exclusion{ + .{ .path = "kernel_sources.core_contract_controls", .reason = "planted kernel-contract violations, not engine runtime libraries" }, + .{ .path = "kernel_sources.drama3", .reason = "the engine loads prebuilt Drama3 metallibs; these texts are for kernel contracts" }, + .{ .path = "kernel_sources.packed_metallib", .reason = "prebuilt binary bytes, not a runtime source export" }, + .{ .path = "kernel_sources.nemotron_paged.glue_names", .reason = "pipeline symbols, not Metal source" }, + .{ .path = "kernel_sources.nemotron_paged.partial_names", .reason = "pipeline symbols, not Metal source" }, + .{ .path = "kernel_sources.nemotron_paged.tree_name", .reason = "pipeline symbol, not Metal source" }, + .{ .path = "kernel_sources.nemotron_paged.prefill_tags", .reason = "source-selection tags, not Metal source" }, + .{ .path = "kernel_sources.nemotron_paged.prefill_names", .reason = "pipeline symbols, not Metal source" }, + .{ .path = "kernel_sources.nemotron_prompt_masked.tags", .reason = "source-selection tags, not Metal source" }, + .{ .path = "h3_kernels.gemm_whole", .reason = "pipeline symbol, not Metal source" }, + .{ .path = "h3_kernels.gemm_ragged", .reason = "pipeline symbol, not Metal source" }, + .{ .path = "h3_kernels.gemm_32x64", .reason = "pipeline symbol, not Metal source" }, + .{ .path = "h3_kernels.gemm_32x64_ragged", .reason = "pipeline symbol, not Metal source" }, + .{ .path = "h3_kernels.names", .reason = "pipeline symbols, not Metal source" }, + .{ .path = "h3_image_encoder_kernels.names", .reason = "pipeline symbols, not Metal source" }, + .{ .path = "h3_prompt_kernels.names", .reason = "pipeline symbols, not Metal source" }, +}; + +const Checker = struct { + sets: []const inventory.Set, + failures: usize = 0, + + const OptionRule = enum { mlx, precise, mlx_or_precise }; + const precise_exports = [_][]const u8{ + "h3_image_encoder_kernels.source", + "inkling2_metal.inkling2_dflash2", + "kernel_sources.inkling2.inkling2_dflash2", + "kernel_sources.core_affine_embed", + "kernel_sources.core_shared_attention", + "kernel_sources.flint_glue", + "kernel_sources.glm_draft_attention", + "kernel_sources.llama_glue", + "kernel_sources.minimax_m3_dflash2", + "kernel_sources.minimax_m3_glue", + "kernel_sources.qwen3_heads", + "kernel_sources.ricursive_dflash2", + "kernel_sources.ricursive_fp4", + "kernel_sources.ricursive_glue", + "kernel_sources.spark25_glue", + "kernel_sources.step5_attend_nax", + "kernel_sources.step5_glue", + "kernel_sources.step5_sparse", + }; + const dual_exports = [_][]const u8{ + "kernel_sources.core_moe_route", + "kernel_sources.minimax_m3_dspark", + "kernel_sources.nax", + }; + + fn requiredOptions(path: []const u8) OptionRule { + for (precise_exports) |candidate| if (std.mem.eql(u8, path, candidate)) return .precise; + for (dual_exports) |candidate| if (std.mem.eql(u8, path, candidate)) return .mlx_or_precise; + return .mlx; + } + + fn optionsMatch(rule: OptionRule, actual: @import("metal").CompileOptions) bool { + const mlx = @import("metal").mlx(); + if (std.meta.eql(actual, mlx)) return rule != .precise; + if (rule == .mlx) return false; + var precise = mlx; + precise.math_functions = .precise; + return std.meta.eql(actual, precise); + } + + fn registered(self: *const Checker, path: []const u8, text: []const u8) bool { + const rule = requiredOptions(path); + for (self.sets) |set| for (set.origins.items) |origin| { + if (!std.mem.eql(u8, origin.text, text)) continue; + if (optionsMatch(rule, origin.options)) return true; + }; + return false; + } + + fn excluded(path: []const u8) bool { + for (exclusions) |entry| { + if (std.mem.eql(u8, entry.path, path)) return true; + if (path.len > entry.path.len and std.mem.startsWith(u8, path, entry.path) and path[entry.path.len] == '.') return true; + } + return false; + } + + fn source(self: *Checker, path: []const u8, text: []const u8) void { + if (self.registered(path, text) or excluded(path)) return; + self.failures += 1; + std.debug.print("unregistered Metal source export: {s} ({d} bytes)\n", .{ path, text.len }); + } + + fn structure(self: *Checker, comptime item_value: anytype, path: []const u8) !void { + inline for (comptime @typeInfo(@TypeOf(item_value)).@"struct".field_names) |field_name| { + if (comptime !std.mem.eql(u8, field_name, "text") and !std.mem.eql(u8, field_name, "source")) continue; + const field_path = try std.fmt.allocPrint(std.testing.allocator, "{s}.{s}", .{ path, field_name }); + defer std.testing.allocator.free(field_path); + try self.value(@field(item_value, field_name), field_path); + } + } + + fn value(self: *Checker, comptime item_value: anytype, path: []const u8) !void { + const T = @TypeOf(item_value); + if (comptime T == type) return self.namespace(item_value, path); + switch (comptime @typeInfo(T)) { + .pointer => |p| { + if (comptime isString(T)) { + const text: []const u8 = item_value; + self.source(path, text); + } else if (comptime p.size == .slice) { + if (comptime isString(p.child)) { + inline for (item_value) |item| self.source(path, item); + } else if (comptime @typeInfo(p.child) == .@"struct") { + inline for (item_value) |item| try self.structure(item, path); + } + } else if (comptime p.size == .one and @typeInfo(p.child) == .@"struct") { + try self.structure(item_value.*, path); + } + }, + .array => |a| { + if (comptime isString(a.child)) { + inline for (item_value) |item| self.source(path, item); + } else if (comptime @typeInfo(a.child) == .@"struct") { + inline for (item_value) |item| try self.structure(item, path); + } + }, + .@"struct" => try self.structure(item_value, path), + else => {}, + } + } + + fn namespace(self: *Checker, comptime module: type, prefix: []const u8) !void { + inline for (comptime std.meta.declarations(module)) |decl| { + const path = try std.fmt.allocPrint(std.testing.allocator, "{s}.{s}", .{ prefix, decl }); + defer std.testing.allocator.free(path); + try self.value(@field(module, decl), path); + } + } +}; + +fn isString(comptime T: type) bool { + return switch (@typeInfo(T)) { + .pointer => |p| switch (p.size) { + .one => switch (@typeInfo(p.child)) { + .array => |a| a.child == u8, + else => false, + }, + .slice => p.child == u8, + else => false, + }, + else => false, + }; +} + +test "Metal runtime source coverage: every export is registered or explicitly excluded" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const sets = [_]inventory.Set{ + try inventory.generateForOs(a, false, 13, 26), + try inventory.generateForOs(a, true, 17, 27), + }; + var checker = Checker{ .sets = &sets }; + try checker.namespace(sources, "kernel_sources"); + try checker.namespace(@import("inkling2_metal"), "inkling2_metal"); + try checker.namespace(@import("qwen_runtime_sources"), "qwen_runtime_sources"); + try checker.namespace(@import("bf16_topk_sources"), "bf16_topk_sources"); + try checker.namespace(@import("tree_round_sources"), "tree_round_sources"); + try checker.namespace(@import("tree_commit_sources"), "tree_commit_sources"); + try checker.namespace(@import("draft_ops_sources"), "draft_ops_sources"); + try checker.namespace(@import("h3_kernels"), "h3_kernels"); + try checker.namespace(@import("../kernels/metal/h3/image_encoder.zig"), "h3_image_encoder_kernels"); + try checker.namespace(@import("../kernels/metal/h3/prompt_kernels.zig"), "h3_prompt_kernels"); + try checker.namespace(@import("../kernels/metal/h3/image_decoder.zig"), "h3_image_decoder_kernels"); + try checker.namespace(@import("../kernels/metal/ling/sources.zig"), "ling_sources"); + if (checker.failures != 0) return error.UnregisteredMetalSources; +} + +test "Metal runtime source coverage: controls reject an unregistered slice export" { + const Fixture = struct { + pub const text: []const u8 = "kernel void unregistered_slice() {}\n"; + }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const set = inventory.Set{ .a = arena.allocator(), .units = false, .generation = 13 }; + var checker = Checker{ .sets = &.{set} }; + try checker.value(Fixture.text, "fixture.slice"); + try std.testing.expectEqual(@as(usize, 1), checker.failures); +} + +test "Metal runtime source coverage: controls reject a new struct array entry" { + const Fixture = struct { + pub const files = [_]struct { text: []const u8 }{.{ .text = "kernel void unregistered_struct() {}\n" }}; + }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const set = inventory.Set{ .a = arena.allocator(), .units = false, .generation = 13 }; + var checker = Checker{ .sets = &.{set} }; + try checker.value(Fixture.files, "fixture.files"); + try std.testing.expectEqual(@as(usize, 1), checker.failures); +} + +test "Metal runtime source coverage: controls reject an unregistered near-duplicate" { + const base = "shared longest source line in the registered library\nshared source line two\nshared source line three\nshared source line four\nunique registered line\n"; + const candidate = "shared longest source line in the registered library\nshared source line two\nshared source line three\nshared source line four\nunique unregistered line\n"; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var set = inventory.Set{ .a = arena.allocator(), .units = false, .generation = 13 }; + try set.add("fixture", "base", base, @import("metal").mlx()); + var checker = Checker{ .sets = &.{set} }; + checker.source("fixture.near_duplicate", candidate); + try std.testing.expectEqual(@as(usize, 1), checker.failures); +} + +test "Metal runtime source coverage: controls reject wrong compiler options in both directions" { + const mtl = @import("metal"); + const ling = @import("../kernels/metal/ling/sources.zig"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var precise = mtl.mlx(); + precise.math_functions = .precise; + var set = inventory.Set{ .a = arena.allocator(), .units = false, .generation = 13 }; + try set.add("fixture", "mlx-only", ling.route, precise); + try set.add("fixture", "precise-only", sources.qwen3_heads, mtl.mlx()); + var checker = Checker{ .sets = &.{set} }; + checker.source("ling_sources.route", ling.route); + try std.testing.expectEqual(@as(usize, 1), checker.failures); + checker.source("kernel_sources.qwen3_heads", sources.qwen3_heads); + try std.testing.expectEqual(@as(usize, 2), checker.failures); +} + +test "Metal runtime source coverage: controls reject an altered prefix" { + const original = "#define TF_RUNTIME_PROBE 1\nkernel void registered() {}\n"; + const altered = "#define TF_RUNTIME_PROBE 0\nkernel void registered() {}\n"; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var set = inventory.Set{ .a = arena.allocator(), .units = false, .generation = 13 }; + try set.add("fixture", "base", original, @import("metal").mlx()); + var checker = Checker{ .sets = &.{set} }; + checker.source("fixture.prefix", altered); + try std.testing.expectEqual(@as(usize, 1), checker.failures); +} + +test "Metal runtime source coverage: simulated macOS 26 and 27 gate tensor-unit experts" { + const dsv = @import("dsv41.zig"); + const xm = @import("../src/families/deepseek_v41/metal/experts_mma.zig"); + for ([_]struct { major: u32, eligible: bool }{ .{ .major = 26, .eligible = false }, .{ .major = 27, .eligible = true } }) |case| { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const device = @import("metal").Device{ .units = true, .gen = 17, .os_major = case.major }; + try std.testing.expectEqual(case.eligible, dsv.expertUnits(device)); + const set = try inventory.generateForOs(a, true, 17, case.major); + const expected = try xm.source(a, "", &.{}, true); + var entries: usize = 0; + var origins: usize = 0; + for (set.entries.items) |entry| if (std.mem.eql(u8, entry.family, "deepseek-v41") and std.mem.eql(u8, entry.name, "expert-mma-units")) { + entries += 1; + try std.testing.expectEqualStrings(expected, entry.text); + try std.testing.expect(std.meta.eql(entry.options, @import("metal").mlx())); + }; + for (set.origins.items) |origin| if (std.mem.eql(u8, origin.text, sources.dsv41.xunits)) { + origins += 1; + try std.testing.expect(std.meta.eql(origin.options, @import("metal").mlx())); + }; + try std.testing.expectEqual(@as(usize, @intFromBool(case.eligible)), entries); + try std.testing.expectEqual(@as(usize, @intFromBool(case.eligible)), origins); + } +} diff --git a/zig/runtime_sources/dsv41.zig b/zig/runtime_sources/dsv41.zig index 1a13bb818f8..19b77edd4c1 100644 --- a/zig/runtime_sources/dsv41.zig +++ b/zig/runtime_sources/dsv41.zig @@ -5,11 +5,23 @@ const ks = @import("kernel_sources").dsv41; const Set = @import("set.zig").Set; const xm = @import("../src/families/deepseek_v41/metal/experts_mma.zig"); pub fn add(s: *Set, device: mtl.Device) !void { - inline for (.{ "fp8_mma", "fp8_rows", "fp8_tile", "csa2_attn", "topk512", "glue", "glue_tmp", "fused", "fold", "compress", "mv", "cand", "index", "engram", "hc" }) |name| - try s.raw("deepseek-v41", name, @field(ks, name)); - try s.raw("deepseek-v41", "experts", try @import("../src/families/deepseek_v41/metal/experts.zig").source(s.a, "", &.{})); - try s.raw("deepseek-v41", "expert-mma", try xm.source(s.a, "", &.{}, false)); - if (xm.units(device)) try s.raw("deepseek-v41", "expert-mma-units", try xm.source(s.a, "", &.{}, true)); + inline for (.{ "fp8_mma", "fp8_rows", "fp8_tile", "csa2_attn", "topk512", "glue", "glue_tmp", "fused", "fold", "compress", "mv", "cand", "index", "engram", "hc" }) |name| { + const text = @field(ks, name); + if (comptime std.mem.eql(u8, name, "csa2_attn") or std.mem.eql(u8, name, "fused") or std.mem.eql(u8, name, "compress") or std.mem.eql(u8, name, "cand") or std.mem.eql(u8, name, "index")) + try s.rawFrom("deepseek-v41", name, &.{ ks.segs_h, text }, text) + else + try s.raw("deepseek-v41", name, text); + } + try s.rawFrom("deepseek-v41", "experts", &.{ ks.experts_kimi, ks.experts }, try @import("../src/families/deepseek_v41/metal/experts.zig").source(s.a, "", &.{})); + try s.rawFrom("deepseek-v41", "expert-mma", &.{ ks.experts_kimi, ks.experts, ks.xmma }, try xm.source(s.a, "", &.{}, false)); + if (expertUnits(device)) try s.rawFrom("deepseek-v41", "expert-mma-units", &.{ ks.experts_kimi, ks.experts, ks.xmma, ks.xunits }, try xm.source(s.a, "", &.{}, true)); for ([_][2]u32{ .{ 256, 8 }, .{ 128, 4 } }) |shape| - try s.raw("deepseek-v41", "route", try @import("../src/families/deepseek_v41/metal/pipelines.zig").routeSource(s.a, shape[0], shape[1])); + try s.rawFrom("deepseek-v41", "route", &.{ks.route}, try @import("../src/families/deepseek_v41/metal/pipelines.zig").routeSource(s.a, shape[0], shape[1])); +} + +pub fn expertUnits(device: mtl.Device) bool { + const eligible = device.tensorUnits() and device.generation() == 17; + if (device.os_major) |major| return eligible and major >= 27; + if (@import("builtin").target.os.tag == .macos) return xm.units(device); + return eligible; } diff --git a/zig/runtime_sources/flashnext.zig b/zig/runtime_sources/flashnext.zig index 34ea0423895..34af1759c68 100644 --- a/zig/runtime_sources/flashnext.zig +++ b/zig/runtime_sources/flashnext.zig @@ -16,8 +16,10 @@ pub fn add(s: *Set) !void { const scalar = std.mem.endsWith(u8, file.name, "-lanes.metal"); if (scalar == s.units) continue; } - for ([_]bool{ false, true }) |cached| - try s.raw("flashnext-recorded", file.name, try rotary.source(s.a, file.text, cached)); + for ([_]bool{ false, true }) |cached| { + const origins: []const []const u8 = if (cached and std.mem.indexOf(u8, file.text, "tf_rotary_scalar") != null) &.{ file.text, ks.flashnext_rotary_scalar, ks.flashnext_rotary_lookup } else &.{file.text}; + try s.rawFrom("flashnext-recorded", file.name, origins, try rotary.source(s.a, file.text, cached)); + } if (std.mem.startsWith(u8, file.name, "q4_attn_parts")) { try s.raw("flashnext-tree", file.name, try tree.patch(s.a, file.text, &tree.attn_edits)); try s.raw("flashnext-attn2", file.name, try tree.patch(s.a, file.text, &@import("../src/families/flashnext/attn2.zig").edits)); @@ -42,9 +44,12 @@ pub fn add(s: *Set) !void { try s.raw("flashnext", "ple-scale", @import("../src/families/flashnext/ple_scale.zig").source); try s.raw("flashnext", "grammar", @import("../src/families/flashnext/grammar.zig").source); try s.raw("flashnext", "tp", @import("../src/families/flashnext/tp_source.zig").source); + const gx_indexed = try @import("../src/families/flashnext/experts4.zig").indexedGrouped(s.a, ks.flashnext_gx); try s.raw("flashnext", "gx", ks.flashnext_gx); - try s.raw("flashnext", "gx-mb2", try @import("../src/families/flashnext/gx_mb2.zig").text(s.a, ks.flashnext_gx, false)); - try s.raw("flashnext", "rotary-producer", try rotary.producer(s.a)); + try s.rawFrom("flashnext", "gx-indexed", &.{ks.flashnext_gx}, gx_indexed); + try s.rawFrom("flashnext", "gx-mb2", &.{ ks.flashnext_gx, ks.flashnext_gx_mb2 }, try @import("../src/families/flashnext/gx_mb2.zig").text(s.a, ks.flashnext_gx, false)); + try s.rawFrom("flashnext", "gx-indexed-mb2", &.{ ks.flashnext_gx, ks.flashnext_gx_mb2 }, try @import("../src/families/flashnext/gx_mb2.zig").text(s.a, gx_indexed, true)); + try s.rawFrom("flashnext", "rotary-producer", &.{ ks.flashnext_rotary_scalar, ks.flashnext_rotary_prepare }, try rotary.producer(s.a)); inline for (.{ "flashnext_select", "flashnext_pool_pos", "flashnext_mrope" }) |name| for ([_]bool{ false, true }) |cached| try s.raw("flashnext", name, try rotary.source(s.a, @field(ks, name), cached)); try s.fragments("flashnext", "prompt-attention", ks.flashnext_attn); @@ -53,9 +58,9 @@ pub fn add(s: *Set) !void { for ([_]bool{ false, true }) |packing| for ([_]bool{ false, true }) |ssd| { const xnew = try compile.xnewSource(s.a, expert, packing, ssd); try s.raw("flashnext", "xnew", xnew.text); - try s.raw("flashnext", "prompt", try std.mem.concat(s.a, u8, &.{ xnew.header, ks.flashnext_prompt })); + try s.rawFrom("flashnext", "prompt", &.{ ks.core_copy_u32, ks.core_stream_rinv, ks.flashnext_prompt }, try std.mem.concat(s.a, u8, &.{ xnew.header, ks.flashnext_prompt })); for ([_][]const u8{ "#define FZ_GDN_REPLAY 0\n", "#define FZ_GDN_REPLAY 1\n", "#define FZ_GDN_REPLAY 0\n#define FZ_GDN_TREE 1\n" }) |mode| - try s.raw("flashnext", "gdn", try std.mem.concat(s.a, u8, &.{ xnew.header, mode, ks.flashnext_gdn })); + try s.rawFrom("flashnext", "gdn", &.{ks.flashnext_gdn}, try std.mem.concat(s.a, u8, &.{ xnew.header, mode, ks.flashnext_gdn })); }; const hc = try fsr.recorded("qa_hc_down_row_85069d94acd4e9c1.metal"); const cut = std.mem.indexOf(u8, hc, "[[max_total_threads_per_threadgroup") orelse return error.NoKernel; @@ -72,11 +77,15 @@ fn widths(s: *Set) !void { for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| for ([_]u16{ 32, 64, 128 }) |group| { for ([_]bool{ false, true }) |ssd| { const body = if (ssd) try @import("../src/families/flashnext/fsr_prompt_source.zig").patch(s.a, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; - try s.fragments("prompt-widths", "qmmw", try @import("../src/core/qmmw_source.zig").source(s.a, body, bits, group)); + try s.fragmentsFrom("prompt-widths", "qmmw", &.{ks.flashnext_qmmw}, try @import("../src/core/qmmw_source.zig").source(s.a, body, bits, group)); + if (bits == 4 and group == 32) { + const indexed = try @import("../src/families/flashnext/prompt_index_source.zig").patch(s.a, body); + try s.fragmentsFrom("prompt-widths", "qmmw-scale-index", &.{ks.flashnext_qmmw}, try @import("../src/core/qmmw_source.zig").source(s.a, indexed, bits, group)); + } } for ([_]u8{ 1, 2, 4 }) |rps| for ([_]u8{ 0, 1, 2 }) |nib| { if (bits != 4 and nib != 0) continue; - try s.raw("flashnext-rows", "dense", try rows.source(s.a, .{ .n = 2560, .k = 2560, .bits = bits, .group = group, .ld = 2560, .rps = rps, .nib = nib })); + try s.rawFrom("flashnext-rows", "dense", &.{ks.flashnext_rows}, try rows.source(s.a, .{ .n = 2560, .k = 2560, .bits = bits, .group = group, .ld = 2560, .rps = rps, .nib = nib })); }; for ([_]bool{ false, true }) |mapped| for ([_]bool{ false, true }) |tiled| { try s.raw("flashnext-lane", "width", try lane.source(s.a, try lane.template(s.units), .{ .n = if (tiled) 2560 else 2576, .k = 2560, .bits = bits, .group = group, .tmr = 16, .ld = 2600, .mapped = mapped, .tiled = tiled })); @@ -84,7 +93,7 @@ fn widths(s: *Set) !void { }; for ([_][2]usize{ .{ 6, 32 }, .{ 4, 64 }, .{ 8, 32 } }) |format| for ([_]u8{ 0, 1, 2 }) |nib| { if (format[0] != 4 and nib != 0) continue; - try s.raw("flashnext-hc", "rows", try hcrows.source(s.a, .{ .nd = 324, .low = 320, .down = format, .up = format, .nib = nib })); + try s.rawFrom("flashnext-hc", "rows", &.{ ks.core_stream_rinv, ks.flashnext_rows_hc }, try hcrows.source(s.a, .{ .nd = 324, .low = 320, .down = format, .up = format, .nib = nib })); }; } diff --git a/zig/runtime_sources/lfm2.zig b/zig/runtime_sources/lfm2.zig index b7d10ccd373..5fb719e7a8e 100644 --- a/zig/runtime_sources/lfm2.zig +++ b/zig/runtime_sources/lfm2.zig @@ -7,7 +7,7 @@ const source = @import("../src/families/lfm2_moe/source.zig"); pub fn add(s: *Set, device: mtl.Device) !void { try s.raw("lfm2", "base", ks.lfm2); if (source.optionalAvailable(device)) { - try s.raw("lfm2", "attention", try source.prompt(device, s.a, false)); - try s.raw("lfm2", "masked-prompt", try source.prompt(device, s.a, true)); + try s.rawFrom("lfm2", "attention", &.{ ks.lfm2, ks.lfm2_attn_nax, ks.nax }, try source.prompt(device, s.a, false)); + try s.rawFrom("lfm2", "masked-prompt", &.{ ks.lfm2, ks.lfm2_prompt_masked.source, ks.nax }, try source.prompt(device, s.a, true)); } } diff --git a/zig/runtime_sources/models.zig b/zig/runtime_sources/models.zig index 95a9a46b1ea..35151fd8211 100644 --- a/zig/runtime_sources/models.zig +++ b/zig/runtime_sources/models.zig @@ -7,52 +7,52 @@ const g4 = @import("../src/families/gemma4/kernels.zig"); const gcfg = @import("../src/families/gemma4/config.zig"); const gmm = @import("../src/families/gemma4/affine_mm.zig"); pub fn add(s: *Set, device: mtl.Device) !void { - const precise = mtl.CompileOptions{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }; + const precise = mtl.CompileOptions{ .language = mtl.mlx().language, .math_functions = .precise }; for ([_]gcfg.Geometry{ gcfg.dense31b, gcfg.unified12b }) |geo| { for ([_]bool{ false, true }) |global| { for ([_]bool{ false, true }) |assistant| { if (assistant and !g4.draftAvailable(device)) continue; - for (gcfg.widths.bit_widths) |bits| try s.raw("gemma4", try std.fmt.allocPrint(s.a, "{s}-{}-{}-embed{d}", .{ geo.name, global, assistant, bits }), try g4.glueSource(s.a, geo, global, assistant, bits)); + for (gcfg.widths.bit_widths) |bits| try s.rawFrom("gemma4", try std.fmt.allocPrint(s.a, "{s}-{}-{}-embed{d}", .{ geo.name, global, assistant, bits }), &.{ks.gemma4_glue}, try g4.glueSource(s.a, geo, global, assistant, bits)); } - try s.raw("gemma4", "prompt-attention", try g4.promptSource(device, s.a, geo, global)); + try s.rawFrom("gemma4", "prompt-attention", &.{ ks.gemma4_prompt_attention, ks.nax }, try g4.promptSource(device, s.a, geo, global)); } - try s.raw("gemma4", "vision", try @import("../src/families/gemma4/vision_source.zig").source(device, s.a, geo.hidden)); + try s.rawFrom("gemma4", "vision", &.{ ks.gemma4_vision, ks.nax }, try @import("../src/families/gemma4/vision_source.zig").source(device, s.a, geo.hidden)); } for (gcfg.widths.bit_widths) |bits| for ([_]u16{ 32, 64 }) |group| for ([_]bool{ false, true }) |out_f32| for (std.enums.values(gmm.Glu)) |glu| - try s.raw("gemma4", "affine", try gmm.source(device, s.a, .{ .bits = bits, .group = group, .out_f32 = out_f32, .glu = glu })); + try s.rawFrom("gemma4", "affine", &.{ ks.gemma4_affine_mm, ks.nax }, try gmm.source(device, s.a, .{ .bits = bits, .group = group, .out_f32 = out_f32, .glu = glu })); for (@import("../src/families/gemma4/contracts.zig").entries) |v| if (v.kind != 0 and @import("../src/families/gemma4/fused_lane.zig").available(device)) - try s.fragments("gemma4", v.name, try @import("../src/families/gemma4/fused_lane.zig").source(s.a, v.layout())); + try s.fragmentsFrom("gemma4", v.name, &.{ ks.core_lane_projection, ks.gemma4_fused, ks.gemma4_lane_projection }, try @import("../src/families/gemma4/fused_lane.zig").source(s.a, v.layout())); const ll = @import("../src/families/llama/contracts.zig"); if (ll.available(device)) { - try s.add("llama", "glue", try ll.glueSource(s.a), precise); - for (ll.geometries) |geo| try s.raw("llama", geo.name, try ll.attentionSource(device, s.a, geo)); - try s.raw("llama", "gemm", try ll.gemmSource(device, s.a)); + try s.addFrom("llama", "glue", &.{ks.llama_glue}, try ll.glueSource(s.a), precise); + for (ll.geometries) |geo| try s.rawFrom("llama", geo.name, &.{ ks.llama_attention_nax, ks.nax }, try ll.attentionSource(device, s.a, geo)); + try s.rawFrom("llama", "gemm", &.{ ks.llama_gemm, ks.nax }, try ll.gemmSource(device, s.a)); } - try s.add("step5", "glue-sparse", ks.step5_glue ++ ks.step5_sparse, precise); + try s.addFrom("step5", "glue-sparse", &.{ ks.core_affine_embed, ks.step5_glue, ks.step5_sparse }, ks.step5_glue ++ ks.step5_sparse, precise); const step: @import("../src/families/step5/config.zig").Config = .{}; const route = @import("../src/core/moe_route.zig"); - try s.add("step5", "route", try route.source(s.a, .{ .hidden = step.hidden, .experts = step.experts, .topk = step.topk }), precise); + try s.addFrom("step5", "route", &.{ks.core_moe_route}, try route.source(s.a, .{ .hidden = step.hidden, .experts = step.experts, .topk = step.topk }), precise); const dsa: @import("../src/families/glm_dsa/config.zig").Config = .{}; - try s.raw("glm-dsa", "route", try route.source(s.a, .{ .hidden = dsa.hidden, .experts = dsa.experts, .topk = dsa.topk })); + try s.rawFrom("glm-dsa", "route", &.{ks.core_moe_route}, try route.source(s.a, .{ .hidden = dsa.hidden, .experts = dsa.experts, .topk = dsa.topk })); const step_attn = try @import("../src/core/frags.zig").sourceMode(device, s.a, ks.step5_attend_nax, false); - try s.add("step5", "attention", step_attn, precise); + try s.addFrom("step5", "attention", &.{ ks.step5_attend_nax, ks.nax }, step_attn, precise); const sp = @import("../src/families/spark25/metal_model.zig"); - try s.add("spark25", "glue", ks.spark25_glue, precise); - for ([_]bool{ false, true }) |sliding| try s.raw("spark25", "attention", try sp.attentionSource(device, s.a, sliding)); + try s.addFrom("spark25", "glue", &.{ ks.core_affine_embed, ks.spark25_glue }, ks.spark25_glue, precise); + for ([_]bool{ false, true }) |sliding| try s.rawFrom("spark25", "attention", &.{ ks.spark25_attention_nax, ks.nax }, try sp.attentionSource(device, s.a, sliding)); try s.fragments("spark25", "gemm", ks.spark25_gemm); const mm = @import("../src/families/minimax_m3/model.zig"); const c: @import("../src/families/minimax_m3/config.zig").Config = .{}; - try s.add("minimax-m3", "glue", ks.minimax_m3_glue, precise); - try s.raw("minimax-m3", "attention", try mm.attentionSource(device, s.a, &c)); - try s.raw("minimax-m3", "index", try mm.indexSource(device, s.a, &c)); - try s.raw("minimax-m3", "sampler", try mm.samplerSource(s.a, &c)); + try s.addFrom("minimax-m3", "glue", &.{ ks.core_affine_embed, ks.minimax_m3_glue }, ks.minimax_m3_glue, precise); + try s.rawFrom("minimax-m3", "attention", &.{ ks.minimax_m3_attention_nax, ks.nax }, try mm.attentionSource(device, s.a, &c)); + try s.rawFrom("minimax-m3", "index", &.{ ks.minimax_m3_index_nax, ks.nax }, try mm.indexSource(device, s.a, &c)); + try s.rawFrom("minimax-m3", "sampler", &.{ks.nemotron_sample}, try mm.samplerSource(s.a, &c)); try s.raw("minimax-m3", "tap-draft-vec", ks.minimax_m3_dspark); try s.add("minimax-m3", "dspark", ks.minimax_m3_dspark, precise); try s.add("minimax-m3", "dflash2", ks.minimax_m3_dflash2, precise); - try s.raw("minimax-m3", "experts", ks.core_row_projection ++ "\n" ++ ks.minimax_m3_experts); + try s.rawFrom("minimax-m3", "experts", &.{ ks.core_row_projection, ks.minimax_m3_experts }, ks.core_row_projection ++ "\n" ++ ks.minimax_m3_experts); const wide = @import("../src/families/glm/wide.zig"); const kda = comptime @import("../src/families/glm/kernels.zig").generatedSource("kda_rows"); - try s.raw("glm", "wide-rows-gather", wide.gather_source); - try s.raw("glm", "wide-kda-pre", try wide.kdaPreSource(s.a, kda)); - try s.raw("glm", "wide-kda-fg", try wide.kdaFgSource(s.a, kda)); + try s.rawFrom("glm", "wide-rows-gather", &.{ ks.core_row_projection, ks.glm_glue, ks.glm_rows, ks.glm_gather }, wide.gather_source); + try s.rawFrom("glm", "wide-kda-pre", &.{kda}, try wide.kdaPreSource(s.a, kda)); + try s.rawFrom("glm", "wide-kda-fg", &.{ ks.core_row_projection, kda }, try wide.kdaFgSource(s.a, kda)); } diff --git a/zig/runtime_sources/modes_test.zig b/zig/runtime_sources/modes_test.zig index e258527a620..35109570312 100644 --- a/zig/runtime_sources/modes_test.zig +++ b/zig/runtime_sources/modes_test.zig @@ -32,7 +32,7 @@ test "Metal runtime source modes: every restricted entry agrees with its loader defer arena.deinit(); const device = mtl.Device{ .units = generation >= 17, .gen = generation }; const set = try root.generate(arena.allocator(), device.units, generation); - const allowed = [_]bool{ lfm2.optionalAvailable(device), llama.available(device), fused.available(device), gemma.draftAvailable(device), moss.available(device), h3.available(device), xm.units(device) }; + const allowed = [_]bool{ lfm2.optionalAvailable(device), llama.available(device), fused.available(device), gemma.draftAvailable(device), moss.available(device), h3.available(device), @import("dsv41.zig").expertUnits(device) }; var counts: [allowed.len]usize = @splat(0); var dense: usize = 0; for (set.entries.items) |e| { diff --git a/zig/runtime_sources/objc_stubs.zig b/zig/runtime_sources/objc_stubs.zig new file mode 100644 index 00000000000..4616df37a16 --- /dev/null +++ b/zig/runtime_sources/objc_stubs.zig @@ -0,0 +1,16 @@ +//! Link-only non-macOS stubs for the device-free source inventory; none is callable in a passing test. +export fn objc_getClass(name: [*:0]const u8) ?*anyopaque { + _ = name; + @panic("Objective-C is unavailable in the host-only Metal source inventory"); +} + +export fn sel_registerName(name: [*:0]const u8) ?*anyopaque { + _ = name; + @panic("Objective-C is unavailable in the host-only Metal source inventory"); +} + +export fn objc_msgSend(receiver: ?*anyopaque, selector: ?*anyopaque) ?*anyopaque { + _ = receiver; + _ = selector; + @panic("Objective-C is unavailable in the host-only Metal source inventory"); +} diff --git a/zig/runtime_sources/qwen27.zig b/zig/runtime_sources/qwen27.zig index 301b8cc87db..54a69c9f0da 100644 --- a/zig/runtime_sources/qwen27.zig +++ b/zig/runtime_sources/qwen27.zig @@ -5,19 +5,53 @@ const Set = @import("set.zig").Set; pub fn add(s: *Set) !void { inline for (.{ "glue", "copy", "moe" }) |name| try s.raw("qwen27", name, @field(ks, name)); - try s.raw("qwen27", "moe-rows", @import("../src/families/qwen27/moe_gpu.zig").rows_source); + try s.rawFrom("qwen27", "moe-rows", &.{ @import("kernel_sources").core_row_projection, ks.moe_rows }, @import("../src/families/qwen27/moe_gpu.zig").rows_source); const quant = @import("../src/families/qwen27/quant_gpu.zig"); for (std.enums.values(quant.Kind)) |kind| { if (kind == .projection) continue; - try s.raw("qwen27", @tagName(kind), try quant.specializedSource(s.a, .{ .kind = kind, .k = 512, .n = 1024, .tile = 256 })); - if (kind == .norm or kind == .input_norm or kind == .mlp) - try s.raw("qwen27", try std.fmt.allocPrint(s.a, "{s}-no-xs", .{@tagName(kind)}), try quant.specializedSource(s.a, .{ .kind = kind, .k = 512, .n = 1024, .xs = false })); + const origin = switch (kind) { + .projection => unreachable, + .xsum => ks.xsum, + .norm => ks.norm_xs, + .input_norm => ks.norm_input, + .mlp, .mlp_rows => ks.mlp_xs, + .ane_input, .mlp_ane, .add_ane => ks.mlp_ane, + }; + try s.rawFrom("qwen27", @tagName(kind), &.{origin}, try quant.specializedSource(s.a, .{ .kind = kind, .k = 512, .n = 1024, .tile = 256 })); + if (kind == .norm or kind == .input_norm or kind == .mlp or kind == .mlp_rows) + try s.rawFrom("qwen27", try std.fmt.allocPrint(s.a, "{s}-no-xs", .{@tagName(kind)}), &.{origin}, try quant.specializedSource(s.a, .{ .kind = kind, .k = 512, .n = 1024, .xs = false })); } + if (s.units) for (1..9) |sk| for ([_]u32{ 8, 16, 24, 32, 40, 48 }) |block| { + const split: u32 = @intCast(sk); + if (@import("../src/core/qk_projection.zig").threadgroupBytes(block, split) > 32768) continue; + const text = try std.fmt.allocPrint(s.a, "#define TF_SK {d}\n#define TF_ROWS {d}\n{s}", .{ split, block, @import("kernel_sources").core_qk }); + try s.rawFrom("qwen27", try std.fmt.allocPrint(s.a, "qk-sk{d}-rows{d}", .{ split, block }), &.{@import("kernel_sources").core_qk}, text); + }; const attention = @import("../src/families/qwen27/simd_attention.zig"); - for ([_]bool{ false, true }) |paged| for ([_]bool{ false, true }) |prompt| for ([_][2]u32{ .{ 6, 4 }, .{ 4, 4 }, .{ 8, 4 } }) |g| - try s.raw("qwen27", try std.fmt.allocPrint(s.a, "attention-paged{}-prompt{}-g{d}", .{ paged, prompt, g[0] }), try attention.grouped(s.a, s.units, prompt, g[0], g[1], paged)); + for ([_]bool{ false, true }) |paged| for ([_]bool{ false, true }) |prompt| for ([_][2]u32{ .{ 6, 4 }, .{ 4, 4 }, .{ 8, 4 } }) |g| { + const origins = try attentionOrigins(s, prompt, paged); + try s.rawFrom("qwen27", try std.fmt.allocPrint(s.a, "attention-paged{}-prompt{}-g{d}", .{ paged, prompt, g[0] }), origins, try attention.grouped(s.a, s.units, prompt, g[0], g[1], paged)); + }; + if (!s.units) { + for ([_]bool{ false, true }) |paged| for ([_][2]u32{ .{ 6, 4 }, .{ 4, 4 }, .{ 8, 4 } }) |g| { + const origins = try attentionOrigins(s, false, paged); + try s.rawFrom("qwen27", try std.fmt.allocPrint(s.a, "attention-join-paged{}-g{d}", .{ paged, g[0] }), origins, try attention.joined(s.a, false, false, g[0], g[1], paged)); + }; + } const ksrc = @import("kernel_sources"); try s.raw("sensenova", "mhc", ksrc.core_sensenova_mhc); try s.fragments("sensenova", "bf16_linear", ksrc.qwen27_bf16_linear); try s.fragments("sensenova", "awq_w4a16", ksrc.qwen27_awq_w4a16); } + +fn attentionOrigins(s: *Set, prompt: bool, paged: bool) ![]const []const u8 { + const twins = @import("kernel_sources").qwen27_paged; + var origins: std.ArrayList([]const u8) = .empty; + try origins.append(s.a, ks.glue); + try origins.append(s.a, if (paged) twins.attention_mpp else ks.attention_mpp); + try origins.append(s.a, if (paged) twins.attention_io else ks.attention_io); + if (paged) try origins.append(s.a, @import("kernel_sources").kv_pages); + if (s.units or prompt) try origins.append(s.a, if (paged) twins.attention_prompt else ks.attention_prompt); + if (!s.units and prompt) try origins.append(s.a, if (paged) twins.attention_prompt_sg else ks.attention_prompt_sg); + return origins.items; +} diff --git a/zig/runtime_sources/registry_test.zig b/zig/runtime_sources/registry_test.zig new file mode 100644 index 00000000000..32b5696d359 --- /dev/null +++ b/zig/runtime_sources/registry_test.zig @@ -0,0 +1,81 @@ +//! Exact production variants and compile options required in the runtime source inventory. +const std = @import("std"); +const mtl = @import("metal"); +const inventory = @import("root.zig"); +const ks = @import("kernel_sources"); +const Set = @import("set.zig").Set; +const t = std.testing; + +fn expectSource(set: Set, text: []const u8, options: mtl.CompileOptions) !void { + for (set.entries.items) |entry| { + if (std.meta.eql(entry.options, options) and std.mem.eql(u8, entry.text, text)) return; + } + return error.MissingExactRuntimeSource; +} + +fn expectEvery(set: Set, text: []const u8) !void { + try expectSource(set, text, mtl.mlx()); +} + +test "Metal runtime source registry: pre-M5 Qwen27 joined attention is exact" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const set = try inventory.generate(a, false, 13); + const attention = @import("../src/families/qwen27/simd_attention.zig"); + for ([_]bool{ false, true }) |paged| for ([_][2]u32{ .{ 6, 4 }, .{ 4, 4 }, .{ 8, 4 } }) |g| { + try expectEvery(set, try attention.joined(a, false, false, g[0], g[1], paged)); + }; +} + +test "Metal runtime source registry: H3 and Ling standalone libraries preserve options" { + const precise = mtl.CompileOptions{ .language = mtl.mlx().language, .math_functions = .precise }; + const encoder = @import("../kernels/metal/h3/image_encoder.zig").source; + const prompt = @import("../kernels/metal/h3/prompt_kernels.zig").source; + const decoder = @import("../kernels/metal/h3/image_decoder.zig").source; + const ling = @import("../kernels/metal/ling/sources.zig"); + for ([_]bool{ false, true }) |units| { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const set = try inventory.generate(arena.allocator(), units, if (units) 17 else 13); + try expectSource(set, encoder, precise); + try expectEvery(set, prompt); + try expectEvery(set, decoder); + try expectEvery(set, ling.route); + try expectEvery(set, ling.mla); + try expectEvery(set, ks.lfm3); + } +} + +test "Metal runtime source registry: Flash Next scale-index variants match both loaders" { + const experts4 = @import("../src/families/flashnext/experts4.zig"); + const mb2 = @import("../src/families/flashnext/gx_mb2.zig"); + const prompt_index = @import("../src/families/flashnext/prompt_index_source.zig"); + const qmmw = @import("../src/core/qmmw_source.zig"); + const precision = @import("../src/core/attention_precision.zig"); + const fsr = @import("../src/families/flashnext/fsr_prompt_source.zig"); + for ([_]bool{ false, true }) |units| { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const set = try inventory.generate(a, units, if (units) 17 else 13); + const grouped = try experts4.indexedGrouped(a, ks.flashnext_gx); + try expectEvery(set, grouped); + try expectEvery(set, try mb2.text(a, grouped, true)); + for ([_]bool{ false, true }) |ssd| { + const body = if (ssd) try fsr.patch(a, ks.flashnext_qmmw, true) else ks.flashnext_qmmw; + const indexed = try prompt_index.patch(a, body); + const specialized = try qmmw.source(a, indexed, 4, 32); + try expectEvery(set, try precision.source(a, units, specialized, ks.nax, false)); + } + } +} + +test "Metal runtime source registry: raw Hy4 elementwise is present on pre-M5 and tensor units" { + for ([_]bool{ false, true }) |units| { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const set = try inventory.generate(arena.allocator(), units, if (units) 17 else 13); + try expectEvery(set, ks.elementwise); + } +} diff --git a/zig/runtime_sources/root.zig b/zig/runtime_sources/root.zig index 27ae5dc357a..bb7b65bb490 100644 --- a/zig/runtime_sources/root.zig +++ b/zig/runtime_sources/root.zig @@ -3,8 +3,17 @@ const std = @import("std"); const mtl = @import("metal"); pub const Set = @import("set.zig").Set; pub fn generate(a: std.mem.Allocator, units: bool, generation: u32) !Set { + return generateInternal(a, units, generation, null); +} + +/// Deterministic macOS-major simulation for provenance; production and default tests retain `generate`. +pub fn generateForOs(a: std.mem.Allocator, units: bool, generation: u32, os_major: u32) !Set { + return generateInternal(a, units, generation, os_major); +} + +fn generateInternal(a: std.mem.Allocator, units: bool, generation: u32, os_major: ?u32) !Set { var s = Set{ .a = a, .units = units, .generation = generation }; - const device = mtl.Device{ .units = units, .gen = generation }; + const device = mtl.Device{ .units = units, .gen = generation, .os_major = os_major }; try @import("catalogs.zig").add(&s, device); try @import("core.zig").add(&s, device); try @import("../src/families/glm/kernels.zig").visitSources(a, device, &s); @@ -16,6 +25,7 @@ pub fn generate(a: std.mem.Allocator, units: bool, generation: u32) !Set { if (std.mem.endsWith(u8, e.name, "-production") or std.mem.endsWith(u8, e.name, "-0") or std.mem.startsWith(u8, e.name, "draw-")) try s.raw("qwen4", e.name, e.text); } + try @import("completion.zig").add(&s, device); return s; } diff --git a/zig/runtime_sources/set.zig b/zig/runtime_sources/set.zig index ef3d78d555d..dad2fa99498 100644 --- a/zig/runtime_sources/set.zig +++ b/zig/runtime_sources/set.zig @@ -4,27 +4,52 @@ const mtl = @import("metal"); const precision = @import("../src/core/attention_precision.zig"); const ks = @import("kernel_sources"); pub const Entry = struct { family: []const u8, name: []const u8, text: []const u8, options: mtl.CompileOptions, packed_inline: bool }; +pub const Origin = struct { text: []const u8, options: mtl.CompileOptions }; pub const Set = struct { a: std.mem.Allocator, units: bool, generation: u32, entries: std.ArrayList(Entry) = .empty, + origins: std.ArrayList(Origin) = .empty, + + fn note(s: *Set, text: []const u8, options: mtl.CompileOptions) !void { + for (s.origins.items) |origin| { + if (std.meta.eql(origin.options, options) and std.mem.eql(u8, origin.text, text)) return; + } + try s.origins.append(s.a, .{ .text = try s.a.dupe(u8, text), .options = options }); + } + + pub fn addFrom(s: *Set, family: []const u8, name: []const u8, origins: []const []const u8, text: []const u8, options: mtl.CompileOptions) !void { + for (origins) |origin| try s.note(origin, options); + try s.add(family, name, text, options); + } + + pub fn rawFrom(s: *Set, family: []const u8, name: []const u8, origins: []const []const u8, text: []const u8) !void { + try s.addFrom(family, name, origins, text, mtl.mlx()); + } pub fn add(s: *Set, family: []const u8, name: []const u8, text: []const u8, options: mtl.CompileOptions) !void { + try s.note(text, options); for (s.entries.items) |e| if (std.meta.eql(e.options, options) and std.mem.eql(u8, e.text, text)) return; try s.entries.append(s.a, .{ .family = family, .name = try s.a.dupe(u8, name), .text = try s.a.dupe(u8, text), .options = options, .packed_inline = std.mem.indexOf(u8, text, "uint4b_format") != null }); } pub fn raw(s: *Set, family: []const u8, name: []const u8, text: []const u8) !void { - try s.add(family, name, text, mtl.CompileOptions.mlx()); + try s.add(family, name, text, mtl.mlx()); } - pub fn fragments(s: *Set, family: []const u8, name: []const u8, text: []const u8) !void { + pub fn fragmentsFrom(s: *Set, family: []const u8, name: []const u8, origins: []const []const u8, text: []const u8) !void { + for (origins) |origin| try s.note(origin, mtl.mlx()); + try s.note(ks.nax, mtl.mlx()); const adapted = try precision.source(s.a, s.units, text, ks.nax, false); - try s.raw(family, name, adapted); + try s.add(family, name, adapted, mtl.mlx()); if (std.mem.indexOf(u8, text, "TF_ATTN_PV_FP32") != null) { const full = try precision.source(s.a, s.units, text, ks.nax, true); - try s.raw(family, try std.fmt.allocPrint(s.a, "{s}-pv-fp32", .{name}), full); + try s.add(family, try std.fmt.allocPrint(s.a, "{s}-pv-fp32", .{name}), full, mtl.mlx()); } } + + pub fn fragments(s: *Set, family: []const u8, name: []const u8, text: []const u8) !void { + try s.fragmentsFrom(family, name, &.{text}, text); + } }; diff --git a/zig/src/core/contract/hy4_mla_paged_records.zig b/zig/src/core/contract/hy4_mla_paged_records.zig new file mode 100644 index 00000000000..363d134ff03 --- /dev/null +++ b/zig/src/core/contract/hy4_mla_paged_records.zig @@ -0,0 +1,45 @@ +//! Hy4-flash paged MLA (`hy4_mla_paged`, `hy4_mla_attn_paged`, `hy4_mla_c2`) 5-SM launch records (`nvcc 13.0`). +const std = @import("std"); +const registry = @import("registry.zig"); +const U = @import("limits.zig").Usage; + +fn sameS(b: u32, s: u32, r80: u32, r86: u32, r89: u32, r120: u32, r121: u32) [5]U { + return .{ + .{ .regs = r80, .static = s, .bound = b }, + .{ .regs = r86, .static = s, .bound = b }, + .{ .regs = r89, .static = s, .bound = b }, + .{ .regs = r120, .static = s, .bound = b }, + .{ .regs = r121, .static = s, .bound = b }, + }; +} + +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "hy4_mla_paged tf_hy4_mla_absorb", .symbol = "tf_hy4_mla_absorb", .image = "hy4_mla_paged", .threads = 128 }, .usage = sameS(128, 12288, 104, 106, 106, 88, 94) }, + .{ .launch = .{ .name = "hy4_mla_paged tf_hy4_mla_attn", .symbol = "tf_hy4_mla_attn", .image = "hy4_mla_paged", .threads = 256, .dynamic = 56672, .opt_in = true }, .usage = sameS(256, 0, 64, 64, 64, 78, 78) }, + .{ .launch = .{ .name = "hy4_mla_paged tf_hy4_mla_attn_rows", .symbol = "tf_hy4_mla_attn_rows", .image = "hy4_mla_paged", .threads = 256, .dynamic = 56672, .opt_in = true }, .usage = sameS(256, 0, 74, 77, 77, 80, 80) }, + .{ .launch = .{ .name = "hy4_mla_paged tf_hy4_mla_value", .symbol = "tf_hy4_mla_value", .image = "hy4_mla_paged", .threads = 128 }, .usage = sameS(128, 8320, 60, 56, 56, 56, 56) }, + .{ .launch = .{ .name = "hy4_mla_paged tf_hy4_mla_post", .symbol = "tf_hy4_mla_post", .image = "hy4_mla_paged", .threads = 256 }, .usage = sameS(256, 32, 40, 40, 40, 40, 40) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16", .symbol = "hy4_mla_dec_x16", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 81552, .opt_in = true }, .usage = sameS(256, 0, 125, 125, 125, 130, 130) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16_rows", .symbol = "hy4_mla_dec_x16_rows", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 81552, .opt_in = true }, .usage = sameS(256, 0, 127, 127, 127, 132, 132) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16_qreg", .symbol = "hy4_mla_dec_x16_qreg", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 48896 }, .usage = sameS(256, 0, 128, 128, 128, 128, 128) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16_qreg_rows", .symbol = "hy4_mla_dec_x16_qreg_rows", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 48896 }, .usage = sameS(256, 0, 128, 128, 128, 128, 128) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_fold", .symbol = "hy4_mla_fold", .image = "hy4_mla_attn_paged", .threads = 256 }, .usage = sameS(256, 16640, 64, 64, 64, 62, 62) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16_paged", .symbol = "hy4_mla_dec_x16_paged", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 81552, .opt_in = true }, .usage = sameS(256, 0, 125, 125, 125, 132, 132) }, + .{ .launch = .{ .name = "hy4_mla_attn_paged hy4_mla_dec_x16_qreg_paged", .symbol = "hy4_mla_dec_x16_qreg_paged", .image = "hy4_mla_attn_paged", .threads = 256, .dynamic = 48896 }, .usage = sameS(256, 0, 128, 128, 128, 128, 128) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_absorb_d1_x", .symbol = "hy4c2_absorb_d1_x", .image = "hy4_mla_c2", .threads = 128, .dynamic = 5632 }, .usage = sameS(128, 0, 82, 82, 82, 78, 78) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_absorb_d2_x", .symbol = "hy4c2_absorb_d2_x", .image = "hy4_mla_c2", .threads = 128, .dynamic = 8704 }, .usage = sameS(128, 0, 92, 92, 92, 88, 88) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_absorb_p_x", .symbol = "hy4c2_absorb_p_x", .image = "hy4_mla_c2", .threads = 256, .dynamic = 33792 }, .usage = sameS(256, 0, 124, 124, 124, 126, 126) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_expand_d1_f32lat", .symbol = "hy4c2_expand_d1_f32lat", .image = "hy4_mla_c2", .threads = 128, .dynamic = 27136 }, .usage = sameS(128, 0, 109, 109, 109, 118, 118) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_expand_d2_f32lat", .symbol = "hy4c2_expand_d2_f32lat", .image = "hy4_mla_c2", .threads = 128, .dynamic = 51712, .opt_in = true }, .usage = sameS(128, 0, 113, 113, 113, 125, 125) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_expand_d4k64s2_f32lat", .symbol = "hy4c2_expand_d4k64s2_f32lat", .image = "hy4_mla_c2", .threads = 128, .dynamic = 27136 }, .usage = sameS(128, 0, 94, 94, 94, 86, 86) }, + .{ .launch = .{ .name = "hy4_mla_c2 hy4c2_expand_p_f32lat", .symbol = "hy4c2_expand_p_f32lat", .image = "hy4_mla_c2", .threads = 256, .dynamic = 46080 }, .usage = sameS(256, 0, 128, 128, 128, 124, 124) }, +}; + +test "Hy4 paged MLA CUDA: every launch is in the live registry and fits every SM" { + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try std.testing.expectEqual(@as(usize, 1), found); + try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 5f075ce6844..873b6ac23bc 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -37,7 +37,8 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("dense_attention_records.zig").cuda ++ @import("dots_mocr_cuda_records.zig").cuda ++ @import("hy4_ihc_hc_records.zig").cuda ++ - @import("hy4_route_rows_records.zig").cuda; + @import("hy4_route_rows_records.zig").cuda ++ + @import("hy4_mla_paged_records.zig").cuda; pub const nvcc_132_after = @import("registry_learning.zig").cuda_132 ++ @import("paging_pending.zig").cuda_132 ++ @import("lfm2_moe_cuda_records.zig").cuda_132 ++ @@ -200,4 +201,5 @@ test { _ = @import("qmmf_many_records.zig"); _ = @import("hy4_route_rows_records.zig"); _ = @import("hy4_engram_fp8_records.zig"); + _ = @import("hy4_mla_paged_records.zig"); } diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 8f8b4bb9987..984df2b897a 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -182,6 +182,9 @@ pub const hy4_ihc_fused: []const u8 = if (available) &Blob("fatbin_hy4_ihc_fused pub const hy4_route: []const u8 = if (available) &Blob("fatbin_hy4_route").bytes else &.{}; pub const hy4_rows: []const u8 = if (available) &Blob("fatbin_hy4_rows").bytes else &.{}; pub const hy4_dfly2_glue: []const u8 = if (available) &Blob("fatbin_hy4_dfly2_glue").bytes else &.{}; +pub const hy4_mla_paged: []const u8 = if (available) &Blob("fatbin_hy4_mla_paged").bytes else &.{}; +pub const hy4_mla_attn_paged: []const u8 = if (available) &Blob("fatbin_hy4_mla_attn_paged").bytes else &.{}; +pub const hy4_mla_c2: []const u8 = if (available) &Blob("fatbin_hy4_mla_c2").bytes else &.{}; /// Symbols in the gdn image as cuobjdump lists them for the built fatbin (named namespace tf_gdn). pub const gdn_symbols = struct { diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index b4e2c6fca5a..db99027af91 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -437,7 +437,30 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an if (m3_fast) jobs[generated.len + 27] = .{ .device = device, .source = m3_src, .names = &affine_mm.names, .out = &m3_out }; const active_jobs = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; if (comptime @TypeOf(visitor) != void) { - for (active_jobs) |j| try visitor.raw("glm", j.names[0], j.source); + for (active_jobs, 0..) |j, i| { + const origins: []const []const u8 = switch (i) { + generated.len => &.{ sources.core_copy_u32, sources.glm_glue }, + generated.len + 4 => &.{ sources.glm_attn, sources.nax }, + generated.len + 5, generated.len + 6 => &.{ sources.core_moe_route, sources.glm_route_one }, + generated.len + 7 => &.{ sources.core_affine_mm, sources.core_affine_nonfinite, sources.glm_mm_groups, sources.nax }, + generated.len + 8, generated.len + 27 => &.{ sources.core_affine_mm, sources.core_affine_nonfinite, sources.nax }, + generated.len + 9 => &.{ comptime kernelOf("kda_rows").source, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }, + generated.len + 10, generated.len + 13 => &.{ sources.glm_sparse_nax, sources.nax }, + generated.len + 11, generated.len + 14 => &.{ sources.glm_absorb_nax, sources.nax }, + generated.len + 12 => &.{sources.core_hc_boundary}, + generated.len + 15 => &.{ sources.glm_index_nax, sources.nax }, + generated.len + 16 => &.{comptime kernelOf("moe_gateup_1").source}, + generated.len + 17 => &.{comptime kernelOf("moe_down_1").source}, + generated.len + 18, generated.len + 20 => &.{comptime kernelOf("moe_gateup_2").source}, + generated.len + 19, generated.len + 21 => &.{comptime kernelOf("moe_down_2").source}, + generated.len + 22 => &.{comptime kernelOf("moe_combine").source}, + generated.len + 24 => &.{ sources.ops_softmax, sources.glm_softmax_rows }, + generated.len + 25 => &.{ sources.core_moe_route, comptime kernelOf("moe_gateup_2").source }, + generated.len + 26 => &.{comptime kernelOf("moe_down_2").source}, + else => &.{j.source}, + }; + try visitor.rawFrom("glm", j.names[0], origins, j.source); + } return; } var sources_seen = std.hash.Wyhash.init(0x6b); diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index e1d1386365b..c55fff2f38a 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -25,6 +25,9 @@ test { _ = @import("rows_cuda.zig"); _ = @import("dfly2_glue_cuda.zig"); _ = @import("engram_fp8_cuda.zig"); + _ = @import("mla_paged_cuda.zig"); + _ = @import("mla_c1_cuda.zig"); + _ = @import("mla_c2_cuda.zig"); if (@import("builtin").os.tag == .linux) _ = @import("bf16_rows_test.zig"); } diff --git a/zig/src/families/hy4_flash/mla_c1_cuda.zig b/zig/src/families/hy4_flash/mla_c1_cuda.zig new file mode 100644 index 00000000000..e8b69aac416 --- /dev/null +++ b/zig/src/families/hy4_flash/mla_c1_cuda.zig @@ -0,0 +1,161 @@ +//! Tensor-core absorbed latent MLA attention (`hy4_mla_attn_paged`): BF16 KV split+fold and paged decode. +const std = @import("std"); +const cuda = @import("cuda"); + +const Stream = cuda.Stream; +const Function = cuda.Function; +const DeviceBuffer = cuda.DeviceBuffer; + +pub const row = 576; +const max_split_rows = 64; +const max_batched_rows = 64; +const max_rows = 4096; +const max_hb = 4; +const max_ns = 18; + +pub fn smemX(mt: u32, kt: u32, qreg: bool) u32 { + const base = (if (qreg) 0 else mt * 16 * 576 * 2 * 2) + 2 * kt * 576 * 2 + mt * 16 * kt * 2 * 2 + (8 / (mt * kt / 8)) * mt * 16 * (kt + 8) * 4 + 2 * kt * 4 + 6 * mt * 16 * 4 + 128 + 16; + return if (qreg) ((base + 127) & ~@as(u32, 127)) + 4 * 16 * 32 * 2 else base; +} + +fn dependentLaunches(d: *const cuda.Driver) bool { + var dev: cuda.abi.Device = 0; + var major: c_int = 0; + if (d.api.cuCtxGetDevice(&dev) != cuda.abi.success) return false; + return d.api.cuDeviceGetAttribute(&major, .compute_capability_major, dev) == cuda.abi.success and major >= 9; +} + +pub const C1 = struct { + mod: cuda.Module, + fold: Function, + x16: Function, + x16_rows: Function, + x16_qreg: Function, + x16_paged: Function, + x16_qreg_paged: Function, + x16_qreg_rows: Function, + pdl: bool = false, + pm: DeviceBuffer, + pl: DeviceBuffer, + po: DeviceBuffer, + rs: DeviceBuffer, + + pub fn load(d: *const cuda.Driver) !C1 { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.hy4_mla_attn_paged); + errdefer mod.unload(); + var c: C1 = undefined; + c.mod = mod; + c.pdl = dependentLaunches(d); + c.fold = try mod.function("hy4_mla_fold"); + c.x16 = try mod.function("hy4_mla_dec_x16"); + try c.x16.allowDynamicShared(smemX(1, 16, false)); + c.x16_rows = try mod.function("hy4_mla_dec_x16_rows"); + try c.x16_rows.allowDynamicShared(smemX(1, 16, false)); + c.x16_qreg = try mod.function("hy4_mla_dec_x16_qreg"); + try c.x16_qreg.allowDynamicShared(smemX(1, 16, true)); + c.x16_paged = try mod.function("hy4_mla_dec_x16_paged"); + try c.x16_paged.allowDynamicShared(smemX(1, 16, false)); + c.x16_qreg_paged = try mod.function("hy4_mla_dec_x16_qreg_paged"); + try c.x16_qreg_paged.allowDynamicShared(smemX(1, 16, true)); + c.x16_qreg_rows = try mod.function("hy4_mla_dec_x16_qreg_rows"); + try c.x16_qreg_rows.allowDynamicShared(smemX(1, 16, true)); + const nf = max_split_rows * max_hb * max_ns * 16; + c.pm = try DeviceBuffer.alloc(d, nf * 4); + errdefer c.pm.free(); + c.pl = try DeviceBuffer.alloc(d, nf * 4); + errdefer c.pl.free(); + c.po = try DeviceBuffer.alloc(d, nf * 512 * 4); + errdefer c.po.free(); + const zeros: [max_rows * 4]u8 = @splat(0); + c.rs = try DeviceBuffer.fromHost(d, &zeros); + return c; + } + + pub fn unload(c: *C1) void { + c.rs.free(); + c.po.free(); + c.pl.free(); + c.pm.free(); + c.mod.unload(); + c.* = undefined; + } +}; + +pub const Keys = struct { + kind: c_int, + ring: usize = 0, + list: u64 = 0, + tok: u64 = 0, + ntok: usize = 0, + single_split: bool = false, + page_table: u64 = 0, + pt_stride: usize = 0, + row_stream: u64 = 0, +}; + +fn ci(v: usize) c_int { + return @intCast(v); +} + +pub fn attn(c: *const C1, s: Stream, qa: u64, qlo: usize, heads: usize, cache: u64, k: Keys, pos: u64, sinks: u64, out: u64, rows: usize) !void { + return attnInner(c, s, qa, qlo, heads, cache, false, k, pos, sinks, out, rows); +} + +pub fn attnRows(c: *const C1, s: Stream, qa: u64, qlo: usize, heads: usize, caches: u64, k: Keys, pos: u64, sinks: u64, out: u64, rows: usize) !void { + return attnInner(c, s, qa, qlo, heads, caches, true, k, pos, sinks, out, rows); +} + +fn attnInner(c: *const C1, s: Stream, qa: u64, qlo: usize, heads: usize, cache: u64, per_row: bool, k: Keys, pos: u64, sinks: u64, out: u64, rows: usize) !void { + if (rows == 0) return; + if (rows > max_rows) return error.RowShape; + if (per_row and rows > max_batched_rows) return error.RowShape; + const mk: usize = switch (k.kind) { + 0 => 512, + 1 => 2048, + else => k.ntok, + }; + const ring: usize = if (k.ring != 0) k.ring else std.math.maxInt(i32); + const paged = k.page_table != 0 and k.kind != 0; + const one_split = k.single_split or rows > max_split_rows; + const want_qreg = one_split or (k.kind != 0 and rows >= 4); + const f = if (want_qreg) (if (paged) c.x16_qreg_paged else if (per_row) c.x16_qreg_rows else c.x16_qreg) else (if (paged) c.x16_paged else if (per_row) c.x16_rows else c.x16); + const sm = smemX(1, 16, want_qreg); + const nq: usize = 16; + const ch: usize = if (one_split) @max(16, (mk + 15) / 16 * 16) else if (k.kind == 0) 64 else 128; + const ns = (mk + ch - 1) / ch; + const hb = (heads + nq - 1) / nq; + if (ns > 1 and (hb > max_hb or ns > max_ns)) return error.RowShape; + var a: cuda.Args = .{}; + a.add(qa); + a.add(ci(heads)); + a.add(cache); + inline for (.{ k.kind, ci(ring), ci(ring) }) |v| a.add(v); + inline for (.{ if (k.row_stream != 0) k.row_stream else c.rs.ptr, pos, k.list, k.tok }) |v| a.add(v); + inline for (.{ ci(k.ntok), ci(k.ntok) }) |v| a.add(v); + a.add(sinks); + a.add(ci(ch)); + inline for (.{ c.pm.ptr, c.pl.ptr, c.po.ptr, @as(u64, 0), out }) |v| a.add(v); + a.add(@as(c_int, 1)); + a.add(ci(rows)); + a.add(@as(i64, @intCast(qlo))); + if (paged) { + a.add(k.page_table); + a.add(ci(k.pt_stride)); + } + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(ns), .y = @intCast(hb), .z = @intCast(rows) }, .block = .{ .x = 256 }, .shared = sm }, s, &a); + if (ns <= 1) return; + var b: cuda.Args = .{}; + inline for (.{ ci(heads), ci(nq), k.kind }) |v| b.add(v); + b.add(pos); + inline for (.{ ci(k.ntok), ci(ch), ci(ns) }) |v| b.add(v); + inline for (.{ c.pm.ptr, c.pl.ptr, c.po.ptr, sinks, out }) |v| b.add(v); + b.add(@as(c_int, 1)); + b.add(ci(rows)); + try cuda.launch.launch(c.fold, .{ .grid = .{ .x = 8, .y = @intCast(hb), .z = @intCast(rows) }, .block = .{ .x = 256 }, .pdl = c.pdl }, s, &b); +} + +test "mla_c1_cuda: shared memory budgets match contract records" { + try std.testing.expectEqual(@as(u32, 81552), smemX(1, 16, false)); + try std.testing.expectEqual(@as(u32, 48896), smemX(1, 16, true)); +} diff --git a/zig/src/families/hy4_flash/mla_c2_cuda.zig b/zig/src/families/hy4_flash/mla_c2_cuda.zig new file mode 100644 index 00000000000..1f2d817837a --- /dev/null +++ b/zig/src/families/hy4_flash/mla_c2_cuda.zig @@ -0,0 +1,173 @@ +//! Tensor-core MLA query absorb (`W_UK_T`), value expand + sigmoid gate (`W_UV`), and `kv_b` tile repack. +const std = @import("std"); +const cuda = @import("cuda"); + +const Stream = cuda.Stream; +const Function = cuda.Function; + +const kl = 512; +const nd = 192; +const vd = 256; +const kvb_rows = nd + vd; + +const Cfg = struct { f: Function, bm: u32, bn: u32, threads: u32, smem: u32 }; + +pub fn cfgSmem(k: u32, mt: u32, nt: u32, warps: u32, kc: u32, stages: u32, planes: u32) u32 { + const bn = 8 * nt; + const cw = 16 * mt; + const slots = @min(stages, k / kc); + return slots * planes * bn * kc * 2 + warps * 8 * (cw + 4) * 4; +} + +fn cfg(m: *cuda.Module, name: [:0]const u8, k: u32, mt: u32, nt: u32, warps: u32, kc: u32, stages: u32, planes: u32) !Cfg { + const bn = 8 * nt; + const cw = 16 * mt; + const smem = cfgSmem(k, mt, nt, warps, kc, stages, planes); + const f = try m.function(name); + try f.allowDynamicShared(smem); + return .{ .f = f, .bm = cw * warps, .bn = bn, .threads = 32 * warps, .smem = smem }; +} + +fn dependentLaunches(d: *const cuda.Driver) bool { + var dev: cuda.abi.Device = 0; + var major: c_int = 0; + if (d.api.cuCtxGetDevice(&dev) != cuda.abi.success) return false; + return d.api.cuDeviceGetAttribute(&major, .compute_capability_major, dev) == cuda.abi.success and major >= 9; +} + +pub const C2 = struct { + mod: cuda.Module, + ab: [3]Cfg, + ex: [3]Cfg, + ex_d4: Cfg, + pdl: bool = false, + + pub fn load(d: *const cuda.Driver) !C2 { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.hy4_mla_c2); + errdefer mod.unload(); + var c: C2 = undefined; + c.mod = mod; + c.ab = .{ + try cfg(&c.mod, "hy4c2_absorb_d1_x", 192, 1, 1, 4, 192, 2, 1), + try cfg(&c.mod, "hy4c2_absorb_d2_x", 192, 1, 2, 4, 192, 2, 1), + try cfg(&c.mod, "hy4c2_absorb_p_x", 192, 2, 8, 8, 64, 3, 1), + }; + c.ex = .{ + try cfg(&c.mod, "hy4c2_expand_d1_f32lat", 512, 1, 1, 4, 512, 2, 3), + try cfg(&c.mod, "hy4c2_expand_d2_f32lat", 512, 1, 2, 4, 512, 2, 3), + try cfg(&c.mod, "hy4c2_expand_p_f32lat", 512, 2, 4, 8, 64, 3, 3), + }; + c.ex_d4 = try cfg(&c.mod, "hy4c2_expand_d4k64s2_f32lat", 512, 1, 4, 4, 64, 2, 3); + c.pdl = dependentLaunches(d); + return c; + } + + pub fn unload(c: *C2) void { + c.mod.unload(); + c.* = undefined; + } +}; + +fn grid(c: Cfg, cols: usize, heads: usize, rows: usize) u32 { + return @intCast((cols / c.bm) * heads * ((rows + c.bn - 1) / c.bn)); +} + +pub fn absorb(c: *const C2, s: Stream, q: u64, ldq: usize, rows: usize, heads: usize, wukt: u64, qa: u64, qlo: usize) !void { + const idx: usize = if (rows <= 8) 0 else if (rows <= 16) 1 else 2; + return absorbVariant(c, idx, s, q, ldq, rows, heads, wukt, qa, qlo); +} + +pub fn absorbVariant(c: *const C2, idx: usize, s: Stream, q: u64, ldq: usize, rows: usize, heads: usize, wukt: u64, qa: u64, qlo: usize) !void { + if (rows == 0) return; + const k = c.ab[idx]; + var a: cuda.Args = .{}; + a.add(q); + a.add(@as(c_int, @intCast(ldq))); + a.add(@as(c_int, @intCast(rows))); + a.add(@as(c_int, @intCast(heads))); + a.add(wukt); + a.add(qa); + a.add(@as(i64, @intCast(qlo))); + try cuda.launch.launch(k.f, .{ .grid = .{ .x = grid(k, kl, heads, rows) }, .block = .{ .x = k.threads }, .shared = k.smem, .pdl = c.pdl }, s, &a); +} + +pub fn expand(c: *const C2, s: Stream, lat: u64, rows: usize, heads: usize, wuv: u64, gate: u64, ldg: usize, out: u64) !void { + const idx: usize = if (rows <= 8) 0 else if (rows <= 16) 1 else if (rows <= 32) 2 else 3; + return expandVariant(c, idx, s, lat, rows, heads, wuv, gate, ldg, out); +} + +pub fn expandVariant(c: *const C2, idx: usize, s: Stream, lat: u64, rows: usize, heads: usize, wuv: u64, gate: u64, ldg: usize, out: u64) !void { + if (rows == 0) return; + const k = switch (idx) { + 0 => c.ex[0], + 1 => c.ex[1], + 2 => c.ex_d4, + else => c.ex[2], + }; + var a: cuda.Args = .{}; + a.add(lat); + a.add(@as(c_int, @intCast(rows))); + a.add(@as(c_int, @intCast(heads))); + a.add(wuv); + a.add(gate); + a.add(@as(c_int, @intCast(ldg))); + a.add(out); + try cuda.launch.launch(k.f, .{ .grid = .{ .x = grid(k, vd, heads, rows) }, .block = .{ .x = k.threads }, .shared = k.smem, .pdl = c.pdl }, s, &a); +} + +fn tile(out: []u16, n: usize, k: usize, ctx: anytype, comptime at: fn (@TypeOf(ctx), usize, usize) u16) void { + const ch = k / 32; + for (0..n / 16) |t| for (0..ch) |b| for (0..2) |j| for (0..32) |l| { + const u = ((t * ch + b) * 2 + j) * 32 + l; + const r = 16 * t + l / 4 + 8 * j; + const k0 = 32 * b + 8 * (l % 4); + for (0..8) |i| out[u * 8 + i] = at(ctx, r, k0 + i); + }; +} + +const Head = struct { kv: []const u16 }; +fn ukAt(h: Head, c: usize, d: usize) u16 { + return h.kv[d * kl + c]; +} +fn uvAt(h: Head, v: usize, c: usize) u16 { + return h.kv[(nd + v) * kl + c]; +} + +/// Repack `kv_b` `[heads * 448][512]` bf16 into tiled `W_UK_T` and `W_UV` on host (caller frees both). +pub fn repack(gpa: std.mem.Allocator, kvb: []const u8, heads: usize) !struct { uk: []u16, uv: []u16 } { + if (kvb.len != heads * kvb_rows * kl * 2) return error.KvbShape; + const src: []align(1) const u16 = std.mem.bytesAsSlice(u16, kvb); + const all = try gpa.alloc(u16, heads * kvb_rows * kl); + defer gpa.free(all); + for (all, src) |*o, v| o.* = v; + const uk = try gpa.alloc(u16, heads * kl * nd); + errdefer gpa.free(uk); + const uv = try gpa.alloc(u16, heads * vd * kl); + errdefer gpa.free(uv); + for (0..heads) |h| { + const hd: Head = .{ .kv = all[h * kvb_rows * kl ..][0 .. kvb_rows * kl] }; + tile(uk[h * kl * nd ..][0 .. kl * nd], kl, nd, hd, ukAt); + tile(uv[h * vd * kl ..][0 .. vd * kl], vd, kl, hd, uvAt); + } + return .{ .uk = uk, .uv = uv }; +} + +test "mla_c2_cuda: repack places every kv_b value in tiled unit order and smem matches records" { + const gpa = std.testing.allocator; + const kv = try gpa.alloc(u16, kvb_rows * kl); + defer gpa.free(kv); + for (kv, 0..) |*v, i| v.* = @truncate(i *% 2654435761 >> 7); + const r = try repack(gpa, std.mem.sliceAsBytes(kv), 1); + defer gpa.free(r.uk); + defer gpa.free(r.uv); + for (0..8) |i| try std.testing.expectEqual(kv[(8 + i) * kl + 1], r.uk[5 * 8 + i]); + for (0..8) |i| try std.testing.expectEqual(kv[(nd + 1) * kl + 8 + i], r.uv[5 * 8 + i]); + try std.testing.expectEqual(@as(u32, 5632), cfgSmem(192, 1, 1, 4, 192, 2, 1)); + try std.testing.expectEqual(@as(u32, 8704), cfgSmem(192, 1, 2, 4, 192, 2, 1)); + try std.testing.expectEqual(@as(u32, 33792), cfgSmem(192, 2, 8, 8, 64, 3, 1)); + try std.testing.expectEqual(@as(u32, 27136), cfgSmem(512, 1, 1, 4, 512, 2, 3)); + try std.testing.expectEqual(@as(u32, 51712), cfgSmem(512, 1, 2, 4, 512, 2, 3)); + try std.testing.expectEqual(@as(u32, 27136), cfgSmem(512, 1, 4, 4, 64, 2, 3)); + try std.testing.expectEqual(@as(u32, 46080), cfgSmem(512, 2, 4, 8, 64, 3, 3)); +} diff --git a/zig/src/families/hy4_flash/mla_paged_cuda.zig b/zig/src/families/hy4_flash/mla_paged_cuda.zig new file mode 100644 index 00000000000..401cd34aa96 --- /dev/null +++ b/zig/src/families/hy4_flash/mla_paged_cuda.zig @@ -0,0 +1,100 @@ +//! Hy4-flash absorbed gated MLA launchers (`hy4_mla_paged`): absorb, sinked attention, value+gate, post norm. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const c1 = @import("mla_c1_cuda.zig"); +pub const c2 = @import("mla_c2_cuda.zig"); + +const Stream = cuda.Stream; +const Function = cuda.Function; +const Args = cuda.Args; + +pub const latent: usize = 512; +pub const rope: usize = 64; +pub const nope: usize = 192; +pub const v_width: usize = 256; +pub const q_head: usize = nope + rope; +pub const kv_head: usize = nope + v_width; +pub const row: usize = latent + rope; +pub const heads_tile: usize = 8; +pub const scale: f32 = 0.0625; // (nope + rope)^-0.5, exact +pub const attn_smem: u32 = heads_tile * row * 4 + 32 * (row + 2) * 2 + heads_tile * 32 * 4 + 32 * 4 + 3 * heads_tile * 4; +pub const post_most: usize = 4096; + +pub const Kernels = struct { + mod: cuda.Module, + absorb: Function, + attn: Function, + attn_rows: Function, + value: Function, + post: Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.hy4_mla_paged); + errdefer mod.unload(); + const k: Kernels = .{ + .mod = mod, + .absorb = try mod.function("tf_hy4_mla_absorb"), + .attn = try mod.function("tf_hy4_mla_attn"), + .attn_rows = try mod.function("tf_hy4_mla_attn_rows"), + .value = try mod.function("tf_hy4_mla_value"), + .post = try mod.function("tf_hy4_mla_post"), + }; + try k.attn.allowDynamicShared(attn_smem); + try k.attn_rows.allowDynamicShared(attn_smem); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn cdiv(a: usize, b: usize) u32 { + return @intCast((a + b - 1) / b); +} + +fn int(v: usize) c_int { + return @intCast(v); +} + +pub fn absorb(f: Function, s: Stream, q: u64, qs: usize, kvb: u64, ql: u64, rows: usize, heads: usize) !void { + if (rows == 0) return; + var a: Args = .{}; + inline for (.{ q, @as(i64, @intCast(qs)), kvb, ql, int(rows), int(heads) }) |v| a.add(v); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(heads), .y = latent / 128, .z = cdiv(rows, 16) }, .block = .{ .x = 128 } }, s, &a); +} + +pub const Keys = struct { pos: u64, window: usize = 0, idx: u64 = 0, nidx: usize = 0, ring: usize = 0 }; + +pub fn attn(f: Function, s: Stream, ql: u64, qr: u64, cache: u64, keys: Keys, sinks: u64, ol: u64, rows: usize, heads: usize) !void { + if (rows == 0) return; + if (heads % heads_tile != 0) return error.MlaHeadsSplit; + var a: Args = .{}; + inline for (.{ ql, qr, cache, keys.pos, keys.idx, sinks, ol }) |v| a.add(v); + inline for (.{ heads, keys.window, keys.nidx, keys.ring }) |v| a.add(int(v)); + a.add(scale); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(heads / heads_tile) }, .block = .{ .x = 256 }, .shared = attn_smem }, s, &a); +} + +pub fn value(f: Function, s: Stream, ol: u64, kvb: u64, gate: u64, gs: usize, out: u64, os: usize, rows: usize, heads: usize) !void { + if (rows == 0) return; + var a: Args = .{}; + inline for (.{ ol, kvb, gate, @as(i64, @intCast(gs)), out, @as(i64, @intCast(os)), int(rows), int(heads) }) |v| a.add(v); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(heads), .y = v_width / 32, .z = cdiv(rows, 16) }, .block = .{ .x = 128 } }, s, &a); +} + +pub fn post(f: Function, s: Stream, parts: u64, world: usize, w: u64, out: u64, rows: usize, width: usize, eps: f32) !void { + if (rows == 0) return; + if (width > post_most or world == 0) return error.RowShape; + var a: Args = .{}; + inline for (.{ parts, @as(i64, @intCast(rows * width)), int(world), w, out, int(width) }) |v| a.add(v); + a.add(eps); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, s, &a); +} + +test "mla_paged_cuda: attention shared bytes match contract record" { + try std.testing.expectEqual(@as(u32, 56672), attn_smem); +} diff --git a/zig/src/metal/library.zig b/zig/src/metal/library.zig index 2e062eef700..3fc2484a096 100644 --- a/zig/src/metal/library.zig +++ b/zig/src/metal/library.zig @@ -77,6 +77,13 @@ pub const Library = struct { /// Metal source compiled now with `options`. pub fn fromSource(device: Device, source: []const u8, options: CompileOptions) Error!Library { + return fromSourceImpl(device, source, options, true); + } + /// The same compile, for callers whose expected failure must not log an error. + pub fn fromSourceNoLog(device: Device, source: []const u8, options: CompileOptions) Error!Library { + return fromSourceImpl(device, source, options, false); + } + fn fromSourceImpl(device: Device, source: []const u8, options: CompileOptions, comptime log_errors: bool) Error!Library { const timing = @import("profile").startup_receipt.span(.metal_source_build); defer timing.end(); built.report(source, .{ @intCast(@backingInt(options.math_mode)), @intCast(@backingInt(options.math_functions)), options.language }); @@ -89,7 +96,9 @@ pub const Library = struct { objc.msg(void, opts, "setLanguageVersion:", .{options.language}); var err: ?Id = null; const id = objc.msg(?Id, device.id, "newLibraryWithSource:options:error:", .{ str, opts, &err }); - return .{ .id = id orelse return fail("source ({d} bytes): {s}", source.len, err) }; + if (id) |value| return .{ .id = value }; + if (log_errors) return fail("source ({d} bytes): {s}", source.len, err); + return error.LibraryLoad; } pub fn function(self: Library, name: []const u8) Error!Id { diff --git a/zig/tests/contract/metal_glm_bits.zig b/zig/tests/contract/metal_glm_bits.zig index dcc889d292b..885c856cea2 100644 --- a/zig/tests/contract/metal_glm_bits.zig +++ b/zig/tests/contract/metal_glm_bits.zig @@ -234,6 +234,9 @@ pub const Loader = struct { pub fn raw(l: *Loader, _: []const u8, _: []const u8, text: []const u8) !void { try l.texts.append(l.a, try l.a.dupe(u8, text)); } + pub fn rawFrom(l: *Loader, family: []const u8, name: []const u8, _: []const []const u8, text: []const u8) !void { + try l.raw(family, name, text); + } /// `text` when the loader compiles exactly it; a contract text that drifted from the loader's is refused. pub fn require(l: *const Loader, text: []const u8) ![]const u8 { for (l.texts.items) |t| if (std.mem.eql(u8, t, text)) return text; diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index e85d079717b..3c7f1aa04eb 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -43,6 +43,7 @@ pub const Sets = struct { sparse_attn: *@import("contract_sparse_attn.zig").Set, hy4_route_rows: *@import("contract_hy4_route_rows.zig").Set, hy4_engram_fp8: *@import("contract_hy4_engram_fp8.zig").Set, + hy4_mla_paged: *@import("contract_hy4_mla_paged.zig").Set, /// 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 { @@ -131,6 +132,10 @@ pub const Sets = struct { a, list, ); + errdefer sparse_attn.deinit(); + errdefer hy4_route_rows.deinit(); + const hy4_mla_paged = try @import("contract_hy4_mla_paged.zig").Set.init(gpu, s, a, list); + errdefer hy4_mla_paged.deinit(); return .{ .gpa = gpu.gpa, .bf16_experts = bf16_experts, @@ -165,10 +170,12 @@ pub const Sets = struct { .sparse_attn = sparse_attn, .hy4_route_rows = hy4_route_rows, .hy4_engram_fp8 = hy4_engram_fp8, + .hy4_mla_paged = hy4_mla_paged, }; } pub fn deinit(sets: Sets) void { + sets.hy4_mla_paged.deinit(); sets.hy4_route_rows.deinit(); sets.sparse_attn.deinit(); sets.sparse_index.deinit(); diff --git a/zig/tests/cuda/contract_hy4_mla_c1_c2.zig b/zig/tests/cuda/contract_hy4_mla_c1_c2.zig new file mode 100644 index 00000000000..adf84efaae5 --- /dev/null +++ b/zig/tests/cuda/contract_hy4_mla_c1_c2.zig @@ -0,0 +1,403 @@ +//! Contract cases for `hy4_mla_attn_paged` (C1 2-plane, paged, long indexed list, wrong-page control) + C2 re-exports. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const hy4 = @import("hy4_mla_paged_cuda"); +const rig_ = @import("contract_rig.zig"); +const c2_k = @import("contract_hy4_mla_c2.zig"); + +pub const C2Absorb = c2_k.C2Absorb; +pub const C2Expand = c2_k.C2Expand; + +const c = core.contract.spec; +const g = core.contract.gates; +const C1 = hy4.c1.C1; + +const lat: usize = hy4.latent; +const row_w: usize = hy4.row; +const page_rows: usize = 256; +const num_streams: usize = 2; +const dsa_keys: usize = 2048; +const list_w: usize = 512; +const poison_bf16: u16 = 0xffff; + +fn zeroDepth(_: c.Shape) usize { + return 0; +} + +fn c1Depth(s: c.Shape) usize { + return row_w + @min(s.k, dsa_keys) + 16; +} + +fn buildPageTable(a: std.mem.Allocator, pages_per_stream: usize, pt_stride: usize) !struct { pt: []u32, phys_pages: usize } { + const total_mapped = num_streams * pages_per_stream; + const phys_pages = total_mapped + 2; + const perm = try a.alloc(u32, phys_pages); + defer a.free(perm); + for (0..phys_pages) |i| perm[i] = @intCast((i * 5 + 3) % phys_pages); + if (phys_pages % 5 == 0) { + for (0..phys_pages) |i| perm[i] = @intCast((phys_pages - 1 - i + 2) % phys_pages); + } + const pt = try a.alloc(u32, num_streams * pt_stride); + @memset(pt, perm[total_mapped]); + for (0..num_streams) |s| for (0..pages_per_stream) |p| { + pt[s * pt_stride + p] = perm[s * pages_per_stream + p]; + }; + return .{ .pt = pt, .phys_pages = phys_pages }; +} + +fn hasMixedFinite(out_ty: c.Elem, bytes: []const u8, n: usize) bool { + var fin: usize = 0; + var nonfin: usize = 0; + for (0..n) |i| { + if (c.classOf(c.read(out_ty, bytes, i)) == .finite) fin += 1 else nonfin += 1; + } + return fin > 0 and nonfin > 0; +} + +pub const C1Mode = enum { x16, x16_rows, x16_qreg, x16_qreg_rows, x16_paged, x16_qreg_paged, x16_paged_wrong }; + +const c1_split_shapes = [_]c.Shape{ + .{ .rows = 2, .n = 16 * lat, .k = 257 }, + .{ .rows = 1, .n = 32 * lat, .k = 513 }, + .{ .rows = 3, .n = 16 * lat, .k = 255 }, + .{ .rows = 2, .n = 16 * lat, .k = 2120 }, +}; +const c1_qreg_shapes = [_]c.Shape{ + .{ .rows = 4, .n = 16 * lat, .k = 257 }, + .{ .rows = 5, .n = 16 * lat, .k = 256 }, + .{ .rows = 4, .n = 16 * lat, .k = 2120 }, +}; +const c1_paged_shapes = [_]c.Shape{ + .{ .rows = 2, .n = 16 * lat, .k = 257 }, + .{ .rows = 2, .n = 16 * lat, .k = 255 }, + .{ .rows = 3, .n = 16 * lat, .k = 256 }, + .{ .rows = 2, .n = 16 * lat, .k = 513 }, + .{ .rows = 2, .n = 16 * lat, .k = 2120 }, +}; +const c1_qreg_paged_shapes = [_]c.Shape{ + .{ .rows = 4, .n = 16 * lat, .k = 257 }, + .{ .rows = 4, .n = 16 * lat, .k = 255 }, + .{ .rows = 4, .n = 16 * lat, .k = 256 }, + .{ .rows = 4, .n = 16 * lat, .k = 513 }, + .{ .rows = 4, .n = 16 * lat, .k = 2120 }, +}; + +pub const C1Case = struct { + rig: rig_.Rig, + c1: *const C1, + mode: C1Mode, + shape: c.Shape = undefined, + heads: usize = 0, + ctx: usize = 0, + pt_stride: usize = 0, + qa: []u16 = &.{}, + cache_contig: []u16 = &.{}, + cache_paged: []u16 = &.{}, + pos: []i32 = &.{}, + rs: []i32 = &.{}, + list_host: []i32 = &.{}, + sinks: []f32 = &.{}, + pt_dev: []u32 = &.{}, + row_ptrs: []u64 = &.{}, + in: [8]u64 = @splat(0), + out_dev: u64 = 0, + base_dev: u64 = 0, + + pub fn deinit(self: *C1Case) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *C1Case) void { + const a = self.rig.gpu.gpa; + inline for (.{ &self.qa, &self.cache_contig, &self.cache_paged }) |s| { + a.free(s.*); + s.* = &.{}; + } + inline for (.{ &self.pos, &self.rs, &self.list_host }) |s| { + a.free(s.*); + s.* = &.{}; + } + a.free(self.sinks); + a.free(self.pt_dev); + a.free(self.row_ptrs); + self.sinks = &.{}; + self.pt_dev = &.{}; + self.row_ptrs = &.{}; + } + + fn isPaged(self: *const C1Case) bool { + return self.mode == .x16_paged or self.mode == .x16_qreg_paged or self.mode == .x16_paged_wrong; + } + + fn isPerRow(self: *const C1Case) bool { + return self.mode == .x16_rows or self.mode == .x16_qreg_rows; + } + + fn singleSplit(self: *const C1Case) bool { + return self.mode == .x16_qreg or self.mode == .x16_qreg_rows or self.mode == .x16_qreg_paged; + } + + pub fn kernel(self: *C1Case) g.Kernel { + const name = switch (self.mode) { + .x16 => "cuda hy4_mla_attn_paged hy4_mla_dec_x16 + hy4_mla_fold (exact 2-plane split+fold)", + .x16_rows => "cuda hy4_mla_attn_paged hy4_mla_dec_x16_rows + hy4_mla_fold (per-row caches)", + .x16_qreg => "cuda hy4_mla_attn_paged hy4_mla_dec_x16_qreg (register-resident single-split)", + .x16_qreg_rows => "cuda hy4_mla_attn_paged hy4_mla_dec_x16_qreg_rows (qreg per-row caches)", + .x16_paged => "cuda hy4_mla_attn_paged hy4_mla_dec_x16_paged + hy4_mla_fold (non-identity 256-row pages)", + .x16_qreg_paged => "cuda hy4_mla_attn_paged hy4_mla_dec_x16_qreg_paged (qreg non-identity pages)", + .x16_paged_wrong => "control: hy4_mla_attn_paged hy4_mla_dec_x16_paged wrong page table", + }; + const is_cmp = self.isPaged() or self.isPerRow(); + const s: c.Spec = .{ + .name = name, + .accum = .none, + .depth = zeroDepth, + .out = .f32, + .nan = if (is_cmp) .{ .stated = "bytes match equivalent contiguous C1 launch" } else .propagate, + .served = switch (self.mode) { + .x16, .x16_rows => &c1_split_shapes, + .x16_qreg, .x16_qreg_rows => &c1_qreg_shapes, + .x16_paged, .x16_paged_wrong => &c1_paged_shapes, + .x16_qreg_paged => &c1_qreg_paged_shapes, + }, + }; + return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.mode == .x16_paged_wrong) .shapes else null }; + } + + const vt = g.hooks(C1Case); + + pub fn count(self: *const C1Case) usize { + return self.shape.rows * self.heads * lat; + } + + pub fn prepare(self: *C1Case, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n % lat != 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.heads = shape.n / lat; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows = shape.rows; + const nkeys = shape.k; + self.ctx = nkeys + 16; + const qlo = rows * self.heads * row_w; + self.qa = try a.alloc(u16, 2 * qlo); + for (0..qlo) |i| { + const x = (rng.float(f32) * 2 - 1) * 0.5; + const hi = c.toBf16(x); + const lo = c.toBf16(x - @as(f32, @floatCast(c.fromBf16(hi)))); + self.qa[i] = hi; + self.qa[qlo + i] = lo; + } + self.pos = try a.alloc(i32, rows); + self.rs = try a.alloc(i32, rows); + self.list_host = try a.alloc(i32, rows * list_w); + self.sinks = try a.alloc(f32, self.heads); + for (self.pos, 0..) |*p, r| p.* = @intCast(nkeys - 1 - @min(r, 2)); + for (self.rs, 0..) |*s, r| s.* = @intCast(if (self.isPaged() or self.isPerRow()) (r & 1) else 0); + // Non-monotonic group list spanning all pages plus -1 sentinels for long-context (pos >= 2048) rows. + const max_grp: usize = @max(@as(usize, 1), nkeys / 4); + for (0..rows) |r| for (0..list_w) |gi| { + self.list_host[r * list_w + gi] = if ((gi % 37) == 36) -1 else @intCast((gi * 7 + r * 13) % max_grp); + }; + for (self.sinks) |*s| s.* = rng.float(f32) * 2 - 1; + const n_streams: usize = if (self.isPaged() or self.isPerRow()) num_streams else 1; + self.cache_contig = try a.alloc(u16, n_streams * self.ctx * row_w); + @memset(self.cache_contig, poison_bf16); + const pages_per_stream = @max(@as(usize, 2), (nkeys + page_rows - 1) / page_rows); + self.pt_stride = pages_per_stream + 1; + const tbl = try buildPageTable(a, pages_per_stream, self.pt_stride); + defer a.free(tbl.pt); + self.pt_dev = try a.dupe(u32, tbl.pt); + if (self.mode == .x16_paged_wrong) { + std.mem.swap(u32, &self.pt_dev[0], &self.pt_dev[1]); + } + self.cache_paged = try a.alloc(u16, tbl.phys_pages * page_rows * row_w); + @memset(self.cache_paged, poison_bf16); + for (0..n_streams) |st| for (0..pages_per_stream) |pg| { + const phys_base = @as(usize, tbl.pt[st * self.pt_stride + pg]) * page_rows * row_w; + for (self.cache_paged[phys_base .. phys_base + page_rows * row_w]) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.5); + for (0..page_rows) |slot| { + const t = pg * page_rows + slot; + if (t < nkeys) { + const src = self.cache_paged[phys_base + slot * row_w ..][0..row_w]; + const dst = self.cache_contig[(st * self.ctx + t) * row_w ..][0..row_w]; + @memcpy(dst, src); + } + } + }; + if (fill == .nonfinite) { + self.qa[0] = c.toBf16(std.math.nan(f32)); + self.qa[qlo] = 0; + if (self.heads > 1) { + self.sinks[1] = std.math.nan(f32); + } + } + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.qa)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.cache_contig)); + self.in[2] = try self.rig.input(std.mem.sliceAsBytes(self.cache_paged)); + self.in[3] = try self.rig.input(std.mem.sliceAsBytes(self.pos)); + self.in[4] = try self.rig.input(std.mem.sliceAsBytes(self.rs)); + self.in[5] = try self.rig.input(std.mem.sliceAsBytes(self.sinks)); + self.in[6] = try self.rig.input(std.mem.sliceAsBytes(self.pt_dev)); + self.in[7] = try self.rig.input(std.mem.sliceAsBytes(self.list_host)); + if (self.isPerRow()) { + self.row_ptrs = try a.alloc(u64, rows); + const stream_bytes: u64 = @intCast(self.ctx * row_w * 2); + for (self.row_ptrs, 0..) |*ptr, r| ptr.* = self.in[1] + @as(u64, @intCast(self.rs[r])) * stream_bytes; + self.in[2] = try self.rig.input(std.mem.sliceAsBytes(self.row_ptrs)); + } + self.out_dev = try self.rig.output(self.count() * 4); + self.base_dev = try self.rig.scratch(self.count() * 4); + return true; + } + + pub fn run(self: *C1Case) !void { + const qlo = self.shape.rows * self.heads * row_w; + if (self.isPerRow()) { + try hy4.c1.attnRows(self.c1, self.rig.s, self.in[0], qlo, self.heads, self.in[2], .{ + .kind = 1, + .ring = self.ctx, + .list = self.in[7], + .single_split = self.singleSplit(), + }, self.in[3], self.in[5], self.out_dev, self.shape.rows); + } else { + try hy4.c1.attn(self.c1, self.rig.s, self.in[0], qlo, self.heads, if (self.isPaged()) self.in[2] else self.in[1], .{ + .kind = 1, + .ring = self.ctx, + .list = self.in[7], + .single_split = self.singleSplit(), + .page_table = if (self.isPaged()) self.in[6] else 0, + .pt_stride = if (self.isPaged()) self.pt_stride else 0, + .row_stream = self.in[4], + }, self.in[3], self.in[5], self.out_dev, self.shape.rows); + } + try self.rig.s.synchronize(); + } + + pub fn replaced(self: *C1Case) ![]const u8 { + try (cuda.DeviceBuffer{ .d = self.rig.gpu.d, .ptr = self.base_dev, .len = self.count() * 4 }).fill8(0xff, self.rig.s.handle); + const qlo = self.shape.rows * self.heads * row_w; + try hy4.c1.attn(self.c1, self.rig.s, self.in[0], qlo, self.heads, self.in[1], .{ + .kind = 1, + .ring = self.ctx, + .list = self.in[7], + .single_split = self.singleSplit(), + .row_stream = self.in[4], + }, self.in[3], self.in[5], self.base_dev, self.shape.rows); + return self.rig.bytes(self.base_dev, self.count() * 4); + } + + pub fn check(self: *C1Case, gate: g.Gate) !?[]const u8 { + if (gate != .nonfinite and gate != .shapes) return null; + const a = self.rig.gpu.gpa; + const n = self.count(); + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + if (self.isPaged() or self.isPerRow()) { + const base = try self.replaced(); + if (gate == .nonfinite and !hasMixedFinite(.f32, base, n)) { + return "non-finite input did not produce mixed finite/non-finite outputs"; + } + if (!std.mem.eql(u8, got, base)) { + return if (gate == .nonfinite) + "paged/per-row non-finite output bytes differ from contiguous baseline" + else + "paged/per-row output bytes differ from contiguous baseline"; + } + if (gate == .nonfinite) return null; + } + const want = try a.alloc(f64, n); + defer a.free(want); + const mag = try a.alloc(f64, n); + defer a.free(mag); + try self.reference(want, mag); + if (gate == .nonfinite) { + var planted: usize = 0; + for (want, 0..) |w, i| { + if (c.classOf(w) != .finite) planted += 1; + if (c.classOf(c.read(.f32, got, i)) != c.classOf(w)) return "C1 non-finite class mismatch"; + } + if (planted == 0 or planted == n) return "C1 non-finite test lacked mixed finite/non-finite outputs"; + return null; + } + const allow = try a.alloc(f64, n); + defer a.free(allow); + try self.bounds(want, mag, allow); + for (want, allow, 0..) |w, limit, i| { + const val = c.read(.f32, got, i); + const q = if (val == w) 0 else @abs(val - w) / limit; + if (!(q <= 1)) return "C1 output exceeded float64 bound"; + } + return null; + } + + pub fn reference(self: *C1Case, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + const qlo = self.shape.rows * self.heads * row_w; + const scores = try a.alloc(f64, dsa_keys); + defer a.free(scores); + const kpos = try a.alloc(i32, dsa_keys); + defer a.free(kpos); + for (0..self.shape.rows) |r| { + const st: usize = @intCast(self.rs[r]); + const prow = self.pos[r]; + const use_list = prow >= @as(i32, dsa_keys); + const n: usize = if (use_list) dsa_keys else @as(usize, @intCast(prow)) + 1; + for (0..n) |i| { + if (!use_list) { + kpos[i] = @intCast(i); + } else { + const gi = self.list_host[r * list_w + (i >> 2)]; + const kp: i32 = if (gi < 0) -1 else 4 * gi + @as(i32, @intCast(i & 3)); + kpos[i] = if (kp >= 0 and kp <= prow) kp else -1; + } + } + for (0..self.heads) |h| { + const q_base = (r * self.heads + h) * row_w; + var top: f64 = self.sinks[h]; + for (0..n) |i| { + if (kpos[i] < 0) { + scores[i] = -std.math.inf(f64); + continue; + } + const k_base = (st * self.ctx + @as(usize, @intCast(kpos[i]))) * row_w; + var dot: f64 = 0; + for (0..row_w) |d| { + const qv = c.fromBf16(self.qa[q_base + d]) + c.fromBf16(self.qa[qlo + q_base + d]); + dot += qv * c.fromBf16(self.cache_contig[k_base + d]); + } + scores[i] = dot * 0.0625; + top = if (std.math.isNan(top) or std.math.isNan(scores[i])) std.math.nan(f64) else @max(top, scores[i]); + } + var den: f64 = @exp(self.sinks[h] - top); + for (0..n) |i| { + if (kpos[i] >= 0) den += @exp(scores[i] - top); + } + const o_base = (r * self.heads + h) * lat; + for (0..lat) |d| { + var acc: f64 = 0; + var amag: f64 = 0; + for (0..n) |i| { + if (kpos[i] < 0) continue; + const w = @exp(scores[i] - top) / den; + const kv = c.fromBf16(self.cache_contig[(st * self.ctx + @as(usize, @intCast(kpos[i]))) * row_w + d]); + acc += w * kv; + amag += @abs(w * kv); + } + want[o_base + d] = acc; + mag[o_base + d] = @max(amag, 1.0); + } + } + } + } + + pub fn bounds(self: *const C1Case, want: []const f64, mag: []const f64, allow: []f64) !void { + const spec: c.Spec = .{ .name = "", .accum = .f32, .depth = c1Depth, .ops = 16, .out = .f32, .served = &c1_split_shapes }; + for (allow, want, mag) |*l, w, m| l.* = c.bound(spec, self.shape, w, m) + 0x1p-14 * m; + } +}; diff --git a/zig/tests/cuda/contract_hy4_mla_c2.zig b/zig/tests/cuda/contract_hy4_mla_c2.zig new file mode 100644 index 00000000000..8b87fd562b6 --- /dev/null +++ b/zig/tests/cuda/contract_hy4_mla_c2.zig @@ -0,0 +1,351 @@ +//! Contract cases for `hy4_mla_c2`: same-engine exact byte comparisons across all absorb/expand variants + fp64 bounds. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const hy4 = @import("hy4_mla_paged_cuda"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const C2 = hy4.c2.C2; + +const lat: usize = hy4.latent; +const row_w: usize = hy4.row; +const nope_dim: usize = 192; +const v_dim: usize = 256; +const kvb_rows: usize = nope_dim + v_dim; + +fn zeroDepth(_: c.Shape) usize { + return 0; +} + +fn c2ExpandDepth(_: c.Shape) usize { + return lat + 16; +} + +const c2_absorb_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 4 * lat, .k = nope_dim }, + .{ .rows = 9, .n = 4 * lat, .k = nope_dim }, + .{ .rows = 17, .n = 4 * lat, .k = nope_dim }, +}; + +pub const C2Absorb = struct { + rig: rig_.Rig, + c2: *const C2, + shape: c.Shape = undefined, + heads: usize = 0, + qb: []u16 = &.{}, + kvb: []u16 = &.{}, + wukt: []u16 = &.{}, + in: [2]u64 = @splat(0), + out_dev: u64 = 0, + + pub fn deinit(self: *C2Absorb) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *C2Absorb) void { + const a = self.rig.gpu.gpa; + inline for (.{ &self.qb, &self.kvb, &self.wukt }) |s| { + a.free(s.*); + s.* = &.{}; + } + } + + pub fn kernel(self: *C2Absorb) g.Kernel { + const s: c.Spec = .{ + .name = "cuda hy4_mla_c2 hy4c2_absorb (d1_x, d2_x, p_x exact 2-plane)", + .accum = .none, + .depth = zeroDepth, + .out = .bf16, + .nan = .{ .stated = "2-plane bf16 sum matches float64 W_UK_T projection, variant bytes match, preserves NaN" }, + .served = &c2_absorb_shapes, + }; + return .{ .spec = s, .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(C2Absorb); + + pub fn count(self: *const C2Absorb) usize { + return 2 * self.shape.rows * self.heads * row_w; + } + + pub fn reference(_: *C2Absorb, _: []f64, _: []f64) !void {} + + pub fn prepare(self: *C2Absorb, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k != nope_dim or shape.n % lat != 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.heads = shape.n / lat; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const ldq = self.heads * 256; + self.qb = try a.alloc(u16, shape.rows * ldq); + self.kvb = try a.alloc(u16, self.heads * kvb_rows * lat); + for (self.qb) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.5); + for (self.kvb) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.5); + if (fill == .nonfinite) { + self.qb[0] = c.toBf16(std.math.nan(f32)); + } + const rep = try hy4.c2.repack(a, std.mem.sliceAsBytes(self.kvb), self.heads); + a.free(rep.uv); + self.wukt = rep.uk; + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.qb)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.wukt)); + self.out_dev = try self.rig.output(self.count() * 2); + return true; + } + + pub fn run(self: *C2Absorb) !void { + const out_b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.out_dev, .len = self.count() * 2 }; + try out_b.fill8(0xff, self.rig.s.handle); + const qlo = self.shape.rows * self.heads * row_w; + try hy4.c2.absorb(self.c2, self.rig.s, self.in[0], self.heads * 256, self.shape.rows, self.heads, self.in[1], self.out_dev, qlo); + try self.rig.s.synchronize(); + } + + pub fn check(self: *C2Absorb, gate: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const raw = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(raw); + const words: []align(1) const u16 = std.mem.bytesAsSlice(u16, raw); + const qlo = self.shape.rows * self.heads * row_w; + const ldq = self.heads * 256; + // Same-engine byte comparison: all 3 absorb variants (d1_x, d2_x, p_x) must emit identical hi/lo bytes. + var cmp = try cuda.DeviceBuffer.alloc(self.rig.gpu.d, raw.len); + defer cmp.free(); + const cmp_host = try a.alloc(u8, raw.len); + defer a.free(cmp_host); + for (0..3) |vi| { + try cmp.fill8(0xff, self.rig.s.handle); + try hy4.c2.absorbVariant(self.c2, vi, self.rig.s, self.in[0], ldq, self.shape.rows, self.heads, self.in[1], cmp.ptr, qlo); + try self.rig.s.synchronize(); + try cmp.download(0, cmp_host); + if (!std.mem.eql(u8, raw, cmp_host)) return "hy4c2_absorb variant bytes differ across d1_x/d2_x/p_x"; + } + // Row-invariance byte comparison against R=1 d1_x for multi-row shapes. + if (self.shape.rows > 1) { + const row_elems = self.heads * row_w; + var solo = try cuda.DeviceBuffer.alloc(self.rig.gpu.d, 2 * row_elems * 2); + defer solo.free(); + const solo_h = try a.alloc(u8, 2 * row_elems * 2); + defer a.free(solo_h); + for ([_]usize{ 0, self.shape.rows / 2, self.shape.rows - 1 }) |ri| { + try solo.fill8(0xff, self.rig.s.handle); + try hy4.c2.absorbVariant(self.c2, 0, self.rig.s, self.in[0] + ri * ldq * 2, ldq, 1, self.heads, self.in[1], solo.ptr, row_elems); + try self.rig.s.synchronize(); + try solo.download(0, solo_h); + const hi_off = ri * row_elems * 2; + const lo_off = (qlo + ri * row_elems) * 2; + if (!std.mem.eql(u8, raw[hi_off..][0 .. row_elems * 2], solo_h[0 .. row_elems * 2]) or + !std.mem.eql(u8, raw[lo_off..][0 .. row_elems * 2], solo_h[row_elems * 2 ..][0 .. row_elems * 2])) + return "hy4c2_absorb multi-row bytes differ from R=1 d1_x"; + } + } + var fin: usize = 0; + var nonfin: usize = 0; + for (0..self.shape.rows) |r| for (0..self.heads) |h| { + const o_base = (r * self.heads + h) * row_w; + for (lat..row_w) |d| { + if (words[o_base + d] != 0 or words[qlo + o_base + d] != 0) return "absorb wrote past latent columns"; + } + for (0..lat) |col| { + var acc: f64 = 0; + var mag: f64 = 0; + for (0..nope_dim) |k| { + const x = c.fromBf16(self.qb[r * ldq + h * 256 + k]) * c.fromBf16(self.kvb[(h * kvb_rows + k) * lat + col]); + acc += x; + mag += @abs(x); + } + const hi = c.fromBf16(words[o_base + col]); + const lo = c.fromBf16(words[qlo + o_base + col]); + const got = if (std.math.isFinite(hi)) hi + lo else hi; + if (gate == .nonfinite) { + if (c.classOf(acc) == .finite) fin += 1 else nonfin += 1; + if (c.classOf(got) != c.classOf(acc)) return "absorb non-finite class mismatch"; + } else { + const lim = c.gamma(nope_dim, 0x1p-24) * mag + 0x1p-14 * @abs(acc) + 0x1p-20; + if (!(std.math.isFinite(got) and @abs(got - acc) <= lim)) return "absorb 2-plane sum exceeded float64 bound"; + } + } + }; + if (gate == .nonfinite and (fin == 0 or nonfin == 0)) return "absorb non-finite test lacked mixed finite/non-finite outputs"; + return null; + } +}; + +const c2_expand_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 4 * v_dim, .k = lat }, + .{ .rows = 9, .n = 4 * v_dim, .k = lat }, + .{ .rows = 17, .n = 4 * v_dim, .k = lat }, + .{ .rows = 33, .n = 4 * v_dim, .k = lat }, +}; + +pub const C2Expand = struct { + rig: rig_.Rig, + c2: *const C2, + shape: c.Shape = undefined, + heads: usize = 0, + lat_in: []f32 = &.{}, + gate_in: []u16 = &.{}, + kvb: []u16 = &.{}, + wuv: []u16 = &.{}, + in: [3]u64 = @splat(0), + out_dev: u64 = 0, + + pub fn deinit(self: *C2Expand) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *C2Expand) void { + const a = self.rig.gpu.gpa; + a.free(self.lat_in); + self.lat_in = &.{}; + inline for (.{ &self.gate_in, &self.kvb, &self.wuv }) |s| { + a.free(s.*); + s.* = &.{}; + } + } + + pub fn kernel(self: *C2Expand) g.Kernel { + const s: c.Spec = .{ + .name = "cuda hy4_mla_c2 hy4c2_expand_f32lat (d1, d2, d4k64s2, p + sigmoid gate)", + .accum = .none, + .depth = zeroDepth, + .ops = 6, + .out = .bf16, + .served = &c2_expand_shapes, + }; + return .{ .spec = s, .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(C2Expand); + + pub fn count(self: *const C2Expand) usize { + return self.shape.rows * self.heads * v_dim; + } + + pub fn prepare(self: *C2Expand, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k != lat or shape.n % v_dim != 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.heads = shape.n / v_dim; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const ldg = self.heads * v_dim; + self.lat_in = try a.alloc(f32, shape.rows * self.heads * lat); + self.gate_in = try a.alloc(u16, shape.rows * ldg); + self.kvb = try a.alloc(u16, self.heads * kvb_rows * lat); + for (self.lat_in) |*v| v.* = (rng.float(f32) * 2 - 1) * 0.5; + for (self.gate_in) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 2.0); + for (self.kvb) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 0.5); + if (fill == .nonfinite) { + self.lat_in[0] = std.math.nan(f32); + self.gate_in[v_dim] = c.toBf16(std.math.nan(f32)); + } + const rep = try hy4.c2.repack(a, std.mem.sliceAsBytes(self.kvb), self.heads); + a.free(rep.uk); + self.wuv = rep.uv; + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.lat_in)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.wuv)); + self.in[2] = try self.rig.input(std.mem.sliceAsBytes(self.gate_in)); + self.out_dev = try self.rig.output(self.count() * 2); + return true; + } + + pub fn run(self: *C2Expand) !void { + try hy4.c2.expand(self.c2, self.rig.s, self.in[0], self.shape.rows, self.heads, self.in[1], self.in[2], self.heads * v_dim, self.out_dev); + try self.rig.s.synchronize(); + } + + pub fn check(self: *C2Expand, gate: g.Gate) !?[]const u8 { + if (gate != .shapes and gate != .nonfinite) return null; + const a = self.rig.gpu.gpa; + const raw = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(raw); + const ldg = self.heads * v_dim; + // Same-engine byte comparison: all 4 expand variants (d1, d2, d4k64s2, p) must emit identical bf16 bytes. + var cmp = try cuda.DeviceBuffer.alloc(self.rig.gpu.d, raw.len); + defer cmp.free(); + const cmp_host = try a.alloc(u8, raw.len); + defer a.free(cmp_host); + for (0..4) |vi| { + try cmp.fill8(0xff, self.rig.s.handle); + try hy4.c2.expandVariant(self.c2, vi, self.rig.s, self.in[0], self.shape.rows, self.heads, self.in[1], self.in[2], ldg, cmp.ptr); + try self.rig.s.synchronize(); + try cmp.download(0, cmp_host); + if (!std.mem.eql(u8, raw, cmp_host)) return "hy4c2_expand_f32lat variant bytes differ across d1/d2/d4k64s2/p"; + } + // Row-invariance byte comparison against R=1 d1 for multi-row shapes. + if (self.shape.rows > 1) { + const row_bytes = ldg * 2; + var solo = try cuda.DeviceBuffer.alloc(self.rig.gpu.d, row_bytes); + defer solo.free(); + const solo_h = try a.alloc(u8, row_bytes); + defer a.free(solo_h); + for ([_]usize{ 0, self.shape.rows / 2, self.shape.rows - 1 }) |ri| { + try solo.fill8(0xff, self.rig.s.handle); + try hy4.c2.expandVariant(self.c2, 0, self.rig.s, self.in[0] + ri * self.heads * lat * 4, 1, self.heads, self.in[1], self.in[2] + ri * row_bytes, ldg, solo.ptr); + try self.rig.s.synchronize(); + try solo.download(0, solo_h); + if (!std.mem.eql(u8, raw[ri * row_bytes ..][0..row_bytes], solo_h)) return "hy4c2_expand_f32lat multi-row bytes differ from R=1 d1"; + } + } + const n = self.count(); + const want = try a.alloc(f64, n); + defer a.free(want); + const mag = try a.alloc(f64, n); + defer a.free(mag); + try self.reference(want, mag); + if (gate == .nonfinite) { + var planted: usize = 0; + for (want, 0..) |w, i| { + if (c.classOf(w) != .finite) planted += 1; + if (c.classOf(c.read(.bf16, raw, i)) != c.classOf(w)) return "hy4c2_expand_f32lat non-finite class mismatch"; + } + if (planted == 0 or planted == n) return "hy4c2_expand_f32lat non-finite test lacked mixed finite/non-finite outputs"; + } else { + const allow = try a.alloc(f64, n); + defer a.free(allow); + try self.bounds(want, mag, allow); + for (want, allow, 0..) |w, limit, i| { + const got = c.read(.bf16, raw, i); + const q = if (got == w) 0 else @abs(got - w) / limit; + if (!(q <= 1)) return "hy4c2_expand_f32lat output exceeded float64 bound"; + } + } + return null; + } + + pub fn reference(self: *C2Expand, want: []f64, mag: []f64) !void { + const ldg = self.heads * v_dim; + for (0..self.shape.rows) |r| for (0..self.heads) |h| { + const l_base = (r * self.heads + h) * lat; + for (0..v_dim) |v| { + var acc: f64 = 0; + var amag: f64 = 0; + for (0..lat) |col| { + const x = @as(f64, self.lat_in[l_base + col]) * c.fromBf16(self.kvb[(h * kvb_rows + nope_dim + v) * lat + col]); + acc += x; + amag += @abs(x); + } + const gval = c.fromBf16(self.gate_in[r * ldg + h * v_dim + v]); + const sig = 1.0 / (1.0 + @exp(-gval)); + const idx = (r * self.heads + h) * v_dim + v; + want[idx] = acc * sig; + mag[idx] = amag * @abs(sig); + } + }; + } + + pub fn bounds(self: *const C2Expand, want: []const f64, mag: []const f64, allow: []f64) !void { + const spec: c.Spec = .{ .name = "", .accum = .f32, .depth = c2ExpandDepth, .ops = 8, .out = .bf16, .served = &c2_expand_shapes }; + for (allow, want, mag) |*l, w, m| l.* = c.bound(spec, self.shape, w, m); + } +}; diff --git a/zig/tests/cuda/contract_hy4_mla_paged.zig b/zig/tests/cuda/contract_hy4_mla_paged.zig new file mode 100644 index 00000000000..3ae5348cb2f --- /dev/null +++ b/zig/tests/cuda/contract_hy4_mla_paged.zig @@ -0,0 +1,161 @@ +//! Hy4-flash paged MLA CUDA contract set (`hy4_mla_paged`): served forms and 20 planted controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const hy4 = @import("hy4_mla_paged_cuda"); +const options = @import("contract_options"); +const check = @import("check.zig"); +const attn_k = @import("contract_hy4_mla_paged_attn.zig"); +const proj_k = @import("contract_hy4_mla_paged_proj.zig"); +const c12_k = @import("contract_hy4_mla_c1_c2.zig"); + +const g = core.contract.gates; + +pub const eps: f32 = 1e-5; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +pub const Fault = enum { + none, + bad_nan, + bad_repeat, + bad_tail, + bad_sums, + + pub fn gate(f: Fault) ?g.Gate { + return switch (f) { + .none => null, + .bad_nan => .nonfinite, + .bad_repeat => .repeat, + .bad_tail => .shapes, + .bad_sums => .sums, + }; + } +}; + +const faults = [_]Fault{ .bad_nan, .bad_repeat, .bad_tail, .bad_sums }; +const kernels = [_][]const u8{ "absorb", "attn", "attn_rows", "value", "post" }; + +fn symbolOf(comptime k: []const u8, comptime f: Fault) [:0]const u8 { + return "tf_ctl_hy4_mla_" ++ k ++ "_" ++ @tagName(f); +} + +fn labelOf(comptime k: []const u8, comptime f: Fault) []const u8 { + const what = switch (f) { + .none => "production", + .bad_nan => "reads a NaN input as 0", + .bad_repeat => "bumps its first input every run", + .bad_tail => "leaves its reduction's last term out", + .bad_sums => "keeps its running sums in fp16", + }; + return "control: hy4_mla_paged tf_hy4_mla_" ++ k ++ " " ++ what; +} + +const labels = blk: { + var out: [kernels.len * faults.len][]const u8 = undefined; + for (kernels, 0..) |k, i| for (faults, 0..) |f, j| { + out[i * faults.len + j] = labelOf(k, f); + }; + break :blk out; +}; + +pub fn controlName(k: []const u8, f: Fault) []const u8 { + for (kernels, 0..) |name, i| if (std.mem.eql(u8, name, k)) for (faults, 0..) |fault, j| { + if (fault == f) return labels[i * faults.len + j]; + }; + return "control: hy4_mla_paged unknown"; +} + +pub const Set = struct { + gpa: std.mem.Allocator, + k: hy4.Kernels, + c1: hy4.c1.C1, + c2: hy4.c2.C2, + ctl: ?cuda.Module = null, + attns: [5]attn_k.Attn = undefined, + projs: [5]proj_k.Proj = undefined, + c1_cases: [7]c12_k.C1Case = undefined, + c2_absorb: c12_k.C2Absorb = undefined, + c2_expand: c12_k.C2Expand = undefined, + attn_ctl: [2 * faults.len]attn_k.Attn = undefined, + proj_ctl: [3 * faults.len]proj_k.Proj = undefined, + has_ctl: bool = false, + + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const self = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(self); + var k = try hy4.Kernels.load(gpu.d); + errdefer k.unload(); + var c1 = try hy4.c1.C1.load(gpu.d); + errdefer c1.unload(); + var c2 = try hy4.c2.C2.load(gpu.d); + errdefer c2.unload(); + const ctl = if (options.controls) try cuda.Module.load(gpu.d, &controls.bytes) else null; + self.* = .{ .gpa = gpu.gpa, .k = k, .c1 = c1, .c2 = c2, .ctl = ctl }; + errdefer if (self.ctl) |*m| m.unload(); + const rig: @import("contract_rig.zig").Rig = .{ .gpu = gpu, .s = s }; + for (&self.attns, std.enums.values(attn_k.Form)) |*x, form| { + x.* = .{ .rig = rig, .form = form, .f = if (form == .rows) self.k.attn_rows else self.k.attn }; + } + const kinds = [_]proj_k.Kind{ .absorb, .value, .post, .post, .post }; + const worlds = [_]usize{ 1, 1, 1, 2, 4 }; + for (&self.projs, kinds, worlds) |*x, kind, world| { + x.* = .{ .rig = rig, .kind = kind, .f = self.fn_(kind), .world = world }; + } + for (&self.c1_cases, std.enums.values(c12_k.C1Mode)) |*x, mode| { + x.* = .{ .rig = rig, .c1 = &self.c1, .mode = mode }; + } + self.c2_absorb = .{ .rig = rig, .c2 = &self.c2 }; + self.c2_expand = .{ .rig = rig, .c2 = &self.c2 }; + for (&self.attns) |*x| try list.append(a, x.kernel()); + for (&self.projs) |*x| try list.append(a, x.kernel()); + for (&self.c1_cases) |*x| try list.append(a, x.kernel()); + try list.append(a, self.c2_absorb.kernel()); + try list.append(a, self.c2_expand.kernel()); + if (self.ctl) |cm| { + inline for (faults, 0..) |fault, j| { + const attn_fn = try cm.function(comptime symbolOf("attn", fault)); + try attn_fn.allowDynamicShared(hy4.attn_smem); + self.attn_ctl[j] = .{ .rig = rig, .form = .window, .f = attn_fn, .fault = fault }; + const rows_fn = try cm.function(comptime symbolOf("attn_rows", fault)); + try rows_fn.allowDynamicShared(hy4.attn_smem); + self.attn_ctl[faults.len + j] = .{ .rig = rig, .form = .rows, .f = rows_fn, .fault = fault }; + inline for ([_]proj_k.Kind{ .absorb, .value, .post }, 0..) |kind, i| { + const f = try cm.function(comptime symbolOf(@tagName(kind), fault)); + self.proj_ctl[i * faults.len + j] = .{ .rig = rig, .kind = kind, .f = f, .fault = fault, .world = if (kind == .post) 2 else 1 }; + } + } + self.has_ctl = true; + for (&self.attn_ctl) |*x| try list.append(a, x.kernel()); + for (&self.proj_ctl) |*x| try list.append(a, x.kernel()); + } + return self; + } + + fn fn_(self: *const Set, kind: proj_k.Kind) cuda.Function { + return switch (kind) { + .absorb => self.k.absorb, + .value => self.k.value, + .post => self.k.post, + }; + } + + pub fn deinit(self: *Set) void { + if (self.has_ctl) { + for (&self.attn_ctl) |*x| x.deinit(); + for (&self.proj_ctl) |*x| x.deinit(); + } + for (&self.attns) |*x| x.deinit(); + for (&self.projs) |*x| x.deinit(); + for (&self.c1_cases) |*x| x.deinit(); + self.c2_absorb.deinit(); + self.c2_expand.deinit(); + if (self.ctl) |*m| m.unload(); + self.c2.unload(); + self.c1.unload(); + self.k.unload(); + self.gpa.destroy(self); + } +}; diff --git a/zig/tests/cuda/contract_hy4_mla_paged_attn.zig b/zig/tests/cuda/contract_hy4_mla_paged_attn.zig new file mode 100644 index 00000000000..d5e1b5932f2 --- /dev/null +++ b/zig/tests/cuda/contract_hy4_mla_paged_attn.zig @@ -0,0 +1,323 @@ +//! Hy4-flash paged MLA attention contract: sliding windows, ring caches, causal spans, and index lists. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const hy4 = @import("hy4_mla_paged_cuda"); +const rig_ = @import("contract_rig.zig"); +const set = @import("contract_hy4_mla_paged.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sumIn = contract.rows.sumIn; +const lat = hy4.latent; +const rope = hy4.rope; +const row = hy4.row; +const chunk = 32; // tf_hy4::kKC +const window = 512; +const ring = 1024; +const u: f64 = 0x1p-24; + +/// Keys by a row's window (linear or 1,024-slot ring), causal span or list; `rows`: spans, a cache a row. +pub const Form = enum { window, ring, dense, list, rows }; + +/// rows x a row's outputs (heads x 512) x the keys the last row sees (a list's entries). +fn depth(s: c.Shape) usize { + return row + s.k + s.k / chunk + 8; +} + +const window_shapes = [_]c.Shape{ .{ .rows = 16, .n = 16 * lat, .k = window }, .{ .rows = 1, .n = 64 * lat, .k = window }, .{ .rows = 5, .n = 32 * lat, .k = 300 } }; +const ring_shapes = [_]c.Shape{ .{ .rows = 16, .n = 32 * lat, .k = window }, .{ .rows = 3, .n = 64 * lat, .k = window } }; +const dense_shapes = [_]c.Shape{ .{ .rows = 8, .n = 16 * lat, .k = 2048 }, .{ .rows = 1, .n = 32 * lat, .k = 1500 }, .{ .rows = 33, .n = 8 * lat, .k = 700 } }; +const rows_shapes = [_]c.Shape{ .{ .rows = 8, .n = 16 * lat, .k = 1024 }, .{ .rows = 3, .n = 32 * lat, .k = 700 }, .{ .rows = 16, .n = 8 * lat, .k = 300 } }; +const list_shapes = [_]c.Shape{ .{ .rows = 4, .n = 32 * lat, .k = 2048 }, .{ .rows = 1, .n = 16 * lat, .k = 2048 }, .{ .rows = 9, .n = 8 * lat, .k = 2048 } }; + +pub fn spec(form: Form, fault: set.Fault) c.Spec { + const keys: c.Tile = .{ .size = chunk }; + var s: c.Spec = switch (form) { + .window => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_attn (sliding window 512, sinks)", .accum = .f32, .depth = depth, .ops = 8, .out = .f32, .tiles = .{ .{}, .{}, keys }, .served = &window_shapes }, + .ring => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_attn (sliding window 512 over a 1,024-slot ring, sinks)", .accum = .f32, .depth = depth, .ops = 8, .out = .f32, .served = &ring_shapes }, + .dense => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_attn (causal span to 2,048 keys, sinks)", .accum = .f32, .depth = depth, .ops = 8, .out = .f32, .tiles = .{ .{}, .{}, keys }, .served = &dense_shapes }, + .list => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_attn (the indexer's list of 2,048 keys, sinks)", .accum = .f32, .depth = depth, .ops = 8, .out = .f32, .tiles = .{ .{}, .{}, keys }, .served = &list_shapes }, + .rows => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_attn_rows (causal spans, a cache a row, sinks)", .accum = .f32, .depth = depth, .ops = 8, .out = .f32, .tiles = .{ .{}, .{}, keys }, .served = &rows_shapes }, + }; + if (fault != .none) s.name = set.controlName(if (form == .rows) "attn_rows" else "attn", fault); + return s; +} + +pub const Attn = struct { + rig: rig_.Rig, + form: Form, + f: cuda.Function, + fault: set.Fault = .none, + fill: g.Fill = .random, + shape: c.Shape = undefined, + heads: usize = 0, + slots: usize = 0, + nidx: usize = 0, + ql: []f32 = &.{}, // [rows][heads][512] + qr: []u16 = &.{}, // [rows][heads][64] + cache: []u16 = &.{}, // [slots][576] + pos: []i32 = &.{}, + idx: []i32 = &.{}, // [rows][nidx] + sinks: []f32 = &.{}, + tol: []f64 = &.{}, + in: [6]u64 = @splat(0), + caches: u64 = 0, // rows: device u64 [rows], row r's cache (in[2] or the second cache past it) + out: u64 = 0, + + pub fn deinit(self: *Attn) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attn) void { + const a = self.rig.gpu.gpa; + a.free(self.ql); + a.free(self.qr); + a.free(self.cache); + a.free(self.pos); + a.free(self.idx); + a.free(self.sinks); + a.free(self.tol); + self.ql = &.{}; + self.qr = &.{}; + self.cache = &.{}; + self.pos = &.{}; + self.idx = &.{}; + self.sinks = &.{}; + self.tol = &.{}; + } + + pub fn kernel(self: *Attn) g.Kernel { + return .{ .spec = spec(self.form, self.fault), .ctx = self, .vt = &vt, .control = self.fault.gate() }; + } + + const vt = g.hooks(Attn); + + pub fn count(self: *const Attn) usize { + return self.shape.rows * self.heads * lat; + } + + fn windowed(self: *const Attn) bool { + return self.form == .window or self.form == .ring; + } + + /// The last row's position: a full window starts past position 0, a short one at it; a list's rows lie far in. + fn lastPos(self: *const Attn, k: usize) usize { + return switch (self.form) { + .window => if (k == window) 700 else k - 1, + .ring => 1500, + .dense, .rows => k - 1, + .list => 3000, + }; + } + + /// The positions row r sees, in the kernel's walk order, into `out` (its length returned). + fn seen(self: *const Attn, r: usize, out: []usize) usize { + const t: usize = @intCast(self.pos[r]); + var n: usize = 0; + if (self.form == .list) { + for (self.idx[r * self.nidx ..][0..self.nidx]) |p| if (p >= 0 and p <= t) { + out[n] = @intCast(p); + n += 1; + }; + return n; + } + const lo = if (self.windowed() and t + 1 > window) t + 1 - window else 0; + for (lo..t + 1) |p| { + out[n] = p; + n += 1; + } + return n; + } + + fn slot(self: *const Attn, p: usize) usize { + return if (self.form == .ring) p % ring else p; + } + + /// Row r's cache row for position p: the second cache past the first for a `rows` form's odd rows. + fn cacheRow(self: *const Attn, r: usize, p: usize) usize { + return (if (self.form == .rows) (r % 2) * self.slots else 0) + self.slot(p); + } + + pub fn prepare(self: *Attn, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n % (hy4.heads_tile * lat) != 0) return false; + if (self.windowed() and shape.k > window) return false; + const last = self.lastPos(shape.k); + if (last + 1 < shape.rows or (self.form != .list and last + 1 < shape.k)) return false; + self.free(); + self.rig.reset(); + self.fill = fill; + self.shape = shape; + self.heads = shape.n / lat; + self.nidx = if (self.form == .list) shape.k else 0; + self.slots = if (self.form == .ring) ring else last + 1; + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows = shape.rows; + self.pos = try a.alloc(i32, rows); + for (self.pos, 0..) |*p, r| p.* = @intCast(if (self.form == .rows) last - (r * 37) % @min(last + 1, 64) else last + 1 - rows + r); + self.ql = try a.alloc(f32, rows * self.heads * lat); + self.qr = try a.alloc(u16, rows * self.heads * rope); + self.cache = try a.alloc(u16, (if (self.form == .rows) 2 * self.slots else self.slots) * row); + self.sinks = try a.alloc(f32, self.heads); + self.idx = try a.alloc(i32, rows * self.nidx); + for (self.ql) |*v| v.* = (rng.float(f32) * 2 - 1) * 4; + for (self.qr) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 4); + for (self.cache) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + for (self.sinks) |*v| v.* = (rng.float(f32) * 2 - 1) * 2; + if (self.form == .list) for (0..rows) |r| try self.choose(rng, r, fill != .stress); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.ql)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.qr)); + self.in[2] = try self.rig.input(std.mem.sliceAsBytes(self.cache)); + self.in[3] = try self.rig.input(std.mem.sliceAsBytes(self.pos)); + self.in[4] = if (self.nidx > 0) try self.rig.input(std.mem.sliceAsBytes(self.idx)) else 0; + self.in[5] = try self.rig.input(std.mem.sliceAsBytes(self.sinks)); + if (self.form == .rows) { + const ptrs = try a.alloc(u64, rows); + defer a.free(ptrs); + for (ptrs, 0..) |*q, r| q.* = self.in[2] + self.cacheRow(r, 0) * row * 2; + self.caches = try self.rig.input(std.mem.sliceAsBytes(ptrs)); + } + self.out = try self.rig.output(self.count() * 4); + return true; + } + + /// Row r's list: its own position and other distinct earlier ones in random order; `masked` adds a -1 and t + 3. + fn choose(self: *Attn, rng: std.Random, r: usize, masked: bool) !void { + const t: usize = @intCast(self.pos[r]); + const list = self.idx[r * self.nidx ..][0..self.nidx]; + const a = self.rig.gpu.gpa; + const all = try a.alloc(i32, t + 1); + defer a.free(all); + for (all, 0..) |*p, i| p.* = @intCast(i); + rng.shuffle(i32, all[0..t]); + @memcpy(list[0 .. list.len - 1], all[0 .. list.len - 1]); + list[list.len - 1] = @intCast(t); + rng.shuffle(i32, list); + if (masked and list.len > 12) { + list[5] = -1; + list[9] = @intCast(t + 3); + } + } + + /// Plants NaN in row 0 head 1 ql, +Inf in row 1 head 2 qr, +-Inf in row 2 head 0 ql, +Inf in last row's own key. + fn plant(self: *Attn) void { + const h = self.heads; + self.ql[(0 * h + 1) * lat + 7] = std.math.nan(f32); + self.qr[(1 * h + 2) * rope + 3] = c.toBf16(std.math.inf(f32)); + self.ql[(2 * h + 0) * lat + 0] = std.math.inf(f32); + self.ql[(2 * h + 0) * lat + 1] = -std.math.inf(f32); + const t: usize = @intCast(self.pos[self.shape.rows - 1]); + self.cache[self.cacheRow(self.shape.rows - 1, t) * row + 9] = c.toBf16(std.math.inf(f32)); + } + + /// Gate 4: q and sinks 0 (weights 1, l = n + 1); eight 1s plus +-10240|14336 cancel in fp32 and break fp16/bf16. + fn stress(self: *Attn, rng: std.Random) !void { + @memset(self.ql, 0); + @memset(self.qr, 0); + @memset(self.sinks, 0); + for (0..self.cache.len / row) |k| @memset(self.cache[k * row ..][0..lat], 0); + const r = self.shape.rows - 1; + if (self.form == .list) for (0..r) |i| @memcpy(self.idx[i * self.nidx ..][0..self.nidx], self.idx[r * self.nidx ..][0..self.nidx]); + const a = self.rig.gpu.gpa; + const keys = try a.alloc(usize, self.slots + self.nidx + 1); + defer a.free(keys); + const n = self.seen(r, keys); + const half = n / 2; + for (0..half) |j| for (0..lat) |col| { + const v: f32 = if (j < 8) 1 else 2048 * @as(f32, @floatFromInt(5 + 2 * rng.uintLessThan(u32, 2))); + self.cache[self.cacheRow(r, keys[j]) * row + col] = c.toBf16(v); + self.cache[self.cacheRow(r, keys[half + j]) * row + col] = c.toBf16(if (j < 8) 0 else -v); + }; + } + + pub fn run(self: *Attn) !void { + const keys: hy4.Keys = .{ .pos = self.in[3], .window = if (self.windowed()) window else 0, .idx = self.in[4], .nidx = self.nidx, .ring = if (self.form == .ring) ring else 0 }; + const cache = if (self.form == .rows) self.caches else self.in[2]; + try hy4.attn(self.f, self.rig.s, self.in[0], self.in[1], cache, keys, self.in[5], self.out, self.shape.rows, self.heads); + try self.rig.s.synchronize(); + } + + /// Row r, head h: sinked softmax reference (NaN kept in M), `acc` on P*V, and per-column fp32 error bound `tol`. + fn attend(self: *const Attn, r: usize, h: usize, acc: ?c.Accum, order: g.Order, o: []f64, tol: ?[]f64) !void { + const a = self.rig.gpu.gpa; + const keys = try a.alloc(usize, self.slots + self.nidx + 1); + defer a.free(keys); + const n = self.seen(r, keys); + const buf = try a.alloc(f64, 4 * n + 1); + defer a.free(buf); + const s = buf[0..n]; + const e = buf[n .. 2 * n]; + const p = buf[2 * n .. 3 * n]; + const col = buf[3 * n ..][0..n]; + const at = r * self.heads + h; + const sink: f64 = self.sinks[h]; + var most = sink; + for (keys[0..n], s, e) |key, *sv, *ev| { + const kr = self.cache[self.cacheRow(r, key) * row ..][0..row]; + var dot: f64 = 0; + var abs: f64 = 0; + for (0..row) |cc| { + const q: f64 = if (cc < lat) self.ql[at * lat + cc] else c.fromBf16(self.qr[at * rope + cc - lat]); + const x = q * c.fromBf16(kr[cc]); + dot += x; + abs += @abs(x); + } + sv.* = dot * hy4.scale; + ev.* = c.gamma(row, u) * abs * hy4.scale; + most = if (std.math.isNan(most) or std.math.isNan(sv.*)) std.math.nan(f64) else @max(most, sv.*); + } + const steps = (n + chunk - 1) / chunk; + const drift = @as(f64, @floatFromInt(4 * steps + 4)) * u + @abs(most - sink) * u; // exp and the rescales + var l: f64 = @exp(sink - most); + var worst: f64 = 0; + for (p, s, e) |*pv, sv, ev| { + pv.* = @exp(sv - most); + l += pv.*; + worst = @max(worst, ev + @abs(sv - most) * u + drift); + } + const rel_l = worst + c.gamma(@floatFromInt(2 * steps + 8), u); + const chain = c.gamma(@floatFromInt(n + steps + 1), u); + for (o, 0..) |*od, d| { + var spread: f64 = 0; + for (col, p, keys[0..n], s, e) |*x, w, key, sv, ev| { + const v: f64 = c.fromBf16(self.cache[self.cacheRow(r, key) * row + d]); + x.* = w * v; + spread += @abs(w * v) * (ev + @abs(sv - most) * u + drift + chain); + } + od.* = (if (acc) |k| sumIn(k, order, col) else sumIn(.none, .sequential, col)) / l; + if (tol) |t| t[d] = @abs(od.*) * (rel_l + 2 * u) + spread / l + 0x1p-126; + } + } + + pub fn reference(self: *Attn, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + a.free(self.tol); + self.tol = try a.alloc(f64, want.len); + for (0..self.shape.rows) |r| for (0..self.heads) |h| { + const at = (r * self.heads + h) * lat; + try self.attend(r, h, null, .sequential, want[at..][0..lat], self.tol[at..][0..lat]); + }; + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(self: *Attn, _: []const f64, _: []const f64, allow: []f64) !void { + if (self.fill == .stress) return; + for (allow, self.tol) |*l, t| l.* = if (std.math.isFinite(t)) t else std.math.floatMax(f64); + } + + pub fn simulate(self: *Attn, acc: c.Accum, order: g.Order, out: []f64) !void { + for (0..self.shape.rows) |r| for (0..self.heads) |h| { + const at = (r * self.heads + h) * lat; + try self.attend(r, h, acc, order, out[at..][0..lat], null); + }; + } +}; diff --git a/zig/tests/cuda/contract_hy4_mla_paged_proj.zig b/zig/tests/cuda/contract_hy4_mla_paged_proj.zig new file mode 100644 index 00000000000..bb4da8eaa7b --- /dev/null +++ b/zig/tests/cuda/contract_hy4_mla_paged_proj.zig @@ -0,0 +1,286 @@ +//! Hy4-flash paged MLA absorb, value, and post-norm contract across worlds and head counts. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const hy4 = @import("hy4_mla_paged_cuda"); +const rig_ = @import("contract_rig.zig"); +const set = @import("contract_hy4_mla_paged.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sumIn = contract.rows.sumIn; +const lat = hy4.latent; +const nope = hy4.nope; +const vw = hy4.v_width; +const kvh = hy4.kv_head; +const qh = hy4.q_head; +const hidden = 3072; + +pub const Kind = enum { absorb, value, post }; + +fn bf(h: u16) f64 { + return c.fromBf16(h); +} + +fn depthAbsorb(_: c.Shape) usize { + return nope; +} + +fn depthValue(_: c.Shape) usize { + return lat; +} + +/// post: a thread's 12 squares, the warp's five steps, the block's three. +fn depthPost(_: c.Shape) usize { + return hidden / 256 + 8; +} + +const absorb_shapes = [_]c.Shape{ .{ .rows = 16, .n = 8 * lat, .k = nope }, .{ .rows = 1, .n = 64 * lat, .k = nope }, .{ .rows = 17, .n = 32 * lat, .k = nope }, .{ .rows = 40, .n = 16 * lat, .k = nope } }; +const value_shapes = [_]c.Shape{ .{ .rows = 16, .n = 8 * vw, .k = lat }, .{ .rows = 1, .n = 64 * vw, .k = lat }, .{ .rows = 17, .n = 32 * vw, .k = lat }, .{ .rows = 33, .n = 16 * vw, .k = lat } }; +const post_shapes = [_]c.Shape{ .{ .rows = 7, .n = hidden, .k = hidden }, .{ .rows = 1, .n = hidden, .k = hidden }, .{ .rows = 64, .n = hidden, .k = hidden } }; +const post_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps (fp16 overflows)"; + +pub fn spec(kind: Kind, world: usize, fault: set.Fault) c.Spec { + const rows: c.Tile = .{ .size = 16 }; + var s: c.Spec = switch (kind) { + .absorb => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_absorb (q_nope . kv_b's key rows into the fp32 latent)", .accum = .f32, .depth = depthAbsorb, .out = .f32, .tiles = .{ rows, .{}, .{} }, .served = &absorb_shapes }, + .value => .{ .name = "cuda hy4_mla_paged tf_hy4_mla_value (latent . kv_b's value rows, times sigmoid(gate))", .accum = .f32, .depth = depthValue, .ops = 4, .out = .bf16, .tiles = .{ rows, .{}, .{} }, .served = &value_shapes }, + .post => .{ .name = switch (world) { + 1 => "cuda hy4_mla_paged tf_hy4_mla_post (one rank's o_proj rows, post_proj_norm)", + 2 => "cuda hy4_mla_paged tf_hy4_mla_post (two ranks' partials summed, post_proj_norm)", + else => "cuda hy4_mla_paged tf_hy4_mla_post (four ranks' partials summed, post_proj_norm)", + }, .accum = .f32, .depth = depthPost, .ops = 6, .out = .bf16, .served = &post_shapes, .sums = .{ .bf16 = 0, .why = post_why } }, + }; + if (fault != .none) s.name = set.controlName(switch (kind) { + .absorb => "absorb", + .value => "value", + .post => "post", + }, fault); + return s; +} + +/// One call of a projection-like kernel: its inputs on the host and the device, its outputs on the device. +pub const Proj = struct { + rig: rig_.Rig, + kind: Kind, + f: cuda.Function, + fault: set.Fault = .none, + world: usize = 1, + shape: c.Shape = undefined, + heads: usize = 0, + x: []f32 = &.{}, // absorb: q (bf16 values) [rows][heads][256]; value: ol [rows][heads][512]; post: parts + w: []u16 = &.{}, // kv_b [heads][448][512], or post_proj_norm [hidden] + gate: []u16 = &.{}, // value: [rows][heads x 256] + in: [3]u64 = @splat(0), + out: u64 = 0, + + pub fn deinit(self: *Proj) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Proj) void { + const a = self.rig.gpu.gpa; + a.free(self.x); + a.free(self.w); + a.free(self.gate); + self.x = &.{}; + self.w = &.{}; + self.gate = &.{}; + } + + pub fn kernel(self: *Proj) g.Kernel { + return .{ .spec = spec(self.kind, self.world, self.fault), .ctx = self, .vt = &vt, .control = self.fault.gate() }; + } + + const vt = g.hooks(Proj); + + fn xWidth(self: *const Proj) usize { + return switch (self.kind) { + .absorb => qh, + .value => lat, + .post => hidden, + }; + } + + fn outWidth(self: *const Proj) usize { + return switch (self.kind) { + .absorb => lat, + .value => vw, + .post => hidden, + }; + } + + pub fn count(self: *const Proj) usize { + return self.shape.rows * self.heads * self.outWidth(); + } + + pub fn prepare(self: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 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.heads = if (self.kind == .post) 1 else shape.n / self.outWidth(); + const planes: usize = if (self.kind == .post) self.world else 1; + const xn = planes * shape.rows * self.heads * self.xWidth(); + self.x = try a.alloc(f32, xn); + self.w = try a.alloc(u16, if (self.kind == .post) hidden else self.heads * kvh * lat); + self.gate = try a.alloc(u16, if (self.kind == .value) shape.rows * self.heads * vw else 0); + const amp: f32 = if (self.kind == .absorb) 2 else 1; + for (self.x) |*v| v.* = (rng.float(f32) * 2 - 1) * amp; + if (self.kind == .absorb) for (self.x) |*v| { + v.* = c.fromBf16(c.toBf16(v.*)); + }; + for (self.w) |*v| v.* = c.toBf16(if (self.kind == .post) 0.5 + rng.float(f32) else (rng.float(f32) * 2 - 1) * 0.125); + for (self.gate) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 4); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => self.stress(rng), + } + if (self.kind == .absorb) { + const q = try a.alloc(u16, xn); + defer a.free(q); + for (q, self.x) |*h, v| h.* = c.toBf16(v); + self.in[0] = try self.rig.input(std.mem.sliceAsBytes(q)); + } else self.in[0] = try self.rig.input(std.mem.sliceAsBytes(self.x)); + self.in[1] = try self.rig.input(std.mem.sliceAsBytes(self.w)); + if (self.kind == .value) self.in[2] = try self.rig.input(std.mem.sliceAsBytes(self.gate)); + self.out = try self.rig.output(self.count() * c.size(spec(self.kind, self.world, .none).out)); + return true; + } + + /// Row 0 a NaN, row 1 +Inf, row 2 both infinities, in head 0's reduced inputs (rank 0); value: row 3's gate NaN. + fn plant(self: *Proj) void { + const k = if (self.kind == .absorb) nope else self.xWidth(); + const xw = self.xWidth() * self.heads; + const at = [_]struct { usize, usize, f32 }{ .{ 0, k / 3, std.math.nan(f32) }, .{ 1, k / 2, std.math.inf(f32) }, .{ 2, 0, std.math.inf(f32) }, .{ 2, k - 1, -std.math.inf(f32) } }; + for (at) |p| if (p[0] < self.shape.rows) { + self.x[p[0] * xw + p[1]] = p[2]; + }; + if (self.kind == .value and self.shape.rows > 3) self.gate[3 * self.heads * vw + 5] = c.toBf16(std.math.nan(f32)); + } + + /// Gate 4: absorb/value mirror weights and inputs across k/2 (gate 0); post sums integer squares past fp16 range. + fn stress(self: *Proj, rng: std.Random) void { + const rows = self.shape.rows; + if (self.kind == .post) { + for (self.x) |*v| v.* = 0; + for (0..rows) |r| for (0..hidden) |i| { + const v: f32 = @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 91))) - 45); + const share: f32 = @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 9))) - 4); + self.x[r * hidden + i] = if (self.world > 1) v - share else v; + if (self.world > 1) self.x[(self.world - 1) * rows * hidden + r * hidden + i] = share; + }; + return; + } + const k: usize = if (self.kind == .absorb) nope else lat; + const h2 = k / 2; + const outs = self.outWidth(); + for (0..self.heads) |hd| for (0..h2) |i| for (0..outs) |o| { + const v = c.toBf16(@floatFromInt(1 + rng.uintLessThan(u32, 2))); + self.w[self.wAt(hd, i, o)] = v; + self.w[self.wAt(hd, h2 + i, o)] = v; + }; + const odd: u32 = if (self.kind == .absorb) 64 else 2048; + const base: u32 = if (self.kind == .absorb) 1 else 4097; + const unit: f32 = if (self.kind == .absorb) 512 else 1; + for (0..rows) |r| for (0..self.heads) |hd| for (0..h2) |i| { + const v = unit * @as(f32, @floatFromInt(base + 2 * rng.uintLessThan(u32, odd))); + const at = (r * self.heads + hd) * self.xWidth(); + self.x[at + i] = v; + self.x[at + h2 + i] = if (i < 8) unit - v else -v; + }; + for (self.gate) |*v| v.* = 0; + } + + /// kv_b's weight for reduced index i and output o of head hd: absorb's key rows [d][c], value's [v][c]. + fn wAt(self: *const Proj, hd: usize, i: usize, o: usize) usize { + return if (self.kind == .absorb) (hd * kvh + i) * lat + o else (hd * kvh + nope + o) * lat + i; + } + + pub fn run(self: *Proj) !void { + const s = self.rig.s; + const rows = self.shape.rows; + switch (self.kind) { + .absorb => try hy4.absorb(self.f, s, self.in[0], self.heads * qh, self.in[1], self.out, rows, self.heads), + .value => try hy4.value(self.f, s, self.in[0], self.in[1], self.in[2], self.heads * vw, self.out, self.heads * vw, rows, self.heads), + .post => try hy4.post(self.f, s, self.in[0], self.world, self.in[1], self.out, rows, hidden, set.eps), + } + try s.synchronize(); + } + + /// The products output o sums, in order; its post-sum factor (sigmoid) in `factor`. + fn terms(self: *const Proj, o: usize, t: []f64, factor: *f64) []f64 { + const outs = self.outWidth(); + const col = o % outs; + const rh = o / outs; + const hd = rh % self.heads; + const xa = rh * self.xWidth(); + const k: usize = if (self.kind == .absorb) nope else lat; + for (t[0..k], 0..) |*v, i| v.* = @as(f64, self.x[xa + i]) * bf(self.w[self.wAt(hd, i, col)]); + factor.* = 1; + if (self.kind == .value) factor.* = 1 / (1 + @exp(-@as(f64, bf(self.gate[rh * vw + col])))); + return t[0..k]; + } + + /// post's row r: x = bf16 of the ranks' fp32 sum in rank order (the stored o_proj output), into `x`. + fn postRow(self: *const Proj, r: usize, x: []f64) void { + const plane = self.shape.rows * hidden; + for (x, 0..) |*v, i| { + var s: f32 = self.x[r * hidden + i]; + for (1..self.world) |q| s += self.x[q * plane + r * hidden + i]; + v.* = c.fromBf16(c.toBf16(s)); + } + } + + fn postOut(self: *const Proj, r: usize, acc: ?c.Accum, order: g.Order, out: []f64, mag: ?[]f64) void { + var x: [hidden]f64 = undefined; + var sq: [hidden]f64 = undefined; + self.postRow(r, &x); + for (&sq, x) |*q, v| q.* = v * v; + const ss = if (acc) |k| sumIn(k, order, &sq) else sumIn(.none, .sequential, &sq); + const inv = 1 / @sqrt(ss / hidden + @as(f64, set.eps)); + for (out[r * hidden ..][0..hidden], x, self.w, 0..) |*y, v, w, i| { + y.* = v * inv * bf(w); + if (mag) |m| m[r * hidden + i] = @abs(y.*); + } + } + + pub fn reference(self: *Proj, want: []f64, mag: []f64) !void { + if (self.kind == .post) { + for (0..self.shape.rows) |r| self.postOut(r, null, .sequential, want, mag); + return; + } + var t: [lat]f64 = undefined; + for (want, mag, 0..) |*w, *m, o| { + var factor: f64 = 1; + const ts = self.terms(o, &t, &factor); + var sum: f64 = 0; + var abs: f64 = 0; + for (ts) |v| { + sum += v; + abs += @abs(v); + } + w.* = sum * factor; + m.* = abs * @abs(factor); + } + } + + pub fn simulate(self: *Proj, acc: c.Accum, order: g.Order, out: []f64) !void { + if (self.kind == .post) { + for (0..self.shape.rows) |r| self.postOut(r, acc, order, out, null); + return; + } + var t: [lat]f64 = undefined; + for (out, 0..) |*v, o| { + var factor: f64 = 1; + const ts = self.terms(o, &t, &factor); + v.* = sumIn(acc, order, ts) * factor; + } + } +}; diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index c254ee56d19..a4ac8c83215 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -57,6 +57,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "hy4_route", "hy4_rows", "hy4_dfly2_glue" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "fn_int4")) return kk.fn_int4; if (std.mem.eql(u8, name, "hy4_engram_fp8")) return kk.hy4_engram_fp8; + inline for (.{ "hy4_mla_paged", "hy4_mla_attn_paged", "hy4_mla_c2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index fcfa93d93bc..160a22efa28 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -95,7 +95,7 @@ zig/src/cuda/experts.zig 5d2cd5aa511b267f7a0800e0c3fd0bb7492ca0e50ed8558c0ee342f zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 31cdf4299056567260a052f924ab2e7999a2aec713b51f7d258a2fb9f754d089 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered; #5301: the ernie5_5_mhc image registered +zig/src/cuda/kernels.zig c46a1a1545fa45c356cd1f8697a5a706f4418352496b514f91564303e1a09043 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered; #1508: the lfm3 image registered; #5100: the hy4_hc and hy4_ihc_fused images registered; #5042: the experts_mxfp4 image registered; #5202: the ernie5_5_head image registered; #4128: the inkling2_dspark image registered; #5087: the hy4_engram_fp8 image registered; #5442: the tfq4 image registered; #5301: the ernie5_5_mhc image registered; #5109: paged Hy4-flash MLA images registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw