diff --git a/CHANGELOG.md b/CHANGELOG.md index c826b153998..1a9ab47c249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](RELEASE-NOTES-1.0.0.md) for the native binary's supported models and migration details. +## Unreleased + +- speech: `stream: true` with `response_format: pcm` streams HTTP/1.1 chunks while Drama 3 generates; incremental codec decode bit-identical to the whole decode (oracle-gated) +- speech: a Drama 3 reply that reaches `max_frames` without an end of speech returns its clipped audio with HTTP 200, as the reference returns its capped replies, instead of a 500 without audio. A whole reply carries `X-Finish-Reason: stop` or `length`; a stream declares the trailer, and only a clipped stream ends with `X-Finish-Reason: length`, a normally finished one with the plain last chunk. + ## 1.0.12 - Nemotron serves MLX checkpoints with a width per module on Metal: TensorFold's oQ4, oQ6 and oQ8 quants, and any MLX affine checkpoint at 2 to 8 bits (not 7) in groups of 32, 64 or 128. 1.0.11 refused every one of them at `config.json` ("the native Nemotron kernels read every matrix at the checkpoint's 4-bit in groups of 64"), and refused a uniform 8-bit checkpoint with a reason about its shapes. A matrix at 4-bit in groups of 64 runs on the kernels it ran on before. In decode, every other width runs on the shared row kernels. Prompt chunks past 128 rows run the other dense matrices on simd_qmm_bits' tiles where their groups are 64, and the routed experts on Flash Next's width-general expert gathers, compiled at load for each width the checkpoint uses. The embedding has a lookup for any width, a mixed q/k/v stack runs member by member, and the routed experts run by expert id. On an M3 Ultra, oQ4, oQ6 and oQ8 each gave drafted replies equal to `"draft": false` on 17 prompts, 2 and 4 concurrent streams equal to their solo runs, and 12 resumed chat turns equal to a cache-off server's. Teacher-forced against mlx_lm's forward of the same checkpoint on 3,072 positions, their mean KL is 0.0050 to 0.0054 nats a token, with the same top token at 96.2% to 97.0% of positions; the 4-bit checkpoint gives 0.0056 and 96.2% through the same tool. Prompts of 8,192 to 32,768 tokens read at 0.96x to 0.99x mlx_lm's rate on the same checkpoint. Greedy prose decodes at 162 tok/s with oQ4, 117 with oQ6 and 111 with oQ8, against 188 with the 4-bit checkpoint, and greedy code at 249, 183 and 174 against 268. The oQ checkpoints carry no MTP head, so copy `mtp-4bit.safetensors` from the 4-bit checkpoint into the folder to draft. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 74546d20cda..9d1215f8bbc 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -83,6 +83,12 @@ Flash Next implements transformers' model math under the attribution above. In t DeltaNet kernel follows flash-linear-attention's numerics, MIT; its NCCL wrapper follows vLLM's stream convention, Apache-2.0, without copying either implementation. +The native Drama 3 backbone's Gated DeltaNet prefill (`zig/kernels/cuda/drama_gdn_chunk.cuh`, driven by +`zig/src/families/drama/backbone_gdn.zig`) is adapted from SGLang's `chunk_gated_delta_rule` (Apache-2.0), whose +kernels are adapted from [flash-linear-attention](https://github.com/fla-org/flash-linear-attention), MIT License, +Copyright (c) 2023-2025 Songlin Yang, Yu Zhang (text below). Its decode recurrence (`drama_backbone.cu`) follows +the same project's packed decode. + The Python engine's GLM CUDA engine implements transformers' `models/glm5_next/modular_glm5_next.py` math, Apache-2.0, without including that source. Its draft inputs and thinking-off rendering follow the public GLM recipe from Mia-AiLab without including recipe code. diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 684d6c3cc9d..28c0baa2a2f 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -58,6 +58,10 @@ const kernels = [_]Kernel{ .{ .name = "torch_indexing", .src = "torch_ops/indexing", .flags = torch_ops }, .{ .name = "torch_movement", .src = "torch_ops/movement", .flags = torch_ops }, .{ .name = "torch_nemotron_constants", .src = "torch_ops/nemotron_constants", .flags = torch_ops }, + .{ .name = "drama_backbone", .flags = glue }, + .{ .name = "drama_backbone_gemm", .flags = &.{"-O3"} }, + .{ .name = "drama_tower", .flags = glue }, + .{ .name = "drama_codec", .flags = glue }, }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. @@ -88,7 +92,7 @@ fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti return cuda; } -fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module, radio: *std.Build.Module } { +fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, drama: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module, radio: *std.Build.Module } { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); core.addImport("tokenizer", tokenizer); @@ -102,7 +106,10 @@ fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin nemotron.addImport("nemotron_draft_ids", draft_ids); const radio = radioModule(b, target, optimize, cuda, core, lanes); nemotron.addImport("radio", radio); - return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .tokenizer = tokenizer, .heat = heat, .radio = radio }; + const drama = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + drama.addImport("cuda", cuda); + drama.addImport("core", core); + return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .drama = drama, .tokenizer = tokenizer, .heat = heat, .radio = radio }; } /// Linux targets: fatbins (-Dnvcc builds them, -Dfatbins embeds prebuilt ones), `tensorfold` and `tf-cuda-test`. @@ -134,7 +141,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu cli.addImport("core", mods.core); cli.addImport("lanes", mods.lanes); cli.addImport("nemotron", mods.nemotron); - const native = engines(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat); + const native = engines(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.drama); cli.addOptions("build_options", build_options); cli.addImport("checkpoint_cli", checkpointCli(b, target, optimize, strip, native.engines, mods.core)); b.installArtifact(b.addExecutable(.{ .name = "tensorfold", .root_module = cli })); @@ -158,7 +165,197 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu b.installArtifact(runner_exe); const controls = if (nvcc) |tool| fatbin(b, tool, version.?, .{ .name = "contract_controls", .flags = &.{"-O3"} }, sms) else null; @import("kernel_contract.zig").cuda(b, runner_exe, controls); - nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, build_options, true).root_module.strip = strip; + nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.drama, mods.tokenizer, build_options, true).root_module.strip = strip; + const codec_oracle = b.addExecutable(.{ .name = "tf-drama-codec-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_codec_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_oracle = b.addInstallArtifact(codec_oracle, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-codec-oracle", "Build the production-codec numerical oracle driver; does not run a GPU").dependOn(&install_oracle.step); + const codec_stream_oracle = b.addExecutable(.{ .name = "tf-drama-codec-stream-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_codec_stream_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_stream_oracle = b.addInstallArtifact(codec_stream_oracle, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-codec-stream-oracle", "Build the chunked-versus-whole codec driver; does not run a GPU").dependOn(&install_stream_oracle.step); + const codec_rvq_replay = b.addExecutable(.{ .name = "tf-drama-codec-rvq-replay", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_codec_rvq_replay.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_codec_rvq_replay = b.addInstallArtifact(codec_rvq_replay, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-codec-rvq-replay", "Build the isolated codec RVQ counterfactual; does not run a GPU").dependOn(&install_codec_rvq_replay.step); + const codec_weight_replay = b.addExecutable(.{ .name = "tf-drama-codec-weight-replay", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_codec_weight_replay.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_codec_weight_replay = b.addInstallArtifact(codec_weight_replay, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-codec-weight-replay", "Build the isolated codec weight counterfactual; does not run a GPU").dependOn(&install_codec_weight_replay.step); + const tower_oracle = b.addExecutable(.{ .name = "tf-drama-tower-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_oracle = b.addInstallArtifact(tower_oracle, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-oracle", "Build the production-tower numerical oracle driver; does not run a GPU").dependOn(&install_tower_oracle.step); + const semantic_fixture = b.addExecutable(.{ .name = "tf-drama-semantic-fixture", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_semantic_fixture.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_semantic_fixture = b.addInstallArtifact(semantic_fixture, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-semantic-fixture", "Build the production generator fixture capture; does not run a GPU").dependOn(&install_semantic_fixture.step); + const backbone_oracle = b.addExecutable(.{ .name = "tf-drama-backbone-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_backbone_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_backbone_oracle = b.addInstallArtifact(backbone_oracle, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-backbone-oracle", "Build the production-backbone numerical oracle driver; does not run a GPU").dependOn(&install_backbone_oracle.step); + const gdn_oracle = b.addExecutable(.{ .name = "tf-drama-gdn-canonical-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_gdn_canonical_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_gdn_oracle = b.addInstallArtifact(gdn_oracle, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-gdn-canonical-oracle", "Build the GDN canonical controller verification driver; does not run a GPU").dependOn(&install_gdn_oracle.step); + const codec_trace = b.addExecutable(.{ .name = "tf-drama-codec-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_codec_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_trace = b.addInstallArtifact(codec_trace, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-codec-trace", "Build the production-codec trace/replay diagnostic; does not run a GPU").dependOn(&install_trace.step); + const backbone_trace = b.addExecutable(.{ .name = "tf-drama-backbone-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_backbone_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_backbone_trace = b.addInstallArtifact(backbone_trace, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-backbone-trace", "Build the production-backbone stage trace diagnostic; does not run a GPU").dependOn(&install_backbone_trace.step); + const backbone_replay = b.addExecutable(.{ .name = "tf-drama-backbone-replay", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_backbone_replay.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_backbone_replay = b.addInstallArtifact(backbone_replay, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-backbone-replay", "Build the production-backbone operator replay diagnostic; does not run a GPU").dependOn(&install_backbone_replay.step); + const gdn_layer0 = b.addExecutable(.{ .name = "tf-drama-gdn-layer0-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_gdn_layer0_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_gdn_layer0 = b.addInstallArtifact(gdn_layer0, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-gdn-layer0-trace", "Build the layer-zero production attention scratch diagnostic; does not run a GPU").dependOn(&install_gdn_layer0.step); + const tower_mixer = b.addExecutable(.{ .name = "tf-drama-tower-mixer-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_mixer_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_mixer = b.addInstallArtifact(tower_mixer, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-mixer-trace", "Build the full-context tower mixer trace diagnostic; does not run a GPU").dependOn(&install_tower_mixer.step); + const tower_qk = b.addExecutable(.{ .name = "tf-drama-tower-qk-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_qk_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_qk = b.addInstallArtifact(tower_qk, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-qk-trace", "Build the full-context tower Q/K and rotary diagnostic; does not run a GPU").dependOn(&install_tower_qk.step); + const tower_head_replay = b.addExecutable(.{ .name = "tf-drama-tower-head-replay", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_head_replay.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_head_replay = b.addInstallArtifact(tower_head_replay, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-head-replay", "Build the production-tower head9 identical-input replay diagnostic; does not run a GPU").dependOn(&install_tower_head_replay.step); + const tower_trace = b.addExecutable(.{ .name = "tf-drama-tower-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_trace = b.addInstallArtifact(tower_trace, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-trace", "Build the production-tower real-input stage trace diagnostic; does not run a GPU").dependOn(&install_tower_trace.step); + const tower_context = b.addExecutable(.{ .name = "tf-drama-tower-context-oracle", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_context_oracle.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_context = b.addInstallArtifact(tower_context, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-context-oracle", "Build the full-context teacher-forced tower diagnostic; does not run a GPU").dependOn(&install_tower_context.step); + const tower_context_trace = b.addExecutable(.{ .name = "tf-drama-tower-context-trace", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_context_trace.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "drama", .module = mods.drama } }, + }) }); + const install_tower_context_trace = b.addInstallArtifact(tower_context_trace, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-context-trace", "Build the full-context tower stage trace diagnostic; does not run a GPU").dependOn(&install_tower_context_trace.step); + const tower_linear_replay = b.addExecutable(.{ .name = "tf-drama-tower-linear-replay", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/drama_tower_linear_replay.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .strip = strip, + .imports = &.{.{ .name = "cuda", .module = cuda }}, + }) }); + const install_tower_linear_replay = b.addInstallArtifact(tower_linear_replay, .{ .dest_dir = .{ .override = .{ .custom = "oracle/bin" } } }); + b.step("drama-tower-linear-replay", "Build the tower eh_proj cuBLASLt identical-input replay diagnostic; does not run a GPU").dependOn(&install_tower_linear_replay.step); } /// The GLM-5.3-Flash CUDA family over the runtime, the core, the lane core, canon's shares and core/heat.zig. @@ -184,7 +381,7 @@ fn radioModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu } /// The CUDA engines a native server opens (native/cuda.zig), over the given runtime and families. -fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, heat: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { +fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, heat: *std.Build.Module, drama: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const mod = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda.zig"), @@ -199,6 +396,7 @@ fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti .{ .name = "lfm2", .module = lfm2Module(b, target, optimize, cuda, core) }, .{ .name = "core", .module = core }, .{ .name = "glm_cuda", .module = glmCuda(b, target, optimize, cuda, core, lanes, heat) }, + .{ .name = "drama", .module = drama }, }, }); return .{ .api = api, .engines = mod }; @@ -210,8 +408,8 @@ fn checkpointCli(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. } /// `zig build native`: tensorfold-native with the CUDA engines into zig-out/native/bin, as the Metal build makes it. -fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, heat: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { - const m = engines(b, target, optimize, cuda, core, lanes, nemotron, heat); +fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, heat: *std.Build.Module, drama: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { + const m = engines(b, target, optimize, cuda, core, lanes, nemotron, heat, drama); // the HTTP side keeps its safety checks; the engine below it runs at `optimize` (the tokenizer is the family's) const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ @@ -240,7 +438,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/build/check_fatbins.zig"), .target = host }) })).step); const cuda = runtime(b, host, .debug, &.{}); const mods = family(b, host, .debug, cuda, draft_ids); - const native_modules = engines(b, host, .debug, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat); + const native_modules = engines(b, host, .debug, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.drama); const native = native_modules.engines; // the HTTP server's unit tests (zig/src/server/root.zig), which the macOS build runs, on Linux hosts too const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = host, .optimize = .debug, .link_libc = true }); @@ -268,7 +466,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st @import("cortheon_fuzz.zig").add(b, host, native_modules.api, mods.tokenizer, template); } // the tokenizer's own tests (memo, steps, regex, unicode) run here: no other test binary reaches them - for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, lfm2Module(b, host, .debug, cuda, mods.core), mods.radio, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, lfm2Module(b, host, .debug, cuda, mods.core), mods.radio, mods.drama, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); // the GLM-5.3-Flash CUDA family's host side const glm = glmCuda(b, host, .debug, cuda, mods.core, mods.lanes, mods.heat); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = glm })).step); @@ -317,7 +515,7 @@ pub fn distServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *s }; const cuda = runtime(b, target, .fast, if (prebuilt != null) &images else &.{}); const mods = family(b, target, .fast, cuda, draft_ids); - return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, build_options, false); + return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.drama, mods.tokenizer, build_options, false); } /// SASS targets every release fatbin holds: Ampere (sm_80, sm_86), RTX 50/PRO Blackwell (sm_120), GB10 (sm_121). diff --git a/zig/kernels/cuda/drama_backbone.cu b/zig/kernels/cuda/drama_backbone.cu new file mode 100644 index 00000000000..9c7ca22823c --- /dev/null +++ b/zig/kernels/cuda/drama_backbone.cu @@ -0,0 +1,467 @@ +// Drama backbone glue in fp32, rounded to bf16 where SGLang v0.5.21, FlashInfer 0.6.18 and FLA store or cast. + +#include +#include +#include +#include + +namespace drama { + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } +__device__ __forceinline__ __nv_bfloat16 tobf(float v) { return __float2bfloat16_rn(v); } +__device__ __forceinline__ float round_bf(float v) { return bf(tobf(v)); } + +__device__ __forceinline__ float warp_sum(float x) { +#pragma unroll + for (int m = 16; m; m >>= 1) x += __shfl_xor_sync(0xffffffffu, x, m); + return x; +} + +__device__ __forceinline__ float warp_max(float x) { +#pragma unroll + for (int m = 16; m; m >>= 1) x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, m)); + return x; +} + +// Block-wide sum for blocks of `nwarps` full warps; every thread gets the total. +__device__ __forceinline__ float block_sum(float x, float* scratch, int nwarps) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + x = warp_sum(x); + if (lane == 0) scratch[warp] = x; + __syncthreads(); + float s = lane < nwarps ? scratch[lane] : 0.f; + s = warp_sum(s); + __syncthreads(); + return s; +} + +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +__device__ __forceinline__ float silu(float x) { return x / (1.0f + expf(-x)); } + +__device__ __forceinline__ void load8(const __nv_bfloat16* p, float (&v)[8]) { + const uint4 u = *reinterpret_cast(p); + const __nv_bfloat16* b = reinterpret_cast(&u); +#pragma unroll + for (int i = 0; i < 8; ++i) v[i] = bf(b[i]); +} + +__device__ __forceinline__ void store8(__nv_bfloat16* p, const float (&v)[8]) { + uint4 u; + __nv_bfloat16* b = reinterpret_cast<__nv_bfloat16*>(&u); +#pragma unroll + for (int i = 0; i < 8; ++i) b[i] = tobf(v[i]); + *reinterpret_cast(p) = u; +} + +// drama_act_quant's e4m3 byte of v under its group's multiplier inv = 448 / amax. +__device__ __forceinline__ uint32_t e4m3(float v, float inv) { + const float c = fminf(fmaxf(v * inv, -448.0f), 448.0f); + return static_cast(__nv_cvt_float_to_fp8(c, __NV_SATFINITE, __NV_E4M3)); +} + +} // namespace drama + +using namespace drama; + +// Semantic rows (ids in [lo, hi]): bf16(bf16(out + extra) * 0.70710677), as embed_backbone; other rows keep out. +extern "C" __global__ void __launch_bounds__(256) drama_semantic_mix(const int* ids, __nv_bfloat16* out, + const __nv_bfloat16* extra, int width, + int lo, int hi) { + const int r = blockIdx.x; + const int id = ids[r]; + if (id < lo || id > hi) return; + const float scale = 0.70710678118654752f; + __nv_bfloat16* o = out + static_cast(r) * width; + const __nv_bfloat16* e = extra + static_cast(r) * width; + for (int i = threadIdx.x; i < width; i += blockDim.x) { + const float s = round_bf(bf(o[i]) + bf(e[i])); + o[i] = tobf(s * scale); + } +} + +// GemmaRMSNorm in FlashInfer's CuTe order with one bf16 residual store; q / s (both or neither) add its FP8 groups. +extern "C" __global__ void __launch_bounds__(256) drama_add_norm(const __nv_bfloat16* x, __nv_bfloat16* res, + const __nv_bfloat16* w, __nv_bfloat16* y, + uint8_t* q, float* s, int width, float eps, + int first) { + __shared__ float square_sum; + const size_t base = static_cast(blockIdx.x) * width; + const int t = threadIdx.x; + if (t < 32) { + // Unrolled so every load is in flight before the FMA chain, which keeps the serial reference order. + float sum = 0.f; +#pragma unroll 8 + for (int block = 0; block < width; block += 256) { + float value[8], other[8]; + load8(x + base + block + 8 * t, value); + if (!first) load8(res + base + block + 8 * t, other); +#pragma unroll + for (int v = 0; v < 8; ++v) { + if (!first) value[v] += other[v]; + sum = fmaf(value[v], value[v], sum); + } + } + for (int offset = 1; offset < 32; offset <<= 1) + sum += __shfl_xor_sync(0xffffffffu, sum, offset); + if (t == 0) square_sum = sum; + } + __syncthreads(); + const float rcp = rsqrtf(square_sum / static_cast(width) + eps); + for (int c = 8 * t; c < width; c += 8 * blockDim.x) { + float value[8], other[8], weight[8], out[8]; + load8(x + base + c, value); + if (!first) load8(res + base + c, other); + load8(w + c, weight); +#pragma unroll + for (int i = 0; i < 8; ++i) { + if (!first) value[i] += other[i]; + out[i] = value[i] * rcp * (1.0f + weight[i]); + } + store8(res + base + c, value); + store8(y + base + c, out); + if (q == nullptr) continue; + // A 128-wide group is 16 lanes; the max is exact in any order. + float amax = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + out[i] = round_bf(out[i]); + amax = fmaxf(amax, fabsf(out[i])); + } +#pragma unroll + for (int m = 8; m; m >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, m)); + amax = fmaxf(amax, 1e-10f); + const float inv = __fdividef(448.0f, amax); + uint2 packed = {0u, 0u}; +#pragma unroll + for (int i = 0; i < 4; ++i) { + packed.x |= e4m3(out[i], inv) << (8 * i); + packed.y |= e4m3(out[4 + i], inv) << (8 * i); + } + *reinterpret_cast(q + base + c) = packed; + if ((t & 15) == 0) s[static_cast(blockIdx.x) * (width / 128) + c / 128] = amax * (1.0f / 448.0f); + } +} + +// Value-head gated RMSNorm in SGLang FLA's full-extend order (8 values a lane, 2 heads a warp) for every row count. +extern "C" __global__ void __launch_bounds__(256) drama_gated_rms_128( + const __nv_bfloat16* y, long long y_ld, + const __nv_bfloat16* z, long long z_ld, + const __nv_bfloat16* w, __nv_bfloat16* out, float eps) { + const int sub = threadIdx.x & 15; + const int hd = (blockIdx.y * blockDim.x + threadIdx.x) / 16; + const long long row = blockIdx.x; + float v[8], gate[8], weight[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int col = sub * 8 + i; + v[i] = __bfloat162float(y[row * y_ld + hd * 128 + col]); + gate[i] = __bfloat162float(z[row * z_ld + hd * 128 + col]); + weight[i] = __bfloat162float(w[col]); + } + float sum = __fmul_rn(v[1], v[1]); + sum = __fmaf_rn(v[0], v[0], sum); +#pragma unroll + for (int i = 2; i < 8; ++i) sum = __fmaf_rn(v[i], v[i], sum); +#pragma unroll + for (int mask = 8; mask > 0; mask >>= 1) + sum = __fadd_rn(sum, __shfl_xor_sync(0xffffffffu, sum, mask)); + float variance; + asm("div.full.f32 %0, %1, %2;" : "=f"(variance) : "f"(sum), "f"(128.0f)); + variance = __fadd_rn(variance, eps); + float inv; + asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(variance)); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float exponent = __fmul_rn(__fsub_rn(0.0f, gate[i]), __int_as_float(0x3fb8aa3b)); + float e; + asm("ex2.approx.f32 %0, %1;" : "=f"(e) : "f"(exponent)); + const float denom = __fadd_rn(e, 1.0f); + float sigmoid; + asm("div.full.f32 %0, %1, %2;" : "=f"(sigmoid) : "f"(1.0f), "f"(denom)); + const float norm = __fmul_rn(__fmul_rn(v[i], inv), weight[i]); + const float result = __fmul_rn(norm, __fmul_rn(gate[i], sigmoid)); + out[(row * 32 + hd) * 128 + sub * 8 + i] = __float2bfloat16_rn(result); + } +} + +// Causal depthwise conv (kernel 4) and silu as causal_conv1d_update, fp32 products; state: the 3 previous inputs. +extern "C" __global__ void __launch_bounds__(256) drama_gdn_conv(const __nv_bfloat16* in, int ld_in, + const __nv_bfloat16* w, __nv_bfloat16* state, + __nv_bfloat16* out, int rows, int C) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + const float w0 = bf(w[4 * c]), w1 = bf(w[4 * c + 1]), w2 = bf(w[4 * c + 2]), w3 = bf(w[4 * c + 3]); + __nv_bfloat16 h0 = state[c], h1 = state[C + c], h2 = state[2 * C + c]; + for (int t = 0; t < rows; ++t) { + const __nv_bfloat16 xt = in[static_cast(t) * ld_in + c]; + float acc = w0 * bf(h0); + acc += w1 * bf(h1); + acc += w2 * bf(h2); + acc += w3 * bf(xt); + out[static_cast(t) * C + c] = tobf(silu(acc)); + h0 = h1; + h1 = h2; + h2 = xt; + } + state[c] = h0; + state[C + c] = h1; + state[2 * C + c] = h2; +} + +// Prefill conv as the Triton kernel: bf16 products, fp32 accumulation, ex2.approx / div.full activation. +extern "C" __global__ void __launch_bounds__(256) drama_gdn_conv_prefill( + const __nv_bfloat16* in, int ld_in, const __nv_bfloat16* w, __nv_bfloat16* state, + __nv_bfloat16* out, int rows, int C) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + const float w0 = bf(w[4 * c]), w1 = bf(w[4 * c + 1]), w2 = bf(w[4 * c + 2]), w3 = bf(w[4 * c + 3]); + __nv_bfloat16 h0 = state[c], h1 = state[C + c], h2 = state[2 * C + c]; + for (int t = 0; t < rows; ++t) { + const __nv_bfloat16 xt = in[static_cast(t) * ld_in + c]; + float acc = 0.0f + bf(tobf(w0 * bf(h0))); + acc += bf(tobf(w1 * bf(h1))); + acc += bf(tobf(w2 * bf(h2))); + acc += bf(tobf(w3 * bf(xt))); + const float exponent = __fmul_rn(__fsub_rn(0.0f, acc), __int_as_float(0x3fb8aa3b)); + float exponential; + asm("ex2.approx.f32 %0, %1;" : "=f"(exponential) : "f"(exponent)); + const float denominator = __fadd_rn(1.0f, exponential); + float y; + asm("div.full.f32 %0, %1, %2;" : "=f"(y) : "f"(acc), "f"(denominator)); + out[static_cast(t) * C + c] = tobf(y); + h0 = h1; + h1 = h2; + h2 = xt; + } + state[c] = h0; + state[C + c] = h1; + state[2 * C + c] = h2; +} + +// Packed gated-delta decode as FLA's fused_recurrent.py, q/k normalized in fp32; state fp32 [NV][128 v][128 k]. +extern "C" __global__ void __launch_bounds__(128) drama_gdn_recur(const __nv_bfloat16* qkv, int ld_qkv, + const __nv_bfloat16* ba, int ld_ba, + const float* a_log, const float* dt_bias, + float* state, __nv_bfloat16* y, int rows, int nk, + int nv, float scale) { + constexpr int DK = 128, DV = 128, R = 8; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int head = blockIdx.y; + const int col0 = (blockIdx.x * 4 + warp) * R; + const int kh = head / (nv / nk); + float* s0 = state + static_cast(head) * DV * DK; + float s[R][4]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float4 v = *reinterpret_cast(s0 + static_cast(col0 + r) * DK + lane * 4); + s[r][0] = v.x; + s[r][1] = v.y; + s[r][2] = v.z; + s[r][3] = v.w; + } + const float A = expf(a_log[head]); + const float bias = dt_bias[head]; + for (int t = 0; t < rows; ++t) { + const __nv_bfloat16* row = qkv + static_cast(t) * ld_qkv; + float q[4], k[4], v[R]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + q[i] = bf(row[kh * DK + lane * 4 + i]); + k[i] = bf(row[nk * DK + kh * DK + lane * 4 + i]); + } +#pragma unroll + for (int r = 0; r < R; ++r) v[r] = bf(row[2 * nk * DK + head * DV + col0 + r]); + const float bb = bf(ba[static_cast(t) * ld_ba + head]); + const float aa = bf(ba[static_cast(t) * ld_ba + nv + head]); + const float x = aa + bias; + const float sp = x <= 20.0f ? logf(1.0f + expf(x)) : x; + const float decay = expf(-A * sp); + const float beta = round_bf(1.0f / (1.0f + expf(-bb))); + float qq = 0.f, kk = 0.f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + qq += q[i] * q[i]; + kk += k[i] * k[i]; + } + qq = warp_sum(qq); + kk = warp_sum(kk); + const float qn = sqrtf(qq + 1e-6f), kn = sqrtf(kk + 1e-6f); +#pragma unroll + for (int i = 0; i < 4; ++i) { + q[i] = (q[i] / qn) * scale; + k[i] = k[i] / kn; + } +#pragma unroll + for (int r = 0; r < R; ++r) { + float mem = 0.f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + s[r][i] *= decay; + mem += s[r][i] * k[i]; + } + mem = warp_sum(mem); + const float delta = (v[r] - mem) * beta; + float o = 0.f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + s[r][i] += k[i] * delta; + o += s[r][i] * q[i]; + } + o = warp_sum(o); + if (lane == r) y[(static_cast(t) * nv + head) * DV + col0 + r] = tobf(o); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) + *reinterpret_cast(s0 + static_cast(col0 + r) * DK + lane * 4) = + make_float4(s[r][0], s[r][1], s[r][2], s[r][3]); +} + +#include "drama_gdn_chunk.cuh" + +#include "drama_backbone_attention.cuh" + +// Router: softmax over 256 experts, top 8 (lower id on ties), renormalized to sum 1, in descending probability. +extern "C" __global__ void __launch_bounds__(256) drama_topk(const __nv_bfloat16* logits, int ld, int* ids, float* wts, + int top) { + __shared__ float scratch[32]; + __shared__ float bv[8]; + __shared__ int bi[8]; + __shared__ float picked_p[8]; + __shared__ int picked_i[8]; + const int r = blockIdx.x, e = threadIdx.x, lane = e & 31, warp = e >> 5; + const float x = bf(logits[static_cast(r) * ld + e]); + float mx = warp_max(x); + if (lane == 0) scratch[warp] = mx; + __syncthreads(); + mx = lane < 8 ? scratch[lane] : -INFINITY; + mx = warp_max(mx); + __syncthreads(); + const float ex = expf(x - mx); + const float sum = block_sum(ex, scratch, 8); + float p = ex / sum; + bool taken = false; + for (int k = 0; k < top; ++k) { + float cv = taken ? -1.0f : p; + int ci = e; +#pragma unroll + for (int m = 16; m; m >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, cv, m); + const int oi = __shfl_xor_sync(0xffffffffu, ci, m); + if (ov > cv || (ov == cv && oi < ci)) { + cv = ov; + ci = oi; + } + } + if (lane == 0) { + bv[warp] = cv; + bi[warp] = ci; + } + __syncthreads(); + if (e == 0) { + float best = bv[0]; + int at = bi[0]; + for (int w = 1; w < 8; ++w) + if (bv[w] > best || (bv[w] == best && bi[w] < at)) { + best = bv[w]; + at = bi[w]; + } + picked_p[k] = best; + picked_i[k] = at; + } + __syncthreads(); + if (e == picked_i[k]) taken = true; + } + if (e == 0) { + float s = 0.f; + for (int k = 0; k < top; ++k) s += picked_p[k]; + for (int k = 0; k < top; ++k) { + ids[r * top + k] = picked_i[k]; + wts[r * top + k] = picked_p[k] / s; + } + } +} + +// Group-128 FP8 quantization; the pinned JIT's fast-math 448 / amax multiplier stays local, with __fdividef. +extern "C" __global__ void __launch_bounds__(128) drama_act_quant(const __nv_bfloat16* x, int ld_x, uint8_t* q, + float* s, int K) { + const int r = blockIdx.x, warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int group = blockIdx.y * 4 + warp; + if (group * 128 >= K) return; + const __nv_bfloat16* xr = x + static_cast(r) * ld_x + group * 128 + lane * 4; + float v[4]; + float amax = 0.f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + v[i] = bf(xr[i]); + amax = fmaxf(amax, fabsf(v[i])); + } + amax = fmaxf(warp_max(amax), 1e-10f); + const float sc = amax * (1.0f / 448.0f); + const float inv = __fdividef(448.0f, amax); + uint32_t packed = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) packed |= e4m3(v[i], inv) << (8 * i); + *reinterpret_cast(q + static_cast(r) * K + group * 128 + lane * 4) = packed; + if (lane == 0) s[static_cast(r) * (K / 128) + group] = sc; +} + +// SwiGLU in one launch: rows below routed FP8-quantized into hq / hs, the shared expert's rows stored bf16 to h_out. +extern "C" __global__ void __launch_bounds__(128) drama_silu_mul(const __nv_bfloat16* gu, int ld_gu, int routed, + uint8_t* hq, float* hs, const __nv_bfloat16* sgu, + int ld_sgu, __nv_bfloat16* h_out, int I) { + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int group = blockIdx.y * 4 + warp; + if (group * 128 >= I) return; + const bool quant = blockIdx.x < routed; + const int r = quant ? blockIdx.x : blockIdx.x - routed; + const int c0 = group * 128 + lane * 4; + const __nv_bfloat16* row = quant ? gu + static_cast(r) * ld_gu : sgu + static_cast(r) * ld_sgu; + float h[4]; + float amax = 0.f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + h[i] = round_bf(silu(bf(row[c0 + i])) * bf(row[I + c0 + i])); + amax = fmaxf(amax, fabsf(h[i])); + } + if (!quant) { +#pragma unroll + for (int i = 0; i < 4; ++i) h_out[static_cast(r) * I + c0 + i] = tobf(h[i]); + return; + } + amax = fmaxf(warp_max(amax), 1e-10f); + const float sc = amax * (1.0f / 448.0f); + const float inv = __fdividef(448.0f, amax); + uint32_t packed = 0; +#pragma unroll + for (int i = 0; i < 4; ++i) packed |= e4m3(h[i], inv) << (8 * i); + *reinterpret_cast(hq + static_cast(r) * I + c0) = packed; + if (lane == 0) hs[static_cast(r) * (I / 128) + group] = sc; +} + +// MoE output as moe_sum_reduce then fused_gate_sigmoid_mul_add; a thread owns 8 contiguous outputs, width % 8 == 0. +extern "C" __global__ void __launch_bounds__(256) drama_moe_combine(const __nv_bfloat16* down, int top, + const __nv_bfloat16* x, const __nv_bfloat16* wg, + const __nv_bfloat16* shared, __nv_bfloat16* out, + int width) { + __shared__ float scratch[32]; + const size_t r = blockIdx.x; + float part = 0.f; + for (int i = threadIdx.x; i < width; i += 256) part += bf(x[r * width + i]) * bf(wg[i]); + const float gate = sigmoid(block_sum(part, scratch, 8)); + for (int c = 8 * threadIdx.x; c < width; c += 8 * 256) { + float acc[8], value[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) acc[i] = 0.f; +#pragma unroll 8 + for (int s = 0; s < top; ++s) { + load8(down + (r * top + s) * width + c, value); +#pragma unroll + for (int i = 0; i < 8; ++i) acc[i] += value[i]; + } + load8(shared + r * width + c, value); +#pragma unroll + for (int i = 0; i < 8; ++i) value[i] = gate * value[i] + round_bf(acc[i]); + store8(out + r * width + c, value); + } +} diff --git a/zig/kernels/cuda/drama_backbone_attention.cuh b/zig/kernels/cuda/drama_backbone_attention.cuh new file mode 100644 index 00000000000..250bc22e585 --- /dev/null +++ b/zig/kernels/cuda/drama_backbone_attention.cuh @@ -0,0 +1,180 @@ +// Backbone full attention: Q/K norm and RoPE prologue, KV append and causal GQA; included by drama_backbone.cu. +#pragma once + +// fused_qk_gemma_rmsnorm_rope_gate for one head: bf16 Gemma norm, NeoX RoPE on 64 dims in fp32, rounded at the store. +__device__ __forceinline__ void qk_norm_rope(const __nv_bfloat16* src, const __nv_bfloat16* w, const float* inv_freq, + int pos, float eps, int lane, float (&o)[8]) { + constexpr int D = 256, ROT = 64, HALF = 32; + float v[8]; + float ss = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) { + v[i] = bf(src[lane * 8 + i]); + ss += v[i] * v[i]; + } + ss = warp_sum(ss); + const float rcp = rsqrtf(ss / static_cast(D) + eps); +#pragma unroll + for (int i = 0; i < 8; ++i) v[i] = round_bf(v[i] * rcp * (1.0f + bf(w[lane * 8 + i]))); + // lanes 0..3 hold dims 0..31, lanes 4..7 dims 32..63: partner lane ^ 4 +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float other = __shfl_xor_sync(0xffffffffu, v[i], 4); + const int d = lane * 8 + i; + if (d < ROT) { + const float ang = static_cast(pos) * inv_freq[d % HALF]; + const float c = cosf(ang), s = sinf(ang); + o[i] = d < HALF ? v[i] * c - other * s : v[i] * c + other * s; + } else { + o[i] = v[i]; + } + } +} + +// Q/K prologue for each head of a row: q to q_out [rows][H][256], k and v to the caches at pos0 + row. +extern "C" __global__ void __launch_bounds__(32) drama_attn_prep(const __nv_bfloat16* qkv, int ld_qkv, + const __nv_bfloat16* qn_w, const __nv_bfloat16* kn_w, + const float* inv_freq, __nv_bfloat16* q_out, + __nv_bfloat16* kc, __nv_bfloat16* vc, int pos0, int H, + int HK, float eps) { + constexpr int D = 256; + const int r = blockIdx.x, h = blockIdx.y, lane = threadIdx.x; + const int pos = pos0 + r; + const __nv_bfloat16* row = qkv + static_cast(r) * ld_qkv; + const bool is_q = h < H; + const int kh = h - H; + const __nv_bfloat16* src = is_q ? row + h * 2 * D : row + H * 2 * D + kh * D; + float o[8]; + qk_norm_rope(src, is_q ? qn_w : kn_w, inv_freq, pos, eps, lane, o); + __nv_bfloat16* dst = is_q ? q_out + (static_cast(r) * H + h) * D + : kc + (static_cast(pos) * HK + kh) * D; +#pragma unroll + for (int i = 0; i < 8; ++i) dst[lane * 8 + i] = tobf(o[i]); + if (!is_q) { + const __nv_bfloat16* vs = row + H * 2 * D + HK * D + kh * D; + __nv_bfloat16* vd = vc + (static_cast(pos) * HK + kh) * D; +#pragma unroll + for (int i = 0; i < 8; ++i) vd[lane * 8 + i] = vs[lane * 8 + i]; + } +} + +// Causal GQA attention as Triton's (bf16(p) in P.V) with the sigmoid gate; given qn_w, one row runs the prologue too. +extern "C" __global__ void __launch_bounds__(256) drama_attention(const __nv_bfloat16* q, __nv_bfloat16* kc, + __nv_bfloat16* vc, const __nv_bfloat16* qkv, + int ld_qkv, __nv_bfloat16* out, int pos0, int H, + int HK, float scale, const __nv_bfloat16* qn_w, + const __nv_bfloat16* kn_w, const float* inv_freq, + float eps) { + constexpr int D = 256, NW = 8, U = 8; + __shared__ float sm_m[NW], sm_l[NW]; + __shared__ float sm_o[NW][D]; + const int r = blockIdx.x, h = blockIdx.y; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int kh = h / (H / HK); + const int last = pos0 + r; + const bool prologue = qn_w != nullptr; + const __nv_bfloat16* row = qkv + static_cast(r) * ld_qkv; + // Cached keys go U at a time with loads in flight; with no cached key (the fused row at 0) nothing is loaded. + const int cached = prologue ? last - 1 : last; + const __nv_bfloat16* kp = kc + kh * D + lane * 8; + const __nv_bfloat16* vp = vc + kh * D + lane * 8; + uint4 kw[U], vw[U]; + if (cached >= 0) { +#pragma unroll + for (int u = 0; u < U; ++u) { + const size_t at = static_cast(min(warp + u * NW, cached)) * HK * D; + kw[u] = *reinterpret_cast(kp + at); + vw[u] = *reinterpret_cast(vp + at); + } + } + float qv[8], o[8]; + if (prologue) { + qk_norm_rope(row + h * 2 * D, qn_w, inv_freq, last, eps, lane, qv); +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = round_bf(qv[i]); + } else { + const __nv_bfloat16* qr = q + (static_cast(r) * H + h) * D + lane * 8; +#pragma unroll + for (int i = 0; i < 8; ++i) qv[i] = bf(qr[i]); + } + // The row's own key is the last key of warp last % NW; scored now, while the first loads are in flight. + const bool own = prologue && warp == last % NW; + float own_score = 0.f; + uint4 own_value{}; + if (own) { + float kv[8]; + qk_norm_rope(row + H * 2 * D + kh * D, kn_w, inv_freq, last, eps, lane, kv); + own_value = *reinterpret_cast(row + H * 2 * D + HK * D + kh * D + lane * 8); + float dot = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) dot += qv[i] * round_bf(kv[i]); + own_score = warp_sum(dot) * scale; + if (h % (H / HK) == 0) { + const size_t at = (static_cast(last) * HK + kh) * D + lane * 8; + store8(kc + at, kv); + *reinterpret_cast(vc + at) = own_value; + } + } +#pragma unroll + for (int i = 0; i < 8; ++i) o[i] = 0.f; + float m = -INFINITY, l = 0.f; + const auto step = [&](float score, const uint4& value) { + const float mn = fmaxf(m, score); + const float corr = expf(m - mn); // m = -inf on the first key: 0 + const float p = expf(score - mn); + l = l * corr + p; + const __nv_bfloat16* v = reinterpret_cast(&value); +#pragma unroll + for (int i = 0; i < 8; ++i) o[i] = o[i] * corr + round_bf(p) * bf(v[i]); + m = mn; + }; + for (int j0 = warp; j0 <= cached; j0 += NW * U) { + float sc[U]; + uint4 vb[U]; +#pragma unroll + for (int u = 0; u < U; ++u) { + const __nv_bfloat16* k = reinterpret_cast(&kw[u]); + float dot = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) dot += qv[i] * bf(k[i]); + sc[u] = dot; + vb[u] = vw[u]; + const size_t at = static_cast(min(j0 + (U + u) * NW, cached)) * HK * D; + kw[u] = *reinterpret_cast(kp + at); + vw[u] = *reinterpret_cast(vp + at); + } +#pragma unroll + for (int u = 0; u < U; ++u) sc[u] = warp_sum(sc[u]) * scale; + const int n = min(U, (cached - j0) / NW + 1); +#pragma unroll + for (int u = 0; u < U; ++u) { + if (u >= n) break; + step(sc[u], vb[u]); + } + } + if (own) step(own_score, own_value); + if (lane == 0) { + sm_m[warp] = m; + sm_l[warp] = l; + } +#pragma unroll + for (int i = 0; i < 8; ++i) sm_o[warp][lane * 8 + i] = o[i]; + __syncthreads(); + float M = -INFINITY; +#pragma unroll + for (int w = 0; w < NW; ++w) M = fmaxf(M, sm_m[w]); + float L = 0.f; + float f[NW]; +#pragma unroll + for (int w = 0; w < NW; ++w) { + f[w] = sm_l[w] > 0.f ? expf(sm_m[w] - M) : 0.f; + L += sm_l[w] * f[w]; + } + const int d = threadIdx.x; // 256 threads, one dim each + float acc = 0.f; +#pragma unroll + for (int w = 0; w < NW; ++w) acc += sm_o[w][d] * f[w]; + const float attn = round_bf(acc / L); + const float gate = bf(qkv[static_cast(r) * ld_qkv + h * 2 * D + D + d]); + out[(static_cast(r) * H + h) * D + d] = tobf(attn * sigmoid(gate)); +} diff --git a/zig/kernels/cuda/drama_backbone_gemm.cu b/zig/kernels/cuda/drama_backbone_gemm.cu new file mode 100644 index 00000000000..eaa6498bc41 --- /dev/null +++ b/zig/kernels/cuda/drama_backbone_gemm.cu @@ -0,0 +1,311 @@ +// Backbone bf16 projections (fp32 accumulate, ascending K16 groups) and the routed experts' block-FP8 W8A8 products. + +#include +#include + +namespace drama_gemm { + +constexpr int WARPS = 4; + +__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) { + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); +} + +// e4m3 mma needs sm_89 or newer; older images trap (Model.init refuses those devices before any launch). +__device__ __forceinline__ void mma_e4m3(float (&d)[4], uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, + uint32_t b0, uint32_t b1) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 890 + asm volatile( + "mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); +#else + __trap(); +#endif +} + +__device__ __forceinline__ uint4 ld_nc(const uint4* p) { + uint4 r; + asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0, %1, %2, %3}, [%4];\n" + : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) + : "l"(p)); + return r; +} + +__device__ __forceinline__ uint32_t word(const uint4& v, int i) { + return i == 0 ? v.x : i == 1 ? v.y : i == 2 ? v.z : v.w; +} + +// OUT 0: bf16; 2: fp32 holding the bf16-rounded value (a bf16 torch output read back as float). +template +__device__ __forceinline__ void store(void* y, size_t at, float v) { + if constexpr (OUT == 0) { + static_cast<__nv_bfloat16*>(y)[at] = __float2bfloat16_rn(v); + } else { + static_cast(y)[at] = __bfloat162float(__float2bfloat16_rn(v)); + } +} + +// Y[m, n] = sum_k X[m, k] W[n, k]; a warp owns NT 8-column tiles of a 16 * RT-row tile; K % 32 == 0. +template +__device__ __forceinline__ void gemm_bf16(const __nv_bfloat16* __restrict__ X, int ldx, int M, + const __nv_bfloat16* __restrict__ W, int N, int K, void* __restrict__ Y, + int ldy) { + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + const int col0 = (blockIdx.x * WARPS + warp) * (8 * NT); + if (col0 >= N) return; + const int row0 = blockIdx.y * 16 * RT; + const uint32_t* xa[RT]; + const uint32_t* xb[RT]; + bool va[RT], vb[RT]; +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int ra = row0 + r * 16 + g, rb = ra + 8; + va[r] = ra < M; + vb[r] = rb < M; + xa[r] = reinterpret_cast(X + static_cast(va[r] ? ra : 0) * ldx); + xb[r] = reinterpret_cast(X + static_cast(vb[r] ? rb : 0) * ldx); + } + const uint32_t* wp[NT]; +#pragma unroll + for (int j = 0; j < NT; ++j) { + const int n = col0 + j * 8 < N ? col0 + j * 8 + g : g; // dead tiles read row g and store nothing + wp[j] = reinterpret_cast(W + static_cast(n) * K); + } + float acc[RT][NT][4]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NT; ++j) acc[r][j][0] = acc[r][j][1] = acc[r][j][2] = acc[r][j][3] = 0.f; + const int chunks = K / 32; +#pragma unroll 2 + for (int c = 0; c < chunks; ++c) { +#pragma unroll + for (int s = 0; s < 2; ++s) { + // Each word holds k=32c+16s+2t and k+1; the second fragment is eight k positions later. + const int lo = 16 * c + 8 * s + t; + uint32_t b0[NT], b1[NT], a0[RT], a1[RT], a2[RT], a3[RT]; +#pragma unroll + for (int j = 0; j < NT; ++j) { + b0[j] = __ldg(wp[j] + lo); + b1[j] = __ldg(wp[j] + lo + 4); + } +#pragma unroll + for (int r = 0; r < RT; ++r) { + a0[r] = va[r] ? __ldg(xa[r] + lo) : 0u; + a2[r] = va[r] ? __ldg(xa[r] + lo + 4) : 0u; + a1[r] = vb[r] ? __ldg(xb[r] + lo) : 0u; + a3[r] = vb[r] ? __ldg(xb[r] + lo + 4) : 0u; + } +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NT; ++j) + mma_bf16(acc[r][j], a0[r], a1[r], a2[r], a3[r], b0[j], b1[j]); + } + } +#pragma unroll + for (int r = 0; r < RT; ++r) { + const int ra = row0 + r * 16 + g, rb = ra + 8; +#pragma unroll + for (int j = 0; j < NT; ++j) { +#pragma unroll + for (int q = 0; q < 2; ++q) { + const int n = col0 + j * 8 + 2 * t + q; + if (n >= N) continue; + if (ra < M) store<0>(Y, static_cast(ra) * ldy + n, acc[r][j][q]); + if (rb < M) store<0>(Y, static_cast(rb) * ldy + n, acc[r][j][2 + q]); + } + } + } +} + +__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { + const uint32_t s = static_cast(__cvta_generic_to_shared(smem)); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(s), "l"(gmem)); +} + +__device__ __forceinline__ void ldmatrix_x4(uint32_t (&r)[4], const void* smem) { + const uint32_t s = static_cast(__cvta_generic_to_shared(smem)); + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"(s)); +} + +// One row, bit-identical to gemm_bf16<1, 1> (OUT 0) or the head's grouping (OUT 2), weights in a swizzled ring. +constexpr int GEMV_STAGES = 3; +constexpr int GEMV_CHUNK = 256; +constexpr int GEMV_ROW = GEMV_CHUNK * 2; +constexpr int GEMV_STAGE = 8 * GEMV_ROW; +static_assert(GEMV_ROW == 32 * 16, "a stage row is one 16-byte copy a lane"); + +template +__device__ __forceinline__ void gemv_bf16(const __nv_bfloat16* __restrict__ X, const __nv_bfloat16* __restrict__ W, + int N, int K, void* __restrict__ Y) { + __shared__ __align__(128) unsigned char ring[GEMV_STAGES * GEMV_STAGE]; + const int lane = threadIdx.x, g = lane >> 2, t = lane & 3; + const int col0 = blockIdx.x * 8; + const unsigned char* rows = reinterpret_cast(W + static_cast(col0) * K); + const int chunks = K / GEMV_CHUNK; + auto issue = [&](int c) { + unsigned char* stage = ring + (c % GEMV_STAGES) * GEMV_STAGE; +#pragma unroll + for (int r = 0; r < 8; ++r) + cp_async16(stage + r * GEMV_ROW + 16 * (lane ^ r), + rows + static_cast(r) * K * 2 + static_cast(c) * GEMV_ROW + 16 * lane); + }; +#pragma unroll + for (int c = 0; c < GEMV_STAGES - 1; ++c) { + if (c < chunks) issue(c); + asm volatile("cp.async.commit_group;\n"); + } + const bool live = g == 0; // the single row is A's row 0; rows 1..15 are zero as in gemm_bf16 + float acc[4] = {0.f, 0.f, 0.f, 0.f}; + for (int c = 0; c < chunks; ++c) { + if (c + GEMV_STAGES - 1 < chunks) issue(c + GEMV_STAGES - 1); + asm volatile("cp.async.commit_group;\n"); + asm volatile("cp.async.wait_group %0;\n" ::"n"(GEMV_STAGES - 1)); + __syncwarp(); + const unsigned char* stage = ring + (c % GEMV_STAGES) * GEMV_STAGE; +#pragma unroll + for (int h = 0; h < GEMV_CHUNK / 32; ++h) { + const __nv_bfloat16* x = X + c * GEMV_CHUNK + 32 * h; + if constexpr (OUT == 0) { + // ldmatrix: lane supplies row lane % 8 of matrix lane / 8, the k octet 4h + lane / 8 + const int r = lane & 7; + uint32_t b[4]; + ldmatrix_x4(b, stage + r * GEMV_ROW + 16 * ((4 * h + (lane >> 3)) ^ r)); + const uint32_t* xw = reinterpret_cast(x) + t; +#pragma unroll + for (int s = 0; s < 2; ++s) { + const uint32_t a0 = live ? __ldg(xw + 8 * s) : 0u, a2 = live ? __ldg(xw + 8 * s + 4) : 0u; + mma_bf16(acc, a0, 0u, a2, 0u, b[2 * s], b[2 * s + 1]); + } + } else { + const uint4 b = *reinterpret_cast(stage + g * GEMV_ROW + 16 * ((4 * h + t) ^ g)); + const uint4 a = live ? __ldg(reinterpret_cast(x) + t) : make_uint4(0u, 0u, 0u, 0u); +#pragma unroll + for (int s = 0; s < 2; ++s) + mma_bf16(acc, word(a, 2 * s), 0u, word(a, 2 * s + 1), 0u, word(b, 2 * s), word(b, 2 * s + 1)); + } + } + __syncwarp(); + } + if (!live) return; +#pragma unroll + for (int q = 0; q < 2; ++q) { + const int n = col0 + 2 * t + q; + if (n < N) store(Y, n, acc[q]); + } +} + +// Routed experts over the experts.cu plan: per 128-k block acc += dot(a_q, w_q) * a_scale * w_scale, as fused_moe. +template +__device__ __forceinline__ void expert_fp8(const uint8_t* __restrict__ A, int a_div, const float* __restrict__ As, + const uint8_t* __restrict__ W, const float* __restrict__ Ws, int N, int K, + const int* __restrict__ items, const int* __restrict__ counts, + const int* __restrict__ members, const float* __restrict__ rw, + __nv_bfloat16* __restrict__ Y) { + const int item = blockIdx.x; + if (item >= __ldg(counts)) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + const int col0 = (blockIdx.y * WARPS + warp) * (8 * NT); + if (col0 >= N) return; + const int e = __ldg(items + 3 * item), first = __ldg(items + 3 * item + 1), cnt = __ldg(items + 3 * item + 2); + const bool v0 = g < cnt, v1 = g + 8 < cnt; + const int p0 = v0 ? __ldg(members + first + g) : 0, p1 = v1 ? __ldg(members + first + g + 8) : 0; + const int r0 = p0 / a_div, r1 = p1 / a_div; + const int KB = K / 128; + const uint4* a0p = reinterpret_cast(A + static_cast(r0) * K) + 2 * t; + const uint4* a1p = reinterpret_cast(A + static_cast(r1) * K) + 2 * t; + const float* s0p = As + static_cast(r0) * KB; + const float* s1p = As + static_cast(r1) * KB; + const uint8_t* we = W + static_cast(e) * N * K; + const uint4* wp[NT]; +#pragma unroll + for (int j = 0; j < NT; ++j) wp[j] = reinterpret_cast(we + static_cast(col0 + j * 8 + g) * K) + 2 * t; + const float* wsp = Ws + (static_cast(e) * (N / 128) + col0 / 128) * KB; + float acc[NT][4]; +#pragma unroll + for (int j = 0; j < NT; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.f; + const uint4 zero = make_uint4(0u, 0u, 0u, 0u); + for (int kb = 0; kb < KB; ++kb) { + // 128 k a block: 32 bytes a lane (two uint4), four k32 steps on the words in pairs + const uint4 a0l = v0 ? __ldg(a0p + 8 * kb) : zero, a0h = v0 ? __ldg(a0p + 8 * kb + 1) : zero; + const uint4 a1l = v1 ? __ldg(a1p + 8 * kb) : zero, a1h = v1 ? __ldg(a1p + 8 * kb + 1) : zero; + float part[NT][4]; +#pragma unroll + for (int j = 0; j < NT; ++j) { + const uint4 bl = ld_nc(wp[j] + 8 * kb), bh = ld_nc(wp[j] + 8 * kb + 1); + part[j][0] = part[j][1] = part[j][2] = part[j][3] = 0.f; +#pragma unroll + for (int s = 0; s < 4; ++s) { + const uint4& a0 = s < 2 ? a0l : a0h; + const uint4& a1 = s < 2 ? a1l : a1h; + const uint4& b = s < 2 ? bl : bh; + const int w0 = 2 * (s & 1); + mma_e4m3(part[j], word(a0, w0), word(a1, w0), word(a0, w0 + 1), word(a1, w0 + 1), word(b, w0), + word(b, w0 + 1)); + } + } + const float sa0 = v0 ? __ldg(s0p + kb) : 0.f, sa1 = v1 ? __ldg(s1p + kb) : 0.f; + const float sw = __ldg(wsp + kb); +#pragma unroll + for (int j = 0; j < NT; ++j) { + acc[j][0] += part[j][0] * sa0 * sw; + acc[j][1] += part[j][1] * sa0 * sw; + acc[j][2] += part[j][2] * sa1 * sw; + acc[j][3] += part[j][3] * sa1 * sw; + } + } + const float w0 = MODE == 1 && v0 ? __ldg(rw + p0) : 1.f; + const float w1 = MODE == 1 && v1 ? __ldg(rw + p1) : 1.f; +#pragma unroll + for (int j = 0; j < NT; ++j) { +#pragma unroll + for (int q = 0; q < 2; ++q) { + const int n = col0 + j * 8 + 2 * t + q; + if (v0) Y[static_cast(p0) * N + n] = __float2bfloat16_rn(MODE == 1 ? acc[j][q] * w0 : acc[j][q]); + if (v1) + Y[static_cast(p1) * N + n] = + __float2bfloat16_rn(MODE == 1 ? acc[j][2 + q] * w1 : acc[j][2 + q]); + } + } +} + +} // namespace drama_gemm + +#define DRAMA_GEMM(RT, NT) \ + extern "C" __global__ void __launch_bounds__(32 * drama_gemm::WARPS) \ + drama_gemm_bf16_r##RT##_n##NT##_o0(const __nv_bfloat16* X, int ldx, int M, const __nv_bfloat16* W, int N, \ + int K, void* Y, int ldy) { \ + drama_gemm::gemm_bf16(X, ldx, M, W, N, K, Y, ldy); \ + } +DRAMA_GEMM(1, 1) +DRAMA_GEMM(2, 2) +DRAMA_GEMM(4, 2) + +#define DRAMA_GEMV(OUT) \ + extern "C" __global__ void __launch_bounds__(32) \ + drama_gemv_bf16_r1_o##OUT(const __nv_bfloat16* X, const __nv_bfloat16* W, int N, int K, void* Y) { \ + drama_gemm::gemv_bf16(X, W, N, K, Y); \ + } +DRAMA_GEMV(0) +DRAMA_GEMV(2) // the semantic head: the last row, bf16-rounded logits widened to fp32 + +#define DRAMA_EXPERT(NT, MODE) \ + extern "C" __global__ void __launch_bounds__(32 * drama_gemm::WARPS) drama_expert_fp8_n##NT##_m##MODE( \ + const uint8_t* A, int a_div, const float* As, const uint8_t* W, const float* Ws, int N, int K, \ + const int* items, const int* counts, const int* members, const float* rw, __nv_bfloat16* Y) { \ + drama_gemm::expert_fp8(A, a_div, As, W, Ws, N, K, items, counts, members, rw, Y); \ + } +DRAMA_EXPERT(1, 0) +DRAMA_EXPERT(2, 0) +DRAMA_EXPERT(1, 1) +DRAMA_EXPERT(2, 1) diff --git a/zig/kernels/cuda/drama_codec.cu b/zig/kernels/cuda/drama_codec.cu new file mode 100644 index 00000000000..33f333fba4f --- /dev/null +++ b/zig/kernels/cuda/drama_codec.cu @@ -0,0 +1,359 @@ +// Drama 3 codec decode (modded DAC quantizer decode and decoder) in sglang-omni's FP16 arithmetic, FP32 reductions. + +#include +#include +#include + +namespace { + +__device__ __forceinline__ float h2f(__half v) { return __half2float(v); } +__device__ __forceinline__ __half f2h(float v) { return __float2half_rn(v); } +// The FP32 value an FP16 tensor would hold. +__device__ __forceinline__ float rh(float v) { return __half2float(__float2half_rn(v)); } + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} + +// Sum over the block (blockDim.x a multiple of 32, at most 1024); every thread gets the total. +__device__ float block_sum(float v, float* part) { + v = warp_sum(v); + const int w = threadIdx.x >> 5, l = threadIdx.x & 31, n = blockDim.x >> 5; + __syncthreads(); + if (l == 0) part[w] = v; + __syncthreads(); + return warp_sum(l < n ? part[l] : 0.f); +} + +__device__ float block_max(float v, float* part) { + v = warp_max(v); + const int w = threadIdx.x >> 5, l = threadIdx.x & 31, n = blockDim.x >> 5; + __syncthreads(); + if (l == 0) part[w] = v; + __syncthreads(); + return warp_max(l < n ? part[l] : -__int_as_float(0x7f800000)); +} + +constexpr int kLatent = 1024; // DownsampleResidualVectorQuantize input_dim +constexpr int kCodebookDim = 8; // codebook_dim +constexpr int kBooks = 10; // 1 semantic + 9 residual +constexpr int kSemanticSize = 4096; +constexpr int kResidualSize = 1024; +constexpr int kHeadDim = 64; + +} // namespace + +// rvq.py decode before post_module: clamped codes, each book's row through out_proj, residual books summed from 0. +extern "C" __global__ void __launch_bounds__(256) drama_codec_rvq_latent( + const uint32_t* __restrict__ codes, const __half* __restrict__ semantic_book, + const __half* __restrict__ residual_books, const __half* __restrict__ out_w, + const __half* __restrict__ out_b, __half* __restrict__ z) { + const size_t t = blockIdx.x; + __shared__ float e[kBooks][kCodebookDim]; + if (threadIdx.x < kBooks * kCodebookDim) { + const int book = threadIdx.x / kCodebookDim, i = threadIdx.x % kCodebookDim; + uint32_t code = codes[t * kBooks + book]; + const __half* row; + if (book == 0) { + code = min(code, (uint32_t)(kSemanticSize - 1)); + row = semantic_book + (size_t)code * kCodebookDim; + } else { + code = min(code, (uint32_t)(kResidualSize - 1)); + row = residual_books + ((size_t)(book - 1) * kResidualSize + code) * kCodebookDim; + } + e[book][i] = h2f(row[i]); + } + __syncthreads(); + for (int c = threadIdx.x; c < kLatent; c += blockDim.x) { + float semantic = 0.f, residual = 0.f; + for (int book = 0; book < kBooks; ++book) { + const __half* w = out_w + ((size_t)book * kLatent + c) * kCodebookDim; + float acc = 0.f; +#pragma unroll + for (int i = 0; i < kCodebookDim; ++i) acc = fmaf(e[book][i], h2f(w[i]), acc); + const float q = rh(rh(acc) + h2f(out_b[book * kLatent + c])); + if (book == 0) semantic = q; + else if (book == 1) residual = 0.f + q; + else residual = rh(residual + q); + } + z[t * kLatent + c] = f2h(semantic + residual); + } +} + +// modded_dac.py RMSNorm: h(h(x * rsqrt(mean(x * x) + eps)) * w), statistics in FP32. +extern "C" __global__ void __launch_bounds__(256) drama_codec_rms_norm( + const __half* __restrict__ x, const __half* __restrict__ w, __half* __restrict__ y, int width, + float eps) { + __shared__ float part[32]; + const __half* xr = x + (size_t)blockIdx.x * width; + __half* yr = y + (size_t)blockIdx.x * width; + float s = 0.f; + for (int c = threadIdx.x; c < width; c += blockDim.x) { + const float v = h2f(xr[c]); + s += __fmul_rn(v, v); + } + s = block_sum(s, part); + const float r = rsqrtf(__fadd_rn(s / (float)width, eps)); + for (int c = threadIdx.x; c < width; c += blockDim.x) + yr[c] = f2h(__fmul_rn(rh(__fmul_rn(h2f(xr[c]), r)), h2f(w[c]))); +} + +// apply_rotary_emb on q and k of a fused qkv row, pairs (2i, 2i + 1) in FP32 as eager PyTorch evaluates them. +extern "C" __global__ void __launch_bounds__(256) drama_codec_rope( + __half* __restrict__ qkv, const __half* __restrict__ table, int width, int ld) { + __half* row = qkv + (size_t)blockIdx.x * ld; + const __half* tab = table + (size_t)blockIdx.x * kHeadDim; + const int pairs = width / 2; + for (int p = threadIdx.x; p < 2 * pairs; p += blockDim.x) { + const int which = p / pairs, pp = p % pairs, i = pp % (kHeadDim / 2); + __half* e = row + which * width + pp * 2; + const float x0 = h2f(e[0]), x1 = h2f(e[1]); + const float c = h2f(tab[2 * i]), s = h2f(tab[2 * i + 1]); + e[0] = f2h(__fsub_rn(__fmul_rn(x0, c), __fmul_rn(x1, s))); + e[1] = f2h(__fadd_rn(__fmul_rn(x1, c), __fmul_rn(x0, s))); + } +} + +// Causal window attention as Torch's efficient path for queries t0.. at their absolute rows; FP16 P, FP32 sums. +extern "C" __global__ void __launch_bounds__(128) drama_codec_window_attention( + const __half* __restrict__ qkv, __half* __restrict__ out, int t0, int heads, int window, float scale) { + constexpr int tile = 64; + __shared__ float q[kHeadDim], p[tile], part[32]; + const int t = t0 + blockIdx.x, h = blockIdx.y, j = threadIdx.x; + const size_t ld = (size_t)3 * heads * kHeadDim; + if (j < kHeadDim) q[j] = h2f(qkv[(size_t)t * ld + h * kHeadDim + j]); + __syncthreads(); + const int first = max(0, t - window + 1); + float maximum = -__int_as_float(0x7f800000), denominator = 0.f, numerator = 0.f; + for (int start = first / tile * tile; start <= t; start += tile) { + const int key = start + j; + const bool valid = j < tile && key >= first && key <= t; + float score = -__int_as_float(0x7f800000); + if (valid) { + const __half* k = qkv + (size_t)key * ld + (size_t)heads * kHeadDim + h * kHeadDim; + float dot = 0.f; +#pragma unroll 16 + for (int d = 0; d < kHeadDim; ++d) dot = fmaf(q[d], h2f(k[d]), dot); + score = (dot * scale) * 1.4426950408889634074f; + } + const float next_maximum = fmaxf(maximum, block_max(score, part)); + const float rescale = exp2f(maximum - next_maximum); + const float probability = valid ? exp2f(score - next_maximum) : 0.f; + if (j < tile) p[j] = rh(probability); + const float mass = block_sum(probability, part); // also publishes p[] + denominator = denominator * rescale + mass; + if (j < kHeadDim) { + numerator *= rescale; + for (int i = 0; i < tile && start + i <= t; ++i) { + if (start + i < first) continue; + const __half v = qkv[(size_t)(start + i) * ld + (size_t)2 * heads * kHeadDim + h * kHeadDim + j]; + numerator = fmaf(p[i], h2f(v), numerator); + } + } + maximum = next_maximum; + __syncthreads(); + } + if (j < kHeadDim) + out[(size_t)t * heads * kHeadDim + h * kHeadDim + j] = f2h(numerator / denominator); +} + +// FeedForward's silu(w1(x)) * w3(x) over a fused (w1 | w3) GEMM output, each step rounded. +extern "C" __global__ void __launch_bounds__(256) drama_codec_silu_mul( + const __half* __restrict__ gu, __half* __restrict__ out, long long rows, int width) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * width) return; + const long long r = i / width, c = i % width; + const float a = h2f(gu[r * 2 * width + c]); + const float b = h2f(gu[r * 2 * width + width + c]); + out[i] = f2h(rh(a / (1.0f + expf(-a))) * b); +} + +// nn.LayerNorm over channels (eps 1e-6) as PyTorch's kernel: FP32 mean and biased variance. +extern "C" __global__ void __launch_bounds__(256) drama_codec_layer_norm( + const __half* __restrict__ x, const __half* __restrict__ w, const __half* __restrict__ b, + __half* __restrict__ y, int width, float eps) { + __shared__ float part[32]; + const __half* xr = x + (size_t)blockIdx.x * width; + __half* yr = y + (size_t)blockIdx.x * width; + float s = 0.f; + for (int c = threadIdx.x; c < width; c += blockDim.x) s += h2f(xr[c]); + const float mean = block_sum(s, part) / (float)width; + float v = 0.f; + for (int c = threadIdx.x; c < width; c += blockDim.x) { + const float d = h2f(xr[c]) - mean; + v = fmaf(d, d, v); + } + const float rstd = rsqrtf(block_sum(v, part) / (float)width + eps); + for (int c = threadIdx.x; c < width; c += blockDim.x) + yr[c] = f2h(fmaf(h2f(w[c]), rstd * (h2f(xr[c]) - mean), h2f(b[c]))); +} + +// ConvNeXtBlock.dwconv: causal depthwise conv, kernel 7, cuDNN then bias add_, on rows t0..t0 + rows - 1. +extern "C" __global__ void __launch_bounds__(256) drama_codec_dwconv7( + const __half* __restrict__ x, const __half* __restrict__ w, const __half* __restrict__ b, + __half* __restrict__ y, long long t0, long long rows, int width) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * width) return; + const long long t = t0 + i / width; + const int c = (int)(i % width); + float acc = 0.f; +#pragma unroll + for (int k = 0; k < 7; ++k) { + const long long r = t - 6 + k; + if (r >= 0) acc = fmaf(h2f(x[r * width + c]), h2f(w[c * 7 + k]), acc); + } + y[t * width + c] = f2h(rh(acc) + h2f(b[c])); +} + +// dac Snake1d as the Triton kernel: y = x + inv * s * s with s = sin(alpha * x), the final multiply-add fused. +extern "C" __global__ void __launch_bounds__(256) drama_codec_snake( + const __half* x, const float* __restrict__ alpha, const float* __restrict__ inv_alpha, __half* y, + long long n, int width) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const int c = (int)(i % width); + const float v = h2f(x[i]); + const float s = sinf(alpha[c] * v); + y[i] = f2h(fmaf(inv_alpha[c] * s, s, v)); +} + +// The last decoder conv (96 -> 1, kernel 7, causal) and tanh on rows t0..t0 + rows - 1, written as FP32 PCM. +extern "C" __global__ void __launch_bounds__(256) drama_codec_conv_out_tanh( + const __half* __restrict__ x, const __half* __restrict__ w, const __half* __restrict__ b, + float* __restrict__ y, long long t0, long long rows, int width) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows) return; + const long long t = t0 + i; + float acc = 0.f; + for (int k = 0; k < 7; ++k) { + const long long r = t - 6 + k; + if (r < 0) continue; + const __half* xr = x + r * width; + const __half* wk = w + k * width; + for (int c = 0; c < width; ++c) acc = fmaf(h2f(xr[c]), h2f(wk[c]), acc); + } + const float v = rh(rh(acc) + h2f(b[0])); + y[t] = rh(tanhf(v)); +} + +// One implicit GEMM for every conv, transposed conv and linear on rows m_begin..m; FP16 epilogue in reference order. +struct GemmParams { + const __half* x; + const __half* w; + const __half* bias; // [period] or null + const __half* scale; // [period] or null + const __half* residual; // [m][ldr] or null (may alias y) + __half* y; + long long m, m_begin; + int n, cin, taps, dilation, ldx, ldy, ldr, period, bias_mode, act; +}; + +namespace { +constexpr int BM = 128, BN = 128, BK = 32, LDS = BK + 8; + +__device__ __forceinline__ float gemm_epilogue(const GemmParams& p, long long m, int n, float acc) { + const int bn = n % p.period; + float v; + if (p.bias_mode == 1) { + v = rh(acc + h2f(p.bias[bn])); + } else { + v = rh(acc); + if (p.bias_mode == 2) v = rh(v + h2f(p.bias[bn])); + } + if (p.act == 1) v = rh(v * 0.5f * (1.0f + erff(v * 0.70710678118654752440f))); + if (p.scale != nullptr) v = rh(v * h2f(p.scale[bn])); + if (p.residual != nullptr) v = rh(h2f(p.residual[m * p.ldr + n]) + v); + return v; +} +} // namespace + +// 128 x 128 tiles from row 0 over [m_begin, m), 8 warps of 64 x 32; cin, ldx, ldy % 8 == 0, x, w 16-byte aligned. +extern "C" __global__ void __launch_bounds__(256) drama_codec_conv_gemm(const GemmParams p) { + using namespace nvcuda; + __shared__ __align__(128) __half as[BM * LDS]; + __shared__ __align__(128) __half bs[BN * LDS]; + __shared__ __align__(128) float cs[8][16 * 16]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const int wm = warp >> 2, wn = warp & 3; + const long long m0 = (p.m_begin / BM + blockIdx.x) * BM; + const int n0 = blockIdx.y * BN; + const int ktot = p.taps * p.cin; + + wmma::fragment acc[4][2]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::fill_fragment(acc[i][j], 0.f); + + uint4 ra[2], rb[2]; + auto fetch = [&](int k0) { +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v = tid + i * 256; + const int r = v >> 2, c = (v & 3) * 8; + const int kk = k0 + c; + uint4 a = make_uint4(0u, 0u, 0u, 0u), b = make_uint4(0u, 0u, 0u, 0u); + const long long m = m0 + r; + if (m >= p.m_begin && m < p.m && kk < ktot) { + const int tap = kk / p.cin, ci = kk - tap * p.cin; + const long long rin = m - (long long)(p.taps - 1 - tap) * p.dilation; + if (rin >= 0) a = *reinterpret_cast(p.x + rin * p.ldx + ci); + } + const int n = n0 + r; + if (n < p.n && kk < ktot) b = *reinterpret_cast(p.w + (size_t)n * ktot + kk); + ra[i] = a; + rb[i] = b; + } + }; + + fetch(0); + for (int k0 = 0; k0 < ktot; k0 += BK) { + __syncthreads(); +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v = tid + i * 256; + const int r = v >> 2, c = (v & 3) * 8; + *reinterpret_cast(&as[r * LDS + c]) = ra[i]; + *reinterpret_cast(&bs[r * LDS + c]) = rb[i]; + } + __syncthreads(); + if (k0 + BK < ktot) fetch(k0 + BK); +#pragma unroll + for (int kk = 0; kk < BK; kk += 16) { + wmma::fragment af[4]; + wmma::fragment bf[2]; +#pragma unroll + for (int i = 0; i < 4; ++i) wmma::load_matrix_sync(af[i], as + (wm * 64 + i * 16) * LDS + kk, LDS); +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::load_matrix_sync(bf[j], bs + (wn * 32 + j * 16) * LDS + kk, LDS); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::mma_sync(acc[i][j], af[i], bf[j], acc[i][j]); + } + } + + float* c = cs[warp]; +#pragma unroll + for (int i = 0; i < 4; ++i) { +#pragma unroll + for (int j = 0; j < 2; ++j) { + wmma::store_matrix_sync(c, acc[i][j], 16, wmma::mem_row_major); + __syncwarp(); + for (int e = lane; e < 256; e += 32) { + const long long m = m0 + wm * 64 + i * 16 + (e >> 4); + const int n = n0 + wn * 32 + j * 16 + (e & 15); + if (m >= p.m_begin && m < p.m && n < p.n) p.y[m * p.ldy + n] = f2h(gemm_epilogue(p, m, n, c[e])); + } + __syncwarp(); + } + } +} diff --git a/zig/kernels/cuda/drama_gdn_chunk.cuh b/zig/kernels/cuda/drama_gdn_chunk.cuh new file mode 100644 index 00000000000..0e077c4c68b --- /dev/null +++ b/zig/kernels/cuda/drama_gdn_chunk.cuh @@ -0,0 +1,525 @@ +// Chunked Gated DeltaNet prefill after SGLang 0.5.21 (Apache-2.0) and flash-linear-attention (MIT); see NOTICES. +#pragma once + +namespace drama_gdn_chunk { + +constexpr int D = 128; // head_k_dim = head_v_dim +constexpr int BT = 64; // chunk.py CHUNK_SIZE +constexpr int BC = 16; // chunk_fwd.py BC +constexpr unsigned FULL = 0xffffffffu; + +__device__ __forceinline__ float log2e() { return __uint_as_float(0x3FB8AA3Bu); } +__device__ __forceinline__ float neg_inf() { return __uint_as_float(0xFF800000u); } + +__device__ __forceinline__ float ex2_approx(float x) { + float r; + asm("ex2.approx.f32 %0, %1;" : "=f"(r) : "f"(x)); + return r; +} + +// tl.exp(x): mul.f32 x, log2(e); ex2.approx.f32 (non-ftz). +__device__ __forceinline__ float tl_exp(float x) { return ex2_approx(__fmul_rn(x, log2e())); } + +// fla/op.py safe_exp(x) = exp(where(x <= 0, x, -inf)): mul, select, ex2 (ex2(-inf) = +0). +__device__ __forceinline__ float safe_exp(float x) { + const float m = __fmul_rn(x, log2e()); + return ex2_approx(x <= 0.f ? m : neg_inf()); +} + +// Half-warp sum of squares in the compiled l2norm_fwd_kernel's order: x1 * x1, fma x0, x2..x7, then lane ^ 8..1. +__device__ __forceinline__ float reference_sumsq(const float (&x)[8]) { + float s = __fmul_rn(x[1], x[1]); + s = __fmaf_rn(x[0], x[0], s); +#pragma unroll + for (int j = 2; j < 8; ++j) s = __fmaf_rn(x[j], x[j], s); +#pragma unroll + for (int m = 8; m; m >>= 1) s = __fadd_rn(s, __shfl_xor_sync(FULL, s, m)); + return s; +} + +__device__ __forceinline__ float sqrt_approx_ftz(float a) { + float r; + asm("sqrt.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(a)); + return r; +} + +__device__ __forceinline__ float div_full(float a, float b) { + float r; + asm("div.full.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +__device__ __forceinline__ unsigned bits(__nv_bfloat16 v) { return __bfloat16_as_ushort(v); } +__device__ __forceinline__ unsigned pack2(unsigned lo, unsigned hi) { return (lo & 0xFFFFu) | (hi << 16); } + +// One warp: C (16 x 8, fp32) += A (16 x 16k) * B (16k x 8), mma.sync m16n8k16 bf16, k ascending; g = lane / 4. +template +__device__ __forceinline__ void mma_bf16_chain(float (&c)[4], FA a, FB b, int ksteps) { + const int lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + for (int s = 0; s < ksteps; ++s) { + const int k0 = s * 16 + 2 * t; + const unsigned a0 = pack2(a(g, k0), a(g, k0 + 1)); + const unsigned a1 = pack2(a(g + 8, k0), a(g + 8, k0 + 1)); + const unsigned a2 = pack2(a(g, k0 + 8), a(g, k0 + 9)); + const unsigned a3 = pack2(a(g + 8, k0 + 8), a(g + 8, k0 + 9)); + const unsigned b0 = pack2(b(k0, g), b(k0 + 1, g)); + const unsigned b1 = pack2(b(k0 + 8, g), b(k0 + 9, g)); + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, " + "{%0, %1, %2, %3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); + } +} + +__device__ __forceinline__ int c_row(int e) { return ((threadIdx.x & 31) >> 2) + ((e >> 1) << 3); } +__device__ __forceinline__ int c_col(int e) { return ((threadIdx.x & 3) << 1) + (e & 1); } + +// One warp: acc (16 x 16) += X * Y, fp32 in shared memory as raw tf32 operands, mma.sync m16n8k8, k-step 0 then 1. +__device__ __forceinline__ void mma_tf32_16(float (&acc)[2][4], const float* X, int ldx, const float* Y, int ldy) { + const int lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; +#pragma unroll + for (int ks = 0; ks < 2; ++ks) { + const unsigned a0 = __float_as_uint(X[g * ldx + ks * 8 + t]); + const unsigned a1 = __float_as_uint(X[(g + 8) * ldx + ks * 8 + t]); + const unsigned a2 = __float_as_uint(X[g * ldx + ks * 8 + t + 4]); + const unsigned a3 = __float_as_uint(X[(g + 8) * ldx + ks * 8 + t + 4]); +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const unsigned b0 = __float_as_uint(Y[(ks * 8 + t) * ldy + nt * 8 + g]); + const unsigned b1 = __float_as_uint(Y[(ks * 8 + t + 4) * ldy + nt * 8 + g]); + asm volatile( + "mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, " + "{%0, %1, %2, %3};\n" + : "+f"(acc[nt][0]), "+f"(acc[nt][1]), "+f"(acc[nt][2]), "+f"(acc[nt][3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); + } + } +} + +__device__ __forceinline__ void zero16(float (&acc)[2][4]) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[nt][e] = 0.f; +} + +// dst (16 x 16, ld) = NEG ? 0 - acc : acc +template +__device__ __forceinline__ void store16(const float (&acc)[2][4], float* dst, int ld) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int e = 0; e < 4; ++e) dst[c_row(e) * ld + nt * 8 + c_col(e)] = NEG ? __fsub_rn(0.f, acc[nt][e]) : acc[nt][e]; +} + +// One row of `cols` bf16 values by the whole block: 16 bytes a thread when both rows allow it, else 2 bytes. +__device__ __forceinline__ void copy_row(const __nv_bfloat16* src, __nv_bfloat16* dst, int cols) { + const bool vec = ((reinterpret_cast(src) | reinterpret_cast(dst)) & 15) == 0 && (cols & 7) == 0; + if (vec) { + const uint4* s = reinterpret_cast(src); + uint4* d = reinterpret_cast(dst); + for (int i = threadIdx.x; i < cols / 8; i += blockDim.x) d[i] = s[i]; + } else { + const unsigned short* s = reinterpret_cast(src); + unsigned short* d = reinterpret_cast(dst); + for (int i = threadIdx.x; i < cols; i += blockDim.x) d[i] = s[i]; + } +} + +} // namespace drama_gdn_chunk + +// Appends gridDim.x qkv and ba rows to the unfinished chunk's dense row caches from row at. +extern "C" __global__ void __launch_bounds__(256) drama_gdn_chunk_append(const __nv_bfloat16* qkv, int ld_qkv, + const __nv_bfloat16* ba, int ld_ba, + __nv_bfloat16* qkv_cache, + __nv_bfloat16* ba_cache, int at, int qkv_cols, + int ba_cols) { + using namespace drama_gdn_chunk; + const size_t r = blockIdx.x, c = at + r; + copy_row(qkv + r * ld_qkv, qkv_cache + c * qkv_cols, qkv_cols); + copy_row(ba + r * ld_ba, ba_cache + c * ba_cols, ba_cols); +} + +// 1. l2norm_fwd of every q and k head row, y = bf16(x / sqrt(sum x^2 + eps)), a half-warp a row. +extern "C" __global__ void __launch_bounds__(256) drama_gdn_chunk_l2norm(const __nv_bfloat16* qkv, int ld_qkv, + __nv_bfloat16* qk, int rows, int nk, + float eps) { + using namespace drama_gdn_chunk; + const int nrow = rows * 2 * nk; + const int r = static_cast(blockIdx.x) * 16 + (threadIdx.x >> 4); + const int col = (threadIdx.x & 15) * 8; + const bool valid = r < nrow; + const int t = valid ? r / (2 * nk) : 0, j = valid ? r % (2 * nk) : 0; + const __nv_bfloat16* x = qkv + static_cast(t) * ld_qkv + j * D + col; + float v[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) v[i] = valid ? bf(x[i]) : 0.f; // masked load, other = 0 + const float s = reference_sumsq(v); + const float n = sqrt_approx_ftz(__fadd_rn(eps, s)); + if (!valid) return; +#pragma unroll + for (int i = 0; i < 8; ++i) qk[static_cast(r) * D + col + i] = tobf(div_full(v[i], n)); +} + +// 2. fused_gdn_gating and chunk_local_cumsum (BT 64): g, beta = bf16(sigmoid(b)) and gc, the chunk's cumsum of g. +extern "C" __global__ void __launch_bounds__(64) drama_gdn_chunk_gate(const __nv_bfloat16* ba, int ld_ba, + const float* a_log, const float* dt_bias, + float* g, float* gc, float* beta, int rows, + int nv) { + using namespace drama_gdn_chunk; + __shared__ float total0; + const int h = blockIdx.y, i = threadIdx.x, lane = i & 31; + const int t = static_cast(blockIdx.x) * BT + i; + const bool valid = t < rows; + float gv = 0.f; // masked load of g, other = 0 + if (valid) { + const float bb = bf(ba[static_cast(t) * ld_ba + h]); + const float aa = bf(ba[static_cast(t) * ld_ba + nv + h]); + const float x = __fadd_rn(aa, dt_bias[h]); + const float sp = x <= 20.f ? logf(__fadd_rn(tl_exp(x), 1.f)) : x; + gv = __fmul_rn(__fsub_rn(0.f, tl_exp(a_log[h])), sp); + const float s = tl_exp(__fsub_rn(0.f, bb)); + const float be = round_bf(div_full(1.f, __fadd_rn(s, 1.f))); + g[static_cast(t) * nv + h] = gv; + beta[static_cast(t) * nv + h] = be; + } + float sc = gv; +#pragma unroll + for (int d = 1; d < 32; d <<= 1) { + const float up = __shfl_up_sync(FULL, sc, d); + if (lane >= d) sc = __fadd_rn(sc, up); + } + if (i == 31) total0 = sc; + __syncthreads(); + if (i >= 32) sc = __fadd_rn(total0, sc); + if (valid) gc[static_cast(t) * nv + h] = sc; +} + +// 3. kkt_solve: A = beta * k k^T * safe_exp(g_r - g_c), diagonal blocks by forward substitution, tf32 merge. +extern "C" __global__ void __launch_bounds__(32) drama_gdn_chunk_kkt(const __nv_bfloat16* qk, const float* gc, + const float* beta, __nv_bfloat16* A, int rows, + int nk, int nv) { + using namespace drama_gdn_chunk; + __shared__ float sA[BT][BT]; // gated, masked, beta-scaled lower blocks + __shared__ float sI[BT][BT]; // (I + A)^-1 blocks + __shared__ float sT[BC][BC]; // merge temporary + __shared__ float sg[BT], sb[BT]; + const int it = blockIdx.x, h = blockIdx.y, lane = threadIdx.x; + const int t0 = it * BT, kh = h / (nv / nk); + for (int i = lane; i < BT; i += 32) { + const int t = t0 + i; + sg[i] = t < rows ? gc[static_cast(t) * nv + h] : 0.f; + sb[i] = t < rows ? beta[static_cast(t) * nv + h] : 0.f; + } + __syncwarp(); + auto kbits = [&](int r, int d) -> unsigned { + const int t = t0 + r; + return t < rows ? bits(qk[(static_cast(t) * 2 * nk + nk + kh) * D + d]) : 0u; + }; + // Steps 1-2 (chunk_fwd.py:126-228) + for (int bi = 0; bi < 4; ++bi) { + for (int bj = 0; bj <= bi; ++bj) { + for (int nt = 0; nt < 2; ++nt) { + float c[4] = {0.f, 0.f, 0.f, 0.f}; + mma_bf16_chain( + c, [&](int r, int k) { return kbits(bi * BC + r, k); }, + [&](int k, int n) { return kbits(bj * BC + nt * 8 + n, k); }, D / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int r = c_row(e), cl = nt * 8 + c_col(e); + const int R = bi * BC + r, C = bj * BC + cl; + float v = __fmul_rn(c[e], safe_exp(__fsub_rn(sg[R], sg[C]))); + if (bi == bj) v = (r > cl && t0 + R < rows && t0 + C < rows) ? v : 0.f; + sA[R][C] = __fmul_rn(v, sb[R]); + } + } + } + } + __syncwarp(); + // Step 3 (chunk_fwd.py:230-266): Ai = -A on the diagonal blocks, forward substitution, Ai += I + for (int d = 0; d < 4; ++d) { + const int o = d * BC; + for (int idx = lane; idx < BC * BC; idx += 32) { + const int r = idx / BC, c = idx % BC; + sI[o + r][o + c] = -sA[o + r][o + c]; + } + __syncwarp(); + const int lim = min(BC, rows - (t0 + o)); + for (int i = 2; i < lim; ++i) { + float a_new = 0.f; + if (lane < BC) { + const int c = lane; + float P[8]; +#pragma unroll + for (int gq = 0; gq < 8; ++gq) { + const float ag = gq < i ? -sA[o + i][o + gq] : 0.f; + const float ag8 = gq + 8 < i ? -sA[o + i][o + gq + 8] : 0.f; + P[gq] = __fmaf_rn(sI[o + gq][o + c], ag, __fmul_rn(sI[o + gq + 8][o + c], ag8)); + } + const float S = __fadd_rn(__fadd_rn(__fadd_rn(P[0], P[4]), __fadd_rn(P[2], P[6])), + __fadd_rn(__fadd_rn(P[1], P[5]), __fadd_rn(P[3], P[7]))); + const float bc = c < i ? -sA[o + i][o + c] : 0.f; + a_new = __fadd_rn(bc, S); + } + __syncwarp(); + if (lane < BC) sI[o + i][o + lane] = a_new; + __syncwarp(); + } + for (int idx = lane; idx < BC * BC; idx += 32) { + const int r = idx / BC, c = idx % BC; + sI[o + r][o + c] = __fadd_rn(sI[o + r][o + c], r == c ? 1.f : 0.f); + } + __syncwarp(); + } + // Step 4 (chunk_fwd.py:269-307): block merge, tf32 MMA, source order + float acc[2][4]; + // Ai10 = -(Ai11 @ A10) @ Ai00 + zero16(acc); mma_tf32_16(acc, &sI[16][16], BT, &sA[16][0], BT); store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sT[0][0], BC, &sI[0][0], BT); store16(acc, &sI[16][0], BT); __syncwarp(); + // Ai21 = -(Ai22 @ A21) @ Ai11 + zero16(acc); mma_tf32_16(acc, &sI[32][32], BT, &sA[32][16], BT); store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sT[0][0], BC, &sI[16][16], BT); store16(acc, &sI[32][16], BT); __syncwarp(); + // Ai32 = -(Ai33 @ A32) @ Ai22 + zero16(acc); mma_tf32_16(acc, &sI[48][48], BT, &sA[48][32], BT); store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sT[0][0], BC, &sI[32][32], BT); store16(acc, &sI[48][32], BT); __syncwarp(); + // Ai20 = -Ai22 @ (A20 @ Ai00 + A21 @ Ai10) + zero16(acc); + mma_tf32_16(acc, &sA[32][0], BT, &sI[0][0], BT); + mma_tf32_16(acc, &sA[32][16], BT, &sI[16][0], BT); + store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sI[32][32], BT, &sT[0][0], BC); store16(acc, &sI[32][0], BT); __syncwarp(); + // Ai31 = -Ai33 @ (A31 @ Ai11 + A32 @ Ai21) + zero16(acc); + mma_tf32_16(acc, &sA[48][16], BT, &sI[16][16], BT); + mma_tf32_16(acc, &sA[48][32], BT, &sI[32][16], BT); + store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sI[48][48], BT, &sT[0][0], BC); store16(acc, &sI[48][16], BT); __syncwarp(); + // Ai30 = -Ai33 @ (A30 @ Ai00 + A31 @ Ai10 + A32 @ Ai20) + zero16(acc); + mma_tf32_16(acc, &sA[48][0], BT, &sI[0][0], BT); + mma_tf32_16(acc, &sA[48][16], BT, &sI[16][0], BT); + mma_tf32_16(acc, &sA[48][32], BT, &sI[32][0], BT); + store16(acc, &sT[0][0], BC); __syncwarp(); + zero16(acc); mma_tf32_16(acc, &sI[48][48], BT, &sT[0][0], BC); store16(acc, &sI[48][0], BT); __syncwarp(); + // Step 5 (chunk_fwd.py:309-338): rows < rows only; upper blocks are the source's torch.zeros + for (int idx = lane; idx < BT * BT; idx += 32) { + const int R = idx / BT, C = idx % BT, t = t0 + R; + if (t >= rows) continue; + const float v = (C / BC <= R / BC) ? sI[R][C] : 0.f; + A[(static_cast(t) * nv + h) * BT + C] = tobf(v); + } +} + +// 4. recompute_w_u_fwd: u = A @ bf16(v * beta); w = A @ bf16(k * beta * exp(gc)). +extern "C" __global__ void __launch_bounds__(128) drama_gdn_chunk_wu(const __nv_bfloat16* qkv, int ld_qkv, + const __nv_bfloat16* qk, const float* gc, + const float* beta, const __nv_bfloat16* A, + __nv_bfloat16* w, __nv_bfloat16* u, int rows, + int nk, int nv) { + using namespace drama_gdn_chunk; + __shared__ unsigned short sAb[BT][BT]; + __shared__ unsigned short sV[BT][D]; + __shared__ unsigned short sK[BT][D]; + const int it = blockIdx.x, h = blockIdx.y, tid = threadIdx.x, warp = tid >> 5; + const int t0 = it * BT, kh = h / (nv / nk); + for (int idx = tid; idx < BT * BT; idx += blockDim.x) { + const int r = idx / BT, c = idx % BT, t = t0 + r; + sAb[r][c] = t < rows ? static_cast(bits(A[(static_cast(t) * nv + h) * BT + c])) : 0; + } + for (int idx = tid; idx < BT * D; idx += blockDim.x) { + const int r = idx / D, d = idx % D, t = t0 + r; + unsigned short vb = 0, kb = 0; + if (t < rows) { + const float be = beta[static_cast(t) * nv + h]; + const float eg = tl_exp(gc[static_cast(t) * nv + h]); + const float v = bf(qkv[static_cast(t) * ld_qkv + 2 * nk * D + h * D + d]); + const float k = bf(qk[(static_cast(t) * 2 * nk + nk + kh) * D + d]); + vb = static_cast(bits(tobf(__fmul_rn(v, be)))); + kb = static_cast(bits(tobf(__fmul_rn(__fmul_rn(k, be), eg)))); + } + sV[r][d] = vb; + sK[r][d] = kb; + } + __syncthreads(); + for (int tile = warp; tile < 2 * (BT / 16) * (D / 8); tile += 4) { + const bool is_w = tile >= (BT / 16) * (D / 8); + const int local = is_w ? tile - (BT / 16) * (D / 8) : tile; + const int mt = local / (D / 8), nt = local % (D / 8); + float c[4] = {0.f, 0.f, 0.f, 0.f}; + if (is_w) { + mma_bf16_chain( + c, [&](int r, int k) { return static_cast(sAb[mt * 16 + r][k]); }, + [&](int k, int n) { return static_cast(sK[k][nt * 8 + n]); }, BT / 16); + } else { + mma_bf16_chain( + c, [&](int r, int k) { return static_cast(sAb[mt * 16 + r][k]); }, + [&](int k, int n) { return static_cast(sV[k][nt * 8 + n]); }, BT / 16); + } + __nv_bfloat16* out = is_w ? w : u; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int t = t0 + mt * 16 + c_row(e); + if (t < rows) out[(static_cast(t) * nv + h) * D + nt * 8 + c_col(e)] = tobf(c[e]); + } + } +} + +// 5. chunk h (BV 32): per chunk h = bf16(S), vn = u - w @ h^T, S = fma(S, exp(g_last), k^T @ decayed vn). +extern "C" __global__ void __launch_bounds__(128) drama_gdn_chunk_h(const __nv_bfloat16* qk, const __nv_bfloat16* w, + const __nv_bfloat16* u, const float* gc, + const float* state_in, float* state_out, + __nv_bfloat16* hout, __nv_bfloat16* vn, int rows, + int nk, int nv) { + using namespace drama_gdn_chunk; + constexpr int BV = 32; + __shared__ float sS[BV][D]; + __shared__ unsigned short sH[BV][D]; + __shared__ unsigned short sVb[BT][BV]; + __shared__ float sG[BT]; + const int v0 = blockIdx.x * BV, h = blockIdx.y, tid = threadIdx.x, warp = tid >> 5; + const int kh = h / (nv / nk), NT = (rows + BT - 1) / BT; + const float* s_in = state_in + static_cast(h) * D * D; + float* s_out = state_out + static_cast(h) * D * D; + for (int idx = tid; idx < BV * D; idx += blockDim.x) { + const int vr = idx / D, k = idx % D; + sS[vr][k] = __fadd_rn(0.f, s_in[static_cast(v0 + vr) * D + k]); // b_h = zeros; b_h += load + } + for (int it = 0; it < NT; ++it) { + const int t0 = it * BT; + __syncthreads(); + for (int idx = tid; idx < BV * D; idx += blockDim.x) { + const int vr = idx / D, k = idx % D; + const __nv_bfloat16 hb = tobf(sS[vr][k]); + sH[vr][k] = static_cast(bits(hb)); + hout[((static_cast(it) * nv + h) * D + v0 + vr) * D + k] = hb; + } + for (int i = tid; i < BT; i += blockDim.x) { + const int t = t0 + i; + sG[i] = t < rows ? gc[static_cast(t) * nv + h] : 0.f; + } + __syncthreads(); + const float glast = gc[static_cast(min(t0 + BT, rows) - 1) * nv + h]; + const float eg = tl_exp(glast); + // b_v [64 t][32 v] = w @ bf16(S)^T, k ascending 0..127 (chunk_delta_h.py:213-231, fused accumulators) + for (int tile = warp; tile < (BT / 16) * (BV / 8); tile += 4) { + const int mt = tile / (BV / 8), nt = tile % (BV / 8); + float c[4] = {0.f, 0.f, 0.f, 0.f}; + mma_bf16_chain( + c, + [&](int r, int k) { + const int t = t0 + mt * 16 + r; + return t < rows ? bits(w[(static_cast(t) * nv + h) * D + k]) : 0u; + }, + [&](int k, int n) { return static_cast(sH[nt * 8 + n][k]); }, D / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int rr = mt * 16 + c_row(e), vv = nt * 8 + c_col(e), t = t0 + rr; + const bool valid = t < rows; + const float uu = valid ? bf(u[(static_cast(t) * nv + h) * D + v0 + vv]) : 0.f; + float bv = __fsub_rn(uu, c[e]); + if (valid) vn[(static_cast(t) * nv + h) * D + v0 + vv] = tobf(bv); + bv = __fmul_rn(bv, safe_exp(__fsub_rn(glast, sG[rr]))); + sVb[rr][vv] = static_cast(bits(tobf(bv))); + } + } + __syncthreads(); + // S[v][k] = fma(S, exp(g_last), sum_t k[t][k] * bf16(b_v)[t][v]), t ascending (chunk_delta_h.py:250-310) + for (int tile = warp; tile < (D / 16) * (BV / 8); tile += 4) { + const int mt = tile / (BV / 8), nt = tile % (BV / 8); + float c[4] = {0.f, 0.f, 0.f, 0.f}; + mma_bf16_chain( + c, + [&](int r, int tt) { + const int t = t0 + tt; + return t < rows ? bits(qk[(static_cast(t) * 2 * nk + nk + kh) * D + mt * 16 + r]) : 0u; + }, + [&](int tt, int n) { return static_cast(sVb[tt][nt * 8 + n]); }, BT / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int kd = mt * 16 + c_row(e), vv = nt * 8 + c_col(e); + sS[vv][kd] = __fmaf_rn(sS[vv][kd], eg, c[e]); + } + } + } + __syncthreads(); + for (int idx = tid; idx < BV * D; idx += blockDim.x) { + const int vr = idx / D, k = idx % D; + s_out[static_cast(v0 + vr) * D + k] = sS[vr][k]; + } +} + +// 6. chunk_fwd_kernel_o (BV 64): o over all 64 chunk rows for every segment length, written from emit_from. +extern "C" __global__ void __launch_bounds__(128) drama_gdn_chunk_o(const __nv_bfloat16* qk, const __nv_bfloat16* vn, + const __nv_bfloat16* hin, const float* gc, + __nv_bfloat16* y, int rows, int emit_from, int nk, + int nv, float scale) { + using namespace drama_gdn_chunk; + constexpr int BV = 64; + __shared__ unsigned short sAo[BT][BT]; + __shared__ float sG[BT]; + const int vb0 = blockIdx.x * BV, it = blockIdx.y, h = blockIdx.z, tid = threadIdx.x, warp = tid >> 5; + const int t0 = it * BT, kh = h / (nv / nk); + const int w0 = t0 + warp * 16; + const bool active = w0 < rows && w0 + 16 > emit_from; + for (int i = tid; i < BT; i += blockDim.x) { + const int t = t0 + i; + sG[i] = t < rows ? gc[static_cast(t) * nv + h] : 0.f; + } + __syncthreads(); + auto qbits = [&](int r, int d) -> unsigned { + const int t = w0 + r; + return t < rows ? bits(qk[(static_cast(t) * 2 * nk + kh) * D + d]) : 0u; + }; + float bo[BV / 8][4]; + if (active) { + // b_A tiles of this warp's rows; masked, gated, bf16 into shared memory + for (int nt = 0; nt < BT / 8; ++nt) { + float c[4] = {0.f, 0.f, 0.f, 0.f}; + mma_bf16_chain( + c, qbits, + [&](int d, int n) { + const int t = t0 + nt * 8 + n; + return t < rows ? bits(qk[(static_cast(t) * 2 * nk + nk + kh) * D + d]) : 0u; + }, + D / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int i = warp * 16 + c_row(e), j = nt * 8 + c_col(e); + float v = __fmul_rn(c[e], safe_exp(__fsub_rn(sG[i], sG[j]))); + v = i >= j ? v : 0.f; + sAo[i][j] = static_cast(bits(tobf(v))); + } + } + // b_o tiles (registers): q @ h^T, k ascending, then * exp(g) + const __nv_bfloat16* h0 = hin + (static_cast(it) * nv + h) * D * D; + for (int nt = 0; nt < BV / 8; ++nt) { +#pragma unroll + for (int e = 0; e < 4; ++e) bo[nt][e] = 0.f; + mma_bf16_chain( + bo[nt], qbits, + [&](int d, int n) { return bits(h0[static_cast(vb0 + nt * 8 + n) * D + d]); }, D / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) bo[nt][e] = __fmul_rn(bo[nt][e], tl_exp(sG[warp * 16 + c_row(e)])); + } + } + __syncthreads(); + if (!active) return; + for (int nt = 0; nt < BV / 8; ++nt) { + float c[4] = {0.f, 0.f, 0.f, 0.f}; + mma_bf16_chain( + c, [&](int r, int j) { return static_cast(sAo[warp * 16 + r][j]); }, + [&](int j, int n) { + const int t = t0 + j; + return t < rows ? bits(vn[(static_cast(t) * nv + h) * D + vb0 + nt * 8 + n]) : 0u; + }, + BT / 16); +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int t = w0 + c_row(e); + const float o = __fmaf_rn(bo[nt][e], scale, __fmul_rn(scale, c[e])); + if (t < rows && t >= emit_from) + y[(static_cast(t - emit_from) * nv + h) * D + vb0 + nt * 8 + c_col(e)] = tobf(o); + } + } +} diff --git a/zig/kernels/cuda/drama_tower.cu b/zig/kernels/cuda/drama_tower.cu new file mode 100644 index 00000000000..912a650cfcd --- /dev/null +++ b/zig/kernels/cuda/drama_tower.cu @@ -0,0 +1,510 @@ +// Drama 3 tower kernels after sglang-omni ab095ef9 (decoder_layers.py, audio_decoder.py, sampling.py). +#include +#include +#include +#include + +using bf16 = __nv_bfloat16; +__device__ inline float f(bf16 x) { return __bfloat162float(x); } +__device__ inline bf16 b(float x) { return __float2bfloat16_rn(x); } +__device__ inline bool semantic(int x, int begin, int end) { return x >= begin && x <= end; } +__device__ inline int code(int x) { return max(0, min(4095, x)); } + +__device__ float sum_block(float x, float* scratch) { + const int t = threadIdx.x; + scratch[t] = x; + __syncthreads(); + for (int n = blockDim.x / 2; n; n >>= 1) { + if (t < n) scratch[t] += scratch[t + n]; + __syncthreads(); + } + return scratch[0]; +} + +// Frame rows are [main token, code0..code9]; sums keep the reference's bf16 embedding-bag output and bf16 adds. +extern "C" __global__ void drama_frame_embeddings( + const int* frames, const bf16* table, bf16* backbone, bf16* shared, + int hidden, int begin, int end) { + const int row = blockIdx.x; + const int* frame = frames + row * 11; + for (int j = threadIdx.x; j < hidden; j += blockDim.x) { + float extra = 0.0f, rest = 0.0f; + if (semantic(frame[0], begin, end)) { + extra = f(table[(4096 + code(frame[2])) * hidden + j]); + for (int c = 2; c < 10; ++c) + rest += f(table[(c * 4096 + code(frame[1 + c])) * hidden + j]); + } + backbone[row * hidden + j] = b(extra); + shared[row * hidden + j] = b(rest); + } +} + +extern "C" __global__ void drama_mix( + const bf16* hidden_in, const bf16* embedding, const int* labels, + const bf16* shared_input, const bf16* enorm, const bf16* hnorm, + bf16* joined, int width, int code_index, int begin, int end, float eps) { + __shared__ float sums[2]; + const int row = blockIdx.x, t = threadIdx.x; + const int* label = labels + row * 11; + const bool speech = semantic(label[0], begin, end); + const int id = code(label[1 + code_index]); + // CuTe's width-2048 RMS path: 8 contiguous elements a lane, FP32 FMA, then an ascending XOR-warp reduction. + if (t < 32) { + float e2 = 0, h2 = 0; + for (int block = 0; block < width; block += 256) { + for (int v = 0; v < 8; ++v) { + const int j = block + 8 * t + v; + float e = speech ? f(embedding[id * width + j]) : 0; + if (shared_input) e = f(b(e + f(shared_input[row * width + j]))); + const float h = f(hidden_in[row * width + j]); + e2 = fmaf(e, e, e2); + h2 = fmaf(h, h, h2); + } + } + for (int offset = 1; offset < 32; offset <<= 1) { + e2 += __shfl_xor_sync(0xffffffffu, e2, offset); + h2 += __shfl_xor_sync(0xffffffffu, h2, offset); + } + if (t == 0) { + sums[0] = e2; + sums[1] = h2; + } + } + __syncthreads(); + const float er = rsqrtf(sums[0] / width + eps); + const float hr = rsqrtf(sums[1] / width + eps); + for (int j = t; j < width; j += blockDim.x) { + float e = speech ? f(embedding[id * width + j]) : 0; + if (shared_input) e = f(b(e + f(shared_input[row * width + j]))); + joined[row * 2 * width + j] = b(e * er * (1.0f + f(enorm[j]))); + joined[row * 2 * width + width + j] = + b(f(hidden_in[row * width + j]) * hr * (1.0f + f(hnorm[j]))); + } +} + +// Gemma RMSNorm with optional fused residual (stored bf16, normalized from the fp32 sum) in FlashInfer's CuTe order. +extern "C" __global__ void drama_norm( + const bf16* x, const bf16* residual, const bf16* weight, + bf16* normalized, bf16* residual_out, int width, float eps) { + __shared__ float square_sum; + const int base = blockIdx.x * width, t = threadIdx.x; + if (t < 32) { + float square = 0; + for (int block = 0; block < width; block += 256) { + for (int v = 0; v < 8; ++v) { + const int j = block + 8 * t + v; + const float value = residual ? f(x[base + j]) + f(residual[base + j]) : f(x[base + j]); + square = fmaf(value, value, square); + } + } + for (int offset = 1; offset < 32; offset <<= 1) + square += __shfl_xor_sync(0xffffffffu, square, offset); + if (t == 0) square_sum = square; + } + __syncthreads(); + const float r = rsqrtf(square_sum / width + eps); + for (int j = t; j < width; j += blockDim.x) { + const float v = residual ? f(x[base + j]) + f(residual[base + j]) : f(x[base + j]); + if (residual_out) residual_out[base + j] = b(v); + normalized[base + j] = b(v * r * (1.0f + f(weight[j]))); + } +} + +// Q/K Gemma RMSNorm then interleaved RoPE in the reference's arithmetic: CuTe sum order and cos/sin angle rounding. +extern "C" __global__ void drama_rope_cache( + const bf16* qkv, const bf16* qnorm, const bf16* knorm, + bf16* queries, bf16* keys, bf16* values, + int start, int qheads, int kvheads, int dim, int rotary_dim, + float rope_base, float eps) { + __shared__ float square_sum; + const int row = blockIdx.x / (qheads + kvheads); + const int h = blockIdx.x % (qheads + kvheads), t = threadIdx.x; + const bool is_q = h < qheads; + const int kh = h - qheads; + const int qw = qheads * dim, kw = kvheads * dim; + const bf16* input = qkv + row * (2 * qw + 2 * kw) + (is_q ? h * dim : 2 * qw + kh * dim); + const bf16* weight = is_q ? qnorm : knorm; + if (t < 32) { + float square = 0; + for (int block = 0; block < dim; block += 256) { + for (int v = 0; v < 8; ++v) { + const float value = f(input[block + 8 * t + v]); + square = fmaf(value, value, square); + } + } + for (int offset = 1; offset < 32; offset <<= 1) + square += __shfl_xor_sync(0xffffffffu, square, offset); + if (t == 0) square_sum = square; + } + __syncthreads(); + const float r = rsqrtf(square_sum / dim + eps); + if (t < dim) { + float x = f(b(f(input[t]) * r * (1.0f + f(weight[t])))); + if (t < rotary_dim) { + const int other = t ^ 1; + const float y = f(b(f(input[other]) * r * (1.0f + f(weight[other])))); + const float inverse = __frcp_rn(powf(rope_base, float(t & ~1) / rotary_dim)); + const float angle = __fmul_rn(float(start + row), inverse); + const float co = cosf(angle), si = sinf(angle); + x = (t & 1) ? fmaf(x, co, __fmul_rn(y, si)) : fmaf(x, co, -__fmul_rn(y, si)); + } + if (is_q) queries[row * qw + h * dim + t] = b(x); + else { + keys[(start + row) * kw + kh * dim + t] = b(x); + values[(start + row) * kw + kh * dim + t] = qkv[row * (2 * qw + 2 * kw) + 2 * qw + kw + kh * dim + t]; + } + } +} + +// Eight keys per tile, FP32 online softmax. One CTA per query head and row. +extern "C" __global__ void drama_attention( + const bf16* query, const bf16* keys, const bf16* values, const bf16* qkv, + bf16* out, int start, int qheads, int kvheads, int dim) { + __shared__ float scores[8], probabilities[8], scale, running_max, denominator; + const int t = threadIdx.x, warp = t / 32, lane = t % 32; + const int row = blockIdx.x / qheads, head = blockIdx.x % qheads; + const int kh = head / (qheads / kvheads), qw = qheads * dim, kw = kvheads * dim; + const int length = start + row + 1; + if (t == 0) { running_max = -INFINITY; denominator = 0; } + __syncthreads(); + float accum = 0; + for (int first = 0; first < length; first += 8) { + const int at = first + warp; + float dot = 0; + if (at < length) + for (int j = lane; j < dim; j += 32) + dot += f(query[row * qw + head * dim + j]) * f(keys[at * kw + kh * dim + j]); + for (int d = 16; d; d >>= 1) dot += __shfl_down_sync(0xffffffff, dot, d); + if (lane == 0) scores[warp] = at < length ? dot * rsqrtf(float(dim)) : -INFINITY; + __syncthreads(); + if (t == 0) { + float next_max = running_max; + for (int i = 0; i < 8; ++i) next_max = fmaxf(next_max, scores[i]); + scale = expf(running_max - next_max); + float mass = 0; + for (int i = 0; i < 8; ++i) { + probabilities[i] = expf(scores[i] - next_max); + mass += probabilities[i]; + } + denominator = denominator * scale + mass; + running_max = next_max; + } + __syncthreads(); + if (t < dim) { + accum *= scale; + for (int i = 0; i < 8 && first + i < length; ++i) + accum += probabilities[i] * f(values[(first + i) * kw + kh * dim + t]); + } + __syncthreads(); + } + if (t < dim) { + const bf16 attended = b(accum / denominator); + const float gate = f(qkv[row * (2 * qw + 2 * kw) + qw + head * dim + t]); + const bf16 gated = b(1.0f / (1.0f + expf(-gate))); + out[row * qw + head * dim + t] = b(f(attended) * f(gated)); + } +} + +// Clusters are sm_90+: older images leave drama_attention_decode out, and the tower runs drama_attention instead. +#if __CUDA_ARCH__ >= 900 +// drama_attention for the one decode row, its keys scored across a cluster of attention_split CTAs, same arithmetic. +constexpr int attention_split = 4, attention_keys = 8192, attention_ahead = 6; + +__device__ inline void copy_async(void* shared, const void* global) { + asm volatile("cp.async.ca.shared.global [%0], [%1], 4;" :: "r"(unsigned(__cvta_generic_to_shared(shared))), "l"(global) : "memory"); +} + +extern "C" __global__ void __cluster_dims__(attention_split, 1, 1) __launch_bounds__(256) drama_attention_decode( + const bf16* query, const bf16* keys, const bf16* values, const bf16* qkv, + bf16* out, int start, int qheads, int kvheads, int dim) { + __shared__ float scores[attention_keys], maxima[attention_keys / 8], scales[attention_keys / 8], denominator; + // The value lanes' own BF16 pairs, attention_ahead tiles of copies in flight ahead of their sums. + __shared__ __nv_bfloat162 ring[attention_ahead][8][32]; + const cooperative_groups::cluster_group cluster = cooperative_groups::this_cluster(); + const int t = threadIdx.x, warp = t / 32, lane = t % 32, warps = blockDim.x / 32; + const int part = cluster.block_rank(), row = blockIdx.x / attention_split / qheads, head = blockIdx.x / attention_split % qheads; + const int kh = head / (qheads / kvheads), qw = qheads * dim, kw = kvheads * dim; + const int length = start + row + 1, tiles = (length + 7) / 8; + const int share = (tiles + attention_split - 1) / attention_split * 8, last = min(8 * tiles, (part + 1) * share); + const int lanes = dim / attention_split / 2, j = part * 2 * lanes + 2 * t; + const auto fetch = [&](int tile) { + for (int i = 0; i < 8; ++i) + if (8 * tile + i < length) copy_async(&ring[tile % attention_ahead][i][t], values + (8 * tile + i) * kw + kh * dim + j); + asm volatile("cp.async.commit_group;" ::: "memory"); + }; + // The first values do not wait for the scores. + if (t < lanes) + for (int tile = 0; tile < attention_ahead; ++tile) fetch(tile); + float q[8]; + for (int i = 0; i < 8; ++i) q[i] = f(query[row * qw + head * dim + lane + 32 * i]); + // A warp scores a tile, its eight keys' loads in flight; keys past the length read the last one and score -inf. + for (int first = part * share + 8 * warp; first < last; first += 8 * warps) { + bf16 k[8][8]; + for (int u = 0; u < 8; ++u) + for (int i = 0; i < 8; ++i) k[u][i] = keys[min(first + u, length - 1) * kw + kh * dim + lane + 32 * i]; + float dot[8] = {}; + for (int i = 0; i < 8; ++i) + for (int u = 0; u < 8; ++u) dot[u] += q[i] * f(k[u][i]); + for (int d = 16; d; d >>= 1) + for (int u = 0; u < 8; ++u) dot[u] += __shfl_down_sync(0xffffffff, dot[u], d); + if (lane == 0) + for (int u = 0; u < 8; ++u) scores[first + u] = first + u < length ? dot[u] * rsqrtf(float(dim)) : -INFINITY; + } + cluster.sync(); + for (int at = t; at < 8 * tiles; at += blockDim.x) + if (at / share != part) scores[at] = cluster.map_shared_rank(scores, at / share)[at]; + // Peers read this CTA's scores until all have arrived: the probabilities overwrite them only after the wait. + auto gathered = cluster.barrier_arrive(); + __syncthreads(); + for (int tile = t; tile < tiles; tile += blockDim.x) { + float next_max = -INFINITY; + for (int i = 0; i < 8; ++i) next_max = fmaxf(next_max, scores[8 * tile + i]); + maxima[tile] = next_max; + } + __syncthreads(); + if (warp == 0) { + float before = -INFINITY; + for (int first = 0; first < tiles; first += 32) { + float next_max = first + lane < tiles ? maxima[first + lane] : -INFINITY; + for (int d = 1; d < 32; d <<= 1) { + const float other = __shfl_up_sync(0xffffffff, next_max, d); + if (lane >= d) next_max = fmaxf(next_max, other); + } + next_max = fmaxf(before, next_max); + if (first + lane < tiles) maxima[first + lane] = next_max; + before = __shfl_sync(0xffffffff, next_max, 31); + } + } + __syncthreads(); + cluster.barrier_wait(std::move(gathered)); + for (int tile = t; tile < tiles; tile += blockDim.x) { + const float running_max = tile ? maxima[tile - 1] : -INFINITY, next_max = maxima[tile]; + scales[tile] = expf(running_max - next_max); + for (int i = 0; i < 8; ++i) scores[8 * tile + i] = expf(scores[8 * tile + i] - next_max); + } + __syncthreads(); + float accum[2] = {0, 0}; + if (t < lanes) { + // A tile's operands reach registers while the previous tile's sums run. + float rescale, p[8]; + __nv_bfloat162 v[8]; + const auto take = [&](int tile) { + rescale = scales[tile]; + for (int i = 0; i < 8; ++i) { p[i] = scores[8 * tile + i]; v[i] = ring[tile % attention_ahead][i][t]; } + }; + asm volatile("cp.async.wait_group %0;" :: "n"(attention_ahead - 1) : "memory"); + take(0); + for (int tile = 0; tile < tiles; ++tile) { + const float now_rescale = rescale; + float now_p[8]; + __nv_bfloat162 now_v[8]; + for (int i = 0; i < 8; ++i) { now_p[i] = p[i]; now_v[i] = v[i]; } + asm volatile("cp.async.wait_group %0;" :: "n"(attention_ahead - 2) : "memory"); + if (tile + 1 < tiles) take(tile + 1); + accum[0] *= now_rescale; + accum[1] *= now_rescale; + for (int i = 0; i < 8; ++i) + if (8 * tile + i < length) { + accum[0] += now_p[i] * f(now_v[i].x); + accum[1] += now_p[i] * f(now_v[i].y); + } + fetch(tile + attention_ahead); // into this tile's slots, summed from registers + } + } else if (t == blockDim.x - 1) { + float sum = 0; + for (int tile = 0; tile < tiles; ++tile) { + float mass = 0; + for (int i = 0; i < 8; ++i) mass += scores[8 * tile + i]; + sum = sum * scales[tile] + mass; + } + denominator = sum; + } + __syncthreads(); + if (t < lanes) + for (int e = 0; e < 2; ++e) { + const bf16 attended = b(accum[e] / denominator); + const float gate = f(qkv[row * (2 * qw + 2 * kw) + qw + head * dim + j + e]); + const bf16 gated = b(1.0f / (1.0f + expf(-gate))); + out[row * qw + head * dim + j + e] = b(f(attended) * f(gated)); + } +} +#endif + +extern "C" __global__ void drama_silu_mul(const bf16* gate_up, bf16* out, int width, int rows) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * width) return; + const int row = i / width, col = i % width; + const float gate = f(gate_up[row * 2 * width + col]); + out[i] = b((gate / (1.0f + expf(-gate))) * f(gate_up[row * 2 * width + width + col])); +} + +__device__ uint64_t random_word(uint64_t x) { + x += 0x9e3779b97f4a7c15ull; + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull; + x = (x ^ (x >> 27)) * 0x94d049bb133111ebull; + return x ^ (x >> 31); +} + +// The sampler's order (score descending; equal scores, ±0 alike, by ascending id) as a key ascending in it. +__device__ inline unsigned order_key(float x) { + const unsigned bits = __float_as_uint(x), magnitude = bits & 0x7fffffffu; + return bits >> 31 ? 0x80000000u + magnitude : 0x80000000u - magnitude; +} + +// Top-p over the whole vocabulary before top-k, ranked by a stable LSD radix sort; 64 KiB dynamic shared memory. +constexpr int sample_rounds = 6; + +extern "C" __global__ void __launch_bounds__(1024) drama_sample( + const void* logits, int is_bf16, int vocab, float temperature, int top_k, + float top_p, uint64_t seed, uint64_t step, int output_index, + int begin, int eos, int* history, int* frame, int* error_flag) { + extern __shared__ unsigned char storage[]; + unsigned short* counts = reinterpret_cast(storage); // [digit][warp] + float* scores = reinterpret_cast(counts + 256 * 32); + unsigned short* ids = reinterpret_cast(scores + vocab); + unsigned short* next = ids + vocab; + // The counts are no longer needed after the sort; reuse them for reductions. + float* partial = reinterpret_cast(counts); + __shared__ int invalid, selected[2]; + __shared__ unsigned key_and, key_or, warp_offsets[32]; + __shared__ float total; + const int t = threadIdx.x, warp = t / 32, lane = t % 32; + if (t == 0) { invalid = 0; key_and = ~0u; key_or = 0; } + __syncthreads(); + unsigned all = ~0u, any = 0; + for (int i = t; i < vocab; i += blockDim.x) { + const float x = is_bf16 ? f(static_cast(logits)[i]) : static_cast(logits)[i]; + if (!isfinite(x)) atomicExch(&invalid, 1); + scores[i] = x; + ids[i] = i; + all &= order_key(x); + any |= order_key(x); + } + all = __reduce_and_sync(0xffffffff, all); + any = __reduce_or_sync(0xffffffff, any); + if (lane == 0) { atomicAnd(&key_and, all); atomicOr(&key_or, any); } + __syncthreads(); + if (invalid) { + if (t == 0) { + *error_flag = 1; + if (output_index == 0) { frame[0] = eos; frame[1] = 0; } + else frame[output_index] = 0; + } + return; + } + // Warp w ranks its run 32 at a time; equal digits keep their order (BF16 keys skip the two zero digits). + const int run = (vocab + 31) / 32, from = warp * run, end = min(vocab, from + run); + const unsigned lower = (1u << lane) - 1; + for (int shift = 0; shift < 32; shift += 8) { + if (!((key_and ^ key_or) >> shift & 255)) continue; + reinterpret_cast(counts)[t] = make_uint4(0, 0, 0, 0); + __syncthreads(); + // Each element's place among its warp's equal digits: the earlier rounds' count, then the lower lanes'. + int digit[sample_rounds], place[sample_rounds]; + for (int r = 0; r < sample_rounds && from + 32 * r < end; ++r) { + const int i = from + 32 * r + lane; + digit[r] = i < end ? order_key(scores[ids[i]]) >> shift & 255 : 0; + unsigned peers = __ballot_sync(0xffffffff, i < end); + for (int bit = 0; bit < 8; ++bit) { + const unsigned set = __ballot_sync(0xffffffff, digit[r] >> bit & 1); + peers &= digit[r] >> bit & 1 ? set : ~set; + } + const int leader = __ffs(peers) - 1; + unsigned counted = 0; + if (lane == leader) { + counted = counts[digit[r] * 32 + warp]; + counts[digit[r] * 32 + warp] = counted + __popc(peers); + } + place[r] = __shfl_sync(0xffffffff, counted, leader) + __popc(peers & lower); + __syncwarp(); + } + __syncthreads(); + // Exclusive scan of the counts in [digit][warp] order: eight per thread, then across threads. + const uint4 packed = reinterpret_cast(counts)[t]; + unsigned c[8] = {packed.x & 0xffff, packed.x >> 16, packed.y & 0xffff, packed.y >> 16, + packed.z & 0xffff, packed.z >> 16, packed.w & 0xffff, packed.w >> 16}; + unsigned sum = 0; + for (int i = 0; i < 8; ++i) { const unsigned n = c[i]; c[i] = sum; sum += n; } + unsigned before = sum; + for (int d = 1; d < 32; d <<= 1) { + const unsigned other = __shfl_up_sync(0xffffffff, before, d); + if (lane >= d) before += other; + } + if (lane == 31) warp_offsets[warp] = before; + __syncthreads(); + if (warp == 0) { + const unsigned own = warp_offsets[lane]; + unsigned prefix = own; + for (int d = 1; d < 32; d <<= 1) { + const unsigned other = __shfl_up_sync(0xffffffff, prefix, d); + if (lane >= d) prefix += other; + } + warp_offsets[lane] = prefix - own; + } + __syncthreads(); + before += warp_offsets[warp] - sum; + reinterpret_cast(counts)[t] = make_uint4( + (c[0] + before) | (c[1] + before) << 16, (c[2] + before) | (c[3] + before) << 16, + (c[4] + before) | (c[5] + before) << 16, (c[6] + before) | (c[7] + before) << 16); + __syncthreads(); + for (int r = 0; r < sample_rounds && from + 32 * r < end; ++r) { + const int i = from + 32 * r + lane; + if (i < end) next[counts[digit[r] * 32 + warp] + place[r]] = ids[i]; + } + __syncthreads(); + unsigned short* const sorted = next; next = ids; ids = sorted; + } + const float top = scores[ids[0]]; + const bool main = output_index == 0; + for (int draw = 0; draw < (main ? 2 : 1); ++draw) { + const float inv_t = 1.0f / fmaxf(draw == 1 ? 1.0f : temperature, 1e-5f); + const float p_limit = draw == 1 ? 0.95f : top_p; + const int k = min(vocab, draw == 1 ? 30 : top_k); + float mass = 0; + for (int i = t; i < vocab; i += blockDim.x) mass += expf((scores[ids[i]] - top) * inv_t); + const float summed = sum_block(mass, partial); + if (t == 0) total = summed; + __syncthreads(); + // Warp 0 takes 32 ranks at a time; lane 0 runs the in-order cumulative sum, cutoff and pick. + if (warp == 0) { + float* const weights = partial; + float* const candidates = partial + 32; + float cumulative = 0, best = -INFINITY; + int pick = ids[0]; + const uint64_t stream = main ? uint64_t(draw) : uint64_t(output_index); + bool cut = false; + for (int first = 0; first < k && !cut; first += 32) { + const int rank = first + lane; + if (rank < k) { + const float log_weight = (scores[ids[rank]] - top) * inv_t; + weights[lane] = expf(log_weight) / total; + const uint64_t word = random_word(seed ^ random_word((step << 20) | (stream << 14) | uint64_t(rank))); + const float u = (float(word >> 41) + 0.5f) * (1.0f / 8388608.0f); + candidates[lane] = log_weight - logf(-logf(u)); + } + __syncwarp(); + if (lane == 0) + for (int i = 0; i < 32 && first + i < k; ++i) { + cumulative += weights[i]; + if (first + i > 0 && cumulative > p_limit) { cut = true; break; } + if (candidates[i] > best) { best = candidates[i]; pick = ids[first + i]; } + } + __syncwarp(); + cut = __shfl_sync(0xffffffff, cut, 0); + } + if (lane == 0) selected[draw] = pick; + } + __syncthreads(); + } + if (t == 0) { + if (main) { + int first = selected[0] == 0 ? eos : begin + selected[0] - 1; + bool repeated = false; + for (int i = 0; i < 16; ++i) repeated |= history[i] == first; + const int pick = repeated && semantic(first, begin, begin + 4095) ? selected[1] : selected[0]; + frame[0] = pick == 0 ? eos : begin + pick - 1; + frame[1] = code(frame[0] - begin); + history[step % 16] = frame[0]; + } else frame[output_index] = selected[0]; + } +} diff --git a/zig/src/core/direct_io.zig b/zig/src/core/direct_io.zig index c06f2133889..3c25b7e4868 100644 --- a/zig/src/core/direct_io.zig +++ b/zig/src/core/direct_io.zig @@ -55,15 +55,23 @@ fn readAt(f: File, buf: Buffer, offset: u64, len: usize, ctx: *anyopaque, pread: const want: usize = @intCast(offset + len - lo); const whole = span(offset, len); if (whole > buf.len) return error.BufferTooSmall; + var aligned = f.direct; var got: usize = 0; while (got < want) { // A short O_DIRECT read is retried from the last 4 KiB boundary so the next pread stays aligned. - const at: usize = if (f.direct) std.mem.alignBackward(usize, got, alignment) else got; + const at: usize = if (aligned) std.mem.alignBackward(usize, got, alignment) else got; const ask = whole - at; const n = pread(ctx, f.fd, buf.ptr + at, ask, lo + @as(u64, @intCast(at))); if (n < 0) { - if (std.c.errno(n) == .INTR) continue; - std.log.err("read of {d} bytes at {d} failed: {t}", .{ ask, lo + at, std.c.errno(n) }); + const e = std.c.errno(n); + if (e == .INTR) continue; + // a file system that took the O_DIRECT open can still refuse its reads: the file goes through the cache + if (e == .INVAL and aligned) { + try buffered(f.fd); + aligned = false; + continue; + } + std.log.err("read of {d} bytes at {d} failed: {t}", .{ ask, lo + at, e }); return error.ReadFailed; } if (n == 0) return error.EndOfFile; @@ -75,6 +83,13 @@ fn readAt(f: File, buf: Buffer, offset: u64, len: usize, ctx: *anyopaque, pread: return buf[@intCast(offset - lo)..][0..len]; } +/// Clears O_DIRECT on `fd`, so this read and every later one through it use the page cache. +fn buffered(fd: std.c.fd_t) !void { + const direct_flag: c_int = @bitCast(@as(u32, @bitCast(std.c.O{ .DIRECT = true }))); + const flags = std.c.fcntl(fd, std.c.F.GETFL); + if (flags < 0 or std.c.fcntl(fd, std.c.F.SETFL, flags & ~direct_flag) < 0) return error.ReadFailed; +} + test "span and fits" { try std.testing.expectEqual(@as(usize, 4096), span(0, 1)); try std.testing.expectEqual(@as(usize, 8192), span(4095, 2)); @@ -104,6 +119,44 @@ test "direct reads return the same bytes as buffered reads" { try std.testing.expectError(error.BufferTooSmall, f.read(buf, 1, 1 << 20)); } +/// Refuses its first read with EINVAL, as a file system that accepts an O_DIRECT open but not the read does. +const Refuse = struct { + refused: bool = false, + + fn pread(ctx: *anyopaque, fd: std.c.fd_t, buf: [*]u8, len: usize, offset: u64) isize { + const r: *Refuse = @ptrCast(@alignCast(ctx)); + if (!r.refused) { + r.refused = true; + std.c._errno().* = @backingInt(std.c.E.INVAL); + return -1; + } + return std.c.pread(fd, buf, len, @intCast(offset)); + } +}; + +test "a direct read the file system refuses is read again through the page cache" { + if (builtin.os.tag != .linux) return error.SkipZigTest; + const gpa = std.testing.allocator; + var f = try File.open("/proc/self/exe"); + defer f.close(); + if (!f.direct) return error.SkipZigTest; + var plain: File = .{ .fd = std.c.open("/proc/self/exe", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }), .direct = false }; + try std.testing.expect(plain.fd >= 0); + defer plain.close(); + const buf = try gpa.alignedAlloc(u8, .fromByteUnits(alignment), 1 << 20); + defer gpa.free(buf); + const want = try gpa.alloc(u8, 100000); + defer gpa.free(want); + try std.testing.expectEqual(@as(isize, @intCast(want.len)), std.c.pread(plain.fd, want.ptr, want.len, 12345)); + var refuse: Refuse = .{}; + try std.testing.expectEqualSlices(u8, want, try readAt(f, buf, 12345, want.len, &refuse, Refuse.pread)); + try std.testing.expect(refuse.refused); + const direct_flag: c_int = @bitCast(@as(u32, @bitCast(std.c.O{ .DIRECT = true }))); + try std.testing.expectEqual(@as(c_int, 0), std.c.fcntl(f.fd, std.c.F.GETFL) & direct_flag); + // later reads through the descriptor, now buffered, still return the file's bytes + try std.testing.expectEqualSlices(u8, want[1..][0..4095], try f.read(buf, 12346, 4095)); +} + const Script = struct { plan: []const usize, offs: [8]u64 = undefined, diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 243b3386a48..071e619efa9 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -109,70 +109,6 @@ pub const Request = struct { } }; -/// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash. -pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; - -/// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold. -pub const Vision = struct { - ctx: *anyopaque, - /// The image's bytes (any format the platform decodes) at most ``max_tokens`` tokens; allocated in ``a``. - prepare: *const fn (ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!PreparedImage, - /// The token the chat template writes once per image, expanded to the image's tokens. - image_token: u32, - /// The tokens the template wraps an image in (the image token among them): text that spells one stays text. - markers: []const u32 = &.{}, - /// Tokens the server writes around each image's rows (Nemotron Omni's and ); null: the template's own. - wrap: ?[2]u32 = null, - /// Image tokens one request may hold in all, and images. - image_tokens: u32, - max_images: u32, - /// Video input, when the engine's family reads it. - video: ?VideoOffer = null, - /// The engine's words for a prepare error the server cannot word (a decoder library it lacks); null: the server's. - explain: ?*const fn (err: anyerror) ?[]const u8 = null, -}; - -/// A video's facts as the server's decoder reads them, and its frames on request. -pub const VideoSource = struct { - frames: u64, // the stream's frame count - rate_num: u64, // its average frame rate, num / den - rate_den: u64, - width: u32, - height: u32, - ctx: *anyopaque, - /// The frames at ``indices`` (ascending, distinct), each to ``sink`` in order. - decode: *const fn (ctx: *anyopaque, indices: []const u32, sink: FrameSink) anyerror!void, -}; - -/// Where a decoded frame goes: RGB rows of ``width`` * 3 bytes, ``stride`` bytes apart. -pub const FrameSink = struct { - ctx: *anyopaque, - take: *const fn (ctx: *anyopaque, k: usize, rgb: []const u8, width: u32, height: u32, stride: usize) anyerror!void, -}; - -/// A video prepared for the tower: each group of frames an image, and each group's time in seconds. -pub const PreparedVideo = struct { groups: []PreparedImage, times: []f64 }; - -/// Video input an engine serves (``Vision.video``): how a decoded video becomes images and how the prompt holds them. -pub const VideoOffer = struct { - /// ``src`` at most ``max_tokens`` tokens and ``max_frames`` sampled frames; allocated in ``a``. - prepare: *const fn (ctx: *anyopaque, a: Allocator, src: VideoSource, max_tokens: u32, max_frames: u32) anyerror!PreparedVideo, - /// The token the chat template writes once per video, expanded to its groups. - video_token: u32, - /// The tokens around each group's image tokens; the group's time follows as text. - group_open: u32, - group_close: u32, - /// The tokens the template wraps a video in (the video token among them): text that spells one stays text. - markers: []const u32 = &.{}, - /// Video tokens one request may hold in all, videos, and frames sampled a video. - video_tokens: u32, - max_videos: u32, - max_frames: u32, -}; - -/// --vision: image and video input's limits (``Open.vision``); image_tokens_set: the flag given, over a family default. -pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256 }; - pub const Reason = enum { stop, length, cancelled, failed }; /// What a finished reply's rounds did, for its runtime fields and /metrics. @@ -201,6 +137,8 @@ pub const Event = union(enum) { prompt_logprobs: []const LogprobRow, /// Tokens committed for this request, in order; valid only during the call. tokens: []const u32, + /// A streamed speech request's samples now final, from its start: whole frames, rising, all before ``finished``. + audio: usize, /// The reply ended; nothing follows. ``message`` says why a failed reply failed. finished: struct { reason: Reason, stats: Stats = .{}, message: []const u8 = "" }, }; @@ -214,6 +152,9 @@ pub const Sink = struct { /// What the engine serves, fixed once it has loaded. pub const Info = struct { name: []const u8 = "lanes", + /// Speech-only models must not be offered through the text completion routes. + text_generation: bool = true, + speech: ?SpeechInfo = null, lanes: u32 = 1, /// Prompt plus reply tokens one request may use (0: no limit). context_window: u32 = 0, @@ -384,7 +325,7 @@ pub const Status = struct { fill_run: u64 = 0, }; -pub const SubmitError = error{ Closed, Busy, InvalidSpans, Stale }; // Stale: a learner's put-back has not reached the device +pub const SubmitError = error{ Closed, Busy, InvalidSpans, Unsupported, Stale }; // Stale: a learner's put-back has not reached the device /// What a reply refused or ended for `Stale` says, a submit's error and a queued job's failure alike. pub const stale_message = "a Living Weights delete could not be put back on the device: send the delete again to retry it, or restart the server"; @@ -473,6 +414,8 @@ pub const Engine = struct { decide: ?*const fn (ctx: *anyopaque, d: *Decision) error{ Failed, Refused }!void = null, /// Queue `request` for the family's learner; it stays valid until `done`. Null: this engine does not learn. learn: ?*const fn (ctx: *anyopaque, request: *const LearnRequest, sink: LearnSink) LearnError!void = null, + /// One synthesis; caller storage lives until finished. Null: this engine does not synthesize speech. + submit_speech: ?*const fn (ctx: *anyopaque, id: Id, request: *const SpeechRequest, sink: Sink) SpeechSubmitError!void = null, /// Recall's record for every later request's drafts and writes, before any request (null: no record read). recall: ?*const fn (ctx: *anyopaque, store: *lanes.recall_store.Store) void = null, /// Queue a question about kept states for the engine thread (it stays valid until `done`); false: refused. @@ -488,6 +431,10 @@ pub const Engine = struct { try @import("cache_modes.zig").validate(request.decode_spans); return e.vtable.submit(e.ctx, id, request, sink); } + pub fn submitSpeech(e: Engine, id: Id, request: *const SpeechRequest, sink: Sink) SpeechSubmitError!void { + const f = e.vtable.submit_speech orelse return error.Unsupported; + return f(e.ctx, id, request, sink); + } pub fn cancel(e: Engine, id: Id) void { e.vtable.cancel(e.ctx, id); } @@ -589,6 +536,21 @@ pub const keepalive = @import("keepalive.zig"); /// A model folder's original files kept before --slide first teaches it, its hold and its rollback (originals.zig). pub const originals = @import("originals.zig"); +/// Image and video input: what an engine offers and what the server prepares for its tower (vision_api.zig). +pub const PreparedImage = @import("vision_api.zig").PreparedImage; +pub const Vision = @import("vision_api.zig").Vision; +pub const VideoSource = @import("vision_api.zig").VideoSource; +pub const FrameSink = @import("vision_api.zig").FrameSink; +pub const PreparedVideo = @import("vision_api.zig").PreparedVideo; +pub const VideoOffer = @import("vision_api.zig").VideoOffer; +pub const VisionOpen = @import("vision_api.zig").VisionOpen; + +/// One speech synthesis's request, result, offer and refusals (speech_api.zig). +pub const SpeechRequest = @import("speech_api.zig").Request; +pub const SpeechResult = @import("speech_api.zig").Result; +pub const SpeechInfo = @import("speech_api.zig").Info; +pub const SpeechSubmitError = @import("speech_api.zig").SubmitError; + test { _ = @import("lane_host.zig"); _ = @import("lane_host_test.zig"); diff --git a/zig/src/core/lane_host_recall_test.zig b/zig/src/core/lane_host_recall_test.zig index f8d8a0fd63a..e4d08bc8df9 100644 --- a/zig/src/core/lane_host_recall_test.zig +++ b/zig/src/core/lane_host_recall_test.zig @@ -26,7 +26,7 @@ const Box = struct { defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| { b.rounds = f.stats.rounds; diff --git a/zig/src/core/lane_host_reuse_test.zig b/zig/src/core/lane_host_reuse_test.zig index d24eb2579dd..6a6f7590d59 100644 --- a/zig/src/core/lane_host_reuse_test.zig +++ b/zig/src/core/lane_host_reuse_test.zig @@ -51,7 +51,7 @@ test "a lane host resumes a conversation from its kept prompt state and reports defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| b.done = f.reason, } @@ -148,7 +148,7 @@ test "an image's placeholders are cached by its content: another image under the defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| b.done = f.reason, } @@ -249,7 +249,7 @@ test "a turn's mark evicting the state it resumed from: the hit is reported firs defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| b.done = f.reason, } @@ -365,7 +365,7 @@ test "a learn step that moves the weights drops every kept state: the next turn defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| b.done = f.reason, } diff --git a/zig/src/core/lane_host_rows_test.zig b/zig/src/core/lane_host_rows_test.zig index 3a6cb1e6ed3..edf6416cf0c 100644 --- a/zig/src/core/lane_host_rows_test.zig +++ b/zig/src/core/lane_host_rows_test.zig @@ -67,7 +67,7 @@ const Box = struct { defer b.mutex.unlock(std.testing.io); switch (e.*) { .prefilled => |c| b.cached = c, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(std.testing.allocator, t) catch {}, .finished => |f| b.done = f.reason, } diff --git a/zig/src/core/speech_api.zig b/zig/src/core/speech_api.zig new file mode 100644 index 00000000000..da9e2e13f62 --- /dev/null +++ b/zig/src/core/speech_api.zig @@ -0,0 +1,27 @@ +//! One speech synthesis: the request, its result, what the engine offers, and why a submit is refused. + +/// Mono PCM written before a successful speech request's finished event. +pub const Result = struct { samples: usize = 0 }; + +/// Caller-owned until finished, even on cancellation; a streamed request's pcm[0..n] is the caller's after ``audio`` n. +pub const Request = struct { + prompt: []const u32, + pcm: []f32, + result: *Result, + seed: u64, + max_frames: u32 = 1024, + temperature: f32 = 1, + top_p: f32 = 0.9, + top_k: u32 = 30, + /// Decode while generating and report each final prefix with ``audio`` events; false: one decode after EOS. + stream: bool = false, +}; + +pub const Info = struct { + sample_rate: u32, + frame_length: u32, + max_frames: u32, + max_prompt_tokens: u32, +}; + +pub const SubmitError = error{ Closed, Busy, InvalidRequest, Unsupported }; diff --git a/zig/src/core/vision_api.zig b/zig/src/core/vision_api.zig new file mode 100644 index 00000000000..ab39df65974 --- /dev/null +++ b/zig/src/core/vision_api.zig @@ -0,0 +1,67 @@ +//! What an engine offers for image and video input, and what the server prepares for its tower. +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash. +pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +/// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold. +pub const Vision = struct { + ctx: *anyopaque, + /// The image's bytes (any format the platform decodes) at most ``max_tokens`` tokens; allocated in ``a``. + prepare: *const fn (ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!PreparedImage, + /// The token the chat template writes once per image, expanded to the image's tokens. + image_token: u32, + /// The tokens the template wraps an image in (the image token among them): text that spells one stays text. + markers: []const u32 = &.{}, + /// Tokens the server writes around each image's rows (Nemotron Omni's and ); null: the template's own. + wrap: ?[2]u32 = null, + /// Image tokens one request may hold in all, and images. + image_tokens: u32, + max_images: u32, + /// Video input, when the engine's family reads it. + video: ?VideoOffer = null, + /// The engine's words for a prepare error the server cannot word (a decoder library it lacks); null: the server's. + explain: ?*const fn (err: anyerror) ?[]const u8 = null, +}; + +/// A video's facts as the server's decoder reads them, and its frames on request. +pub const VideoSource = struct { + frames: u64, // the stream's frame count + rate_num: u64, // its average frame rate, num / den + rate_den: u64, + width: u32, + height: u32, + ctx: *anyopaque, + /// The frames at ``indices`` (ascending, distinct), each to ``sink`` in order. + decode: *const fn (ctx: *anyopaque, indices: []const u32, sink: FrameSink) anyerror!void, +}; + +/// Where a decoded frame goes: RGB rows of ``width`` * 3 bytes, ``stride`` bytes apart. +pub const FrameSink = struct { + ctx: *anyopaque, + take: *const fn (ctx: *anyopaque, k: usize, rgb: []const u8, width: u32, height: u32, stride: usize) anyerror!void, +}; + +/// A video prepared for the tower: each group of frames an image, and each group's time in seconds. +pub const PreparedVideo = struct { groups: []PreparedImage, times: []f64 }; + +/// Video input an engine serves (``Vision.video``): how a decoded video becomes images and how the prompt holds them. +pub const VideoOffer = struct { + /// ``src`` at most ``max_tokens`` tokens and ``max_frames`` sampled frames; allocated in ``a``. + prepare: *const fn (ctx: *anyopaque, a: Allocator, src: VideoSource, max_tokens: u32, max_frames: u32) anyerror!PreparedVideo, + /// The token the chat template writes once per video, expanded to its groups. + video_token: u32, + /// The tokens around each group's image tokens; the group's time follows as text. + group_open: u32, + group_close: u32, + /// The tokens the template wraps a video in (the video token among them): text that spells one stays text. + markers: []const u32 = &.{}, + /// Video tokens one request may hold in all, videos, and frames sampled a video. + video_tokens: u32, + max_videos: u32, + max_frames: u32, +}; + +/// --vision: image and video input's limits (``Open.vision``); image_tokens_set: the flag given, over a family default. +pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256 }; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 18542b8cb47..e202c3404b1 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -56,6 +56,10 @@ pub const ck_lane: []const u8 = if (available) &Blob("fatbin_ck_lane").bytes els pub const ck_experts: []const u8 = if (available) &Blob("fatbin_ck_experts").bytes else &.{}; pub const norms: []const u8 = if (available) &Blob("fatbin_norms").bytes else &.{}; pub const embed_rows: []const u8 = if (available) &Blob("fatbin_embed_rows").bytes else &.{}; +pub const drama_backbone: []const u8 = if (available) &Blob("fatbin_drama_backbone").bytes else &.{}; +pub const drama_backbone_gemm: []const u8 = if (available) &Blob("fatbin_drama_backbone_gemm").bytes else &.{}; +pub const drama_tower: []const u8 = if (available) &Blob("fatbin_drama_tower").bytes else &.{}; +pub const drama_codec: []const u8 = if (available) &Blob("fatbin_drama_codec").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/cuda/memory.zig b/zig/src/cuda/memory.zig index 2c469bae2cb..f25bae02291 100644 --- a/zig/src/cuda/memory.zig +++ b/zig/src/cuda/memory.zig @@ -12,6 +12,35 @@ var device_bytes: std.atomic.Value(u64) = .init(0); var host_bytes: std.atomic.Value(u64) = .init(0); var peak_bytes: std.atomic.Value(u64) = .init(0); var counts_mutex: std.atomic.Mutex = .unlocked; +var allocation_limit: ?u64 = null; +var reserved_bytes: u64 = 0; + +/// Caps DeviceBuffer plus pinned HostBuffer bytes (driver-private ones excluded); returns the previous limit. +pub fn setAllocationLimit(limit: ?u64) Error!?u64 { + lockCounts(); + defer counts_mutex.unlock(); + const used = device_bytes.load(.monotonic) +| host_bytes.load(.monotonic) +| reserved_bytes; + if (limit) |cap| if (used > cap) return error.OutOfDeviceMemory; + const previous = allocation_limit; + allocation_limit = limit; + return previous; +} + +fn reserveAllocation(n: usize) Error!void { + lockCounts(); + defer counts_mutex.unlock(); + const used = device_bytes.load(.monotonic) +| host_bytes.load(.monotonic) +| reserved_bytes; + if (allocation_limit) |cap| if (n > cap -| used) return error.OutOfDeviceMemory; + reserved_bytes = std.math.add(u64, reserved_bytes, n) catch return error.OutOfDeviceMemory; +} + +/// A failed driver call refunds its reservation without changing usage or the measured allocation peak. +fn finishAllocation(counter: ?*std.atomic.Value(u64), n: usize) void { + lockCounts(); + defer counts_mutex.unlock(); + reserved_bytes -= n; + if (counter) |c| recordAllocation(c, n); +} /// The counts now; `reset_peak` starts a new peak at the current device bytes. Safe from any thread. pub fn usage(reset_peak: bool) Usage { @@ -30,18 +59,20 @@ fn usageWithHook(reset_peak: bool, hook: anytype) Usage { return .{ .device = now, .host = host_bytes.load(.monotonic), .peak = @max(now, peak_bytes.load(.monotonic)) }; } -fn held(counter: *std.atomic.Value(u64), n: usize) void { - const device = counter == &device_bytes; - if (device) lockCounts(); - defer if (device) counts_mutex.unlock(); +fn recordAllocation(counter: *std.atomic.Value(u64), n: usize) void { const now = counter.fetchAdd(n, .monotonic) + n; if (counter == &device_bytes) _ = peak_bytes.fetchMax(now, .monotonic); } +fn held(counter: *std.atomic.Value(u64), n: usize) void { + lockCounts(); + defer counts_mutex.unlock(); + recordAllocation(counter, n); +} + fn freed(counter: *std.atomic.Value(u64), n: usize) void { - const device = counter == &device_bytes; - if (device) lockCounts(); - defer if (device) counts_mutex.unlock(); + lockCounts(); + defer counts_mutex.unlock(); _ = counter.fetchSub(n, .monotonic); } @@ -57,9 +88,11 @@ pub const DeviceBuffer = struct { /// `len` bytes, 256-byte aligned by the driver; zero bytes allocate nothing and hold address 0. pub fn alloc(d: *const Driver, len: usize) Error!DeviceBuffer { + try reserveAllocation(len); + errdefer finishAllocation(null, len); var p: abi.DevicePtr = 0; if (len > 0) try d.check(d.api.cuMemAlloc_v2(&p, len), "cuMemAlloc"); - held(&device_bytes, len); + finishAllocation(&device_bytes, len); return .{ .d = d, .ptr = p, .len = len }; } @@ -171,9 +204,11 @@ pub const HostBuffer = struct { fn allocFlags(d: *const Driver, len: usize, flags: c_uint) Error!HostBuffer { if (len == 0) return error.Invalid; + try reserveAllocation(len); + errdefer finishAllocation(null, len); var p: ?*anyopaque = null; try d.check(d.api.cuMemHostAlloc(&p, len, flags), "cuMemHostAlloc"); - held(&host_bytes, len); + finishAllocation(&host_bytes, len); const base: [*]align(16) u8 = @ptrCast(@alignCast(p.?)); return .{ .d = d, .bytes = base[0..len] }; } @@ -251,3 +286,63 @@ test "peak reset preserves an allocation between its read and store" { try std.testing.expectEqual(before.device + 100, after.device); try std.testing.expectEqual(before.device + 400, after.peak); } + +test "allocation cap includes pinned and in-flight bytes and refunds failed driver calls" { + const before = usage(true); + const base = before.device + before.host; + const previous = try setAllocationLimit(base + 16); + defer _ = setAllocationLimit(previous) catch unreachable; + var pending: usize = 0; + defer if (pending > 0) finishAllocation(null, pending); + + try reserveAllocation(12); + pending = 12; + try std.testing.expectError(error.OutOfDeviceMemory, reserveAllocation(5)); + try std.testing.expectEqual(before.device, usage(false).device); + finishAllocation(null, 12); + pending = 0; + try std.testing.expectEqual(before.peak, usage(false).peak); + + try reserveAllocation(12); + finishAllocation(&host_bytes, 12); + defer freed(&host_bytes, 12); + try reserveAllocation(4); + finishAllocation(&device_bytes, 4); + defer freed(&device_bytes, 4); + try std.testing.expectError(error.OutOfDeviceMemory, reserveAllocation(1)); + try std.testing.expectError(error.OutOfDeviceMemory, setAllocationLimit(base + 15)); + try std.testing.expectEqual(before.host + 12, usage(false).host); + try std.testing.expectEqual(before.device + 4, usage(false).device); +} + +test "public allocations refused by the cap skip the driver, and failed driver calls are refunded" { + const Fake = struct { + var calls: usize = 0; + // NOT_READY fails the call without the driver's error log, which would fail the test + fn memAlloc(_: *abi.DevicePtr, _: usize) callconv(.c) abi.Result { + calls += 1; + return abi.error_not_ready; + } + fn hostAlloc(_: *?*anyopaque, _: usize, _: c_uint) callconv(.c) abi.Result { + calls += 1; + return abi.error_not_ready; + } + }; + var d: Driver = .{ .lib = undefined, .api = undefined }; + d.api.cuMemAlloc_v2 = Fake.memAlloc; + d.api.cuMemHostAlloc = Fake.hostAlloc; + const before = usage(true); + const previous = try setAllocationLimit(before.device + before.host + 4096); + defer _ = setAllocationLimit(previous) catch unreachable; + + // the second call fits only if the first refunded its reservation + try std.testing.expectError(error.NotReady, DeviceBuffer.alloc(&d, 4096)); + try std.testing.expectError(error.NotReady, HostBuffer.alloc(&d, 4096)); + try std.testing.expectEqual(@as(usize, 2), Fake.calls); + try std.testing.expectEqual(before, usage(false)); + + try std.testing.expectError(error.OutOfDeviceMemory, DeviceBuffer.alloc(&d, 4097)); + try std.testing.expectError(error.OutOfDeviceMemory, HostBuffer.alloc(&d, 4097)); + try std.testing.expectEqual(@as(usize, 2), Fake.calls); + try std.testing.expectEqual(before, usage(false)); +} diff --git a/zig/src/cuda/module.zig b/zig/src/cuda/module.zig index 92fab825451..fa39da84830 100644 --- a/zig/src/cuda/module.zig +++ b/zig/src/cuda/module.zig @@ -53,6 +53,12 @@ pub const Module = struct { try self.d.check(self.d.api.cuModuleGetGlobal_v2(&g.ptr, &g.len, self.handle, name.ptr), "cuModuleGetGlobal"); return g; } + + /// Whether the loaded image defines device global `name`; any driver failure answers false, never an error. + pub fn holds(self: Module, name: [:0]const u8) bool { + var g: Global = .{ .ptr = 0, .len = 0 }; + return self.d.api.cuModuleGetGlobal_v2(&g.ptr, &g.len, self.handle, name.ptr) == abi.success; + } }; pub const Function = struct { @@ -81,3 +87,24 @@ pub const Function = struct { try self.setAttribute(.max_dynamic_shared_size_bytes, @intCast(bytes)); } }; + +test "holds answers whether the image defines a global, and false on any driver failure" { + const Fake = struct { + fn getGlobal(ptr: *abi.DevicePtr, len: *usize, _: abi.Module, name: [*:0]const u8) callconv(.c) abi.Result { + const n = std.mem.span(name); + if (std.mem.eql(u8, n, "marker")) { + ptr.* = 0x1000; + len.* = 4; + return abi.success; + } + // CUDA_ERROR_INVALID_CONTEXT: a failure that is not a missing name + return if (std.mem.eql(u8, n, "lost")) 201 else abi.error_not_found; + } + }; + var d: Driver = .{ .lib = undefined, .api = undefined }; + d.api.cuModuleGetGlobal_v2 = Fake.getGlobal; + const m: Module = .{ .d = &d, .handle = null }; + try std.testing.expect(m.holds("marker")); + try std.testing.expect(!m.holds("absent")); + try std.testing.expect(!m.holds("lost")); +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 6c4e0991b67..9c0a201c91a 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -8,6 +8,7 @@ pub const DeviceBuffer = @import("memory.zig").DeviceBuffer; pub const HostBuffer = @import("memory.zig").HostBuffer; pub const usage = @import("memory.zig").usage; pub const Usage = @import("memory.zig").Usage; +pub const setAllocationLimit = @import("memory.zig").setAllocationLimit; pub const carveout = @import("carveout.zig"); pub const Carveout = carveout.Carveout; pub const Stream = @import("stream.zig").Stream; diff --git a/zig/src/families/drama/backbone.zig b/zig/src/families/drama/backbone.zig new file mode 100644 index 00000000000..4091840402a --- /dev/null +++ b/zig/src/families/drama/backbone.zig @@ -0,0 +1,469 @@ +//! Drama 3 text backbone on CUDA (Qwen3.5-MoE hybrid, 30 DeltaNet + 10 attention layers), one request's state. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const config = @import("backbone_config.zig"); +pub const weights = @import("backbone_weights.zig"); +pub const kernels = @import("backbone_kernels.zig"); +pub const gdn = @import("backbone_gdn.zig"); + +const H = config.hidden; +const top = config.top_k; + +pub const Options = struct { + context: usize = 8192, + max_rows: usize = 128, +}; + +/// Prefill is chunked GDN (bf16 q/k), decode the packed recurrence (fp32 q/k); callers choose it, never row count. +pub const Phase = enum { prefill, decode }; + +pub const Rows = struct { + // Borrowed views, valid until next run/reset/deinit. BF16 row-major [rows, hidden]. + hidden: cuda.DeviceBuffer, + // F32 [4097] for the LAST row only: EOS first, then semantic_start..semantic_end. + semantic_logits: cuda.DeviceBuffer, + rows: usize, +}; + +/// Diagnostic capture points of forward, BF16 [rows, hidden] each; tf-drama-backbone-trace is the only tracer. +pub const Stage = enum { attention_input, attention_residual, attention_output, mlp_input, mlp_residual, mlp_output }; + +/// Hashed by the trace driver so a capture names the exact forward it observed; unreferenced in production. +pub const trace_source = @embedFile("backbone.zig"); + +/// Diagnostic replayOperator selector: a layer's attention, or moe on the FP8 groups addNorm writes in forward. +pub const ReplayOperator = enum { attention, moe }; + +/// Bump offsets in one device allocation, 256-byte aligned. +const Bump = struct { + used: usize = 0, + + fn take(b: *Bump, bytes: usize) usize { + const at = std.mem.alignForward(usize, b.used, 256); + b.used = at + bytes; + return at; + } +}; + +/// Per-call activations for up to `max_rows` rows (offsets until `place`, then device addresses). +const Scratch = struct { + ids: u64 = 0, // i32 [R] + x: u64 = 0, // bf16 [R][H] layer delta (embedding, mixer or MoE output) + residual: u64 = 0, // bf16 [R][H] + normed: u64 = 0, // bf16 [R][H] + proj: u64 = 0, // bf16 [R][max(gdn_in_rows, attn_in_rows)] + conv: u64 = 0, // bf16 [R][conv_dim] + core: u64 = 0, // bf16 [R][value_dim] recurrence output + gated: u64 = 0, // bf16 [R][4096] gated core (DeltaNet) or gated attention, the out projection's input + q: u64 = 0, // bf16 [R][heads][head_dim] + moe_in: u64 = 0, // bf16 [R][moe_in_rows] + picks: u64 = 0, // i32 [P] + routed: u64 = 0, // f32 [P] + xq: u64 = 0, // e4m3 [R][H] + xs: u64 = 0, // f32 [R][H / 128] + members: u64 = 0, // i32 [P] + items: u64 = 0, // i32 [3 * max items] + counts: u64 = 0, // i32 [2] + rank: u64 = 0, // i32 [P] + hist: u64 = 0, // i32 [ceil(P / 1024) * experts] + gu: u64 = 0, // bf16 [P][gu_rows] + hq: u64 = 0, // e4m3 [P][expert_inner] + hs: u64 = 0, // f32 [P][expert_inner / 128] + down: u64 = 0, // bf16 [P][H] + shared_h: u64 = 0, // bf16 [R][shared_inner] + shared_out: u64 = 0, // bf16 [R][H] + gdn: u64 = 0, // the DeltaNet prefill workspace (gdn.Workspace), shared by every layer + + fn layout(rows: usize) struct { Scratch, usize } { + const pairs = rows * top; + const proj_cols = @max(weights.gdn_in_rows, weights.attn_in_rows); + const items = cuda.grouped.maxItems(pairs, config.experts, tile); + const blocks = (pairs + 1023) / 1024; + var b: Bump = .{}; + var s: Scratch = .{}; + s.ids = b.take(rows * 4); + s.x = b.take(rows * H * 2); + s.residual = b.take(rows * H * 2); + s.normed = b.take(rows * H * 2); + s.proj = b.take(rows * proj_cols * 2); + s.conv = b.take(rows * config.conv_dim * 2); + s.core = b.take(rows * config.value_dim * 2); + s.gated = b.take(rows * @max(config.value_dim, config.query_heads * config.head_dim) * 2); + s.q = b.take(rows * config.query_heads * config.head_dim * 2); + s.moe_in = b.take(rows * weights.moe_in_rows * 2); + s.picks = b.take(pairs * 4); + s.routed = b.take(pairs * 4); + s.xq = b.take(rows * H); + s.xs = b.take(rows * (H / config.block) * 4); + s.members = b.take(pairs * 4); + s.items = b.take(3 * items * 4); + s.counts = b.take(2 * 4); + s.rank = b.take(pairs * 4); + s.hist = b.take(blocks * config.experts * 4); + s.gu = b.take(pairs * weights.gu_rows * 2); + s.hq = b.take(pairs * config.expert_inner); + s.hs = b.take(pairs * (config.expert_inner / config.block) * 4); + s.down = b.take(pairs * H * 2); + s.shared_h = b.take(rows * config.shared_inner * 2); + s.shared_out = b.take(rows * H * 2); + s.gdn = b.take(gdnWorkspace(rows)[1]); + return .{ s, b.used }; + } + + fn place(s: *Scratch, base: u64) void { + inline for (@typeInfo(Scratch).@"struct".field_names) |name| @field(s, name) += base; + } +}; + +const tile = 16; // routed pairs an expert item takes (the plan's decode tile; the expert kernel's 16 mma rows) + +const conv_state_bytes = (config.conv_taps - 1) * config.conv_dim * 2; // bf16 [3][conv_dim] a DeltaNet layer +const rec_state_bytes = config.linear_value_heads * config.linear_dim * config.linear_dim * 4; // f32 [32][128][128] +const gdn_qkv_cache_bytes = gdn.chunk_rows * config.conv_dim * 2; // bf16 [64][conv_dim] the unfinished chunk's rows +const gdn_ba_cache_bytes = gdn.chunk_rows * 2 * config.linear_value_heads * 2; // bf16 [64][b 32 | a 32] +const gdn_state_bytes = 2 * rec_state_bytes + gdn_qkv_cache_bytes + gdn_ba_cache_bytes; // a DeltaNet layer's gdn.State + +fn gdnWorkspace(rows: usize) struct { gdn.Workspace, usize } { + return gdn.Workspace.layout(rows, config.linear_key_heads, config.linear_value_heads); +} + +/// DeltaNet layer `slot`'s recurrent state in the state buffer at `base`: two FP32 banks, then the row caches. +fn gdnState(base: u64, slot: usize) gdn.State { + const at = base + config.linear_layers * conv_state_bytes + slot * gdn_state_bytes; + return .{ + .banks = .{ at, at + rec_state_bytes }, + .qkv_cache = at + 2 * rec_state_bytes, + .ba_cache = at + 2 * rec_state_bytes + gdn_qkv_cache_bytes, + }; +} + +pub const Model = struct { + hidden: usize, + semantic_start: u32, + semantic_end: u32, + eos: u32, + + gpa: std.mem.Allocator, + d: *const cuda.Driver, + options: Options, + k: kernels.Kernels, + w: weights.Weights, + scratch_buf: cuda.DeviceBuffer, + state_buf: cuda.DeviceBuffer, // DeltaNet conv states, then per DeltaNet layer its gdn.State banks and row caches + kv_buf: cuda.DeviceBuffer, // per attention layer: k cache then v cache, bf16 [context][kv_heads][head_dim] + hidden_buf: cuda.DeviceBuffer, // bf16 [max_rows][H] + logits_buf: cuda.DeviceBuffer, // f32 [4097], the last row's semantic logits + tokens: cuda.HostBuffer, // pinned i32 [max_rows] + s: Scratch, + gdn_ws: gdn.Workspace, // placed in scratch_buf + gdn_states: [config.linear_layers]gdn.State, // per DeltaNet layer: device addresses and chunk metadata + pos: usize = 0, + /// Set while a run's device work is in flight; a failed run leaves it set and only reset clears it. + poisoned: bool = false, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *cuda.Context, checkpoint_dir: []const u8, kernel_dir: []const u8, options: Options) !Model { + if (options.max_rows == 0 or options.context == 0 or options.context > 262144) return error.BadDramaOptions; + if (try ctx.capability() < 89) return error.DramaNeedsFp8Mma; // the experts' e4m3 mma is sm_89+ + const d = ctx.d; + const c = try config.Config.read(gpa, io, checkpoint_dir); + var k = try kernels.Kernels.load(gpa, io, d, kernel_dir); + errdefer k.unload(); + var w = blk: { + var stream = try cuda.Stream.init(d, true); + defer stream.deinit(); + break :blk try weights.load(gpa, io, d, stream, checkpoint_dir, c); + }; + errdefer w.deinit(); + const R = options.max_rows; + var s, const scratch_bytes = Scratch.layout(R); + var scratch_buf = try cuda.DeviceBuffer.alloc(d, scratch_bytes); + errdefer scratch_buf.free(); + try scratch_buf.fill8(0, null); + s.place(scratch_buf.ptr); + const gdn_ws = gdnWorkspace(R)[0].place(s.gdn); + var state_buf = try cuda.DeviceBuffer.alloc(d, config.linear_layers * (conv_state_bytes + gdn_state_bytes)); + errdefer state_buf.free(); + try state_buf.fill8(0, null); + var gdn_states: [config.linear_layers]gdn.State = undefined; + for (&gdn_states, 0..) |*st, slot| st.* = gdnState(state_buf.ptr, slot); + var kv_buf = try cuda.DeviceBuffer.alloc(d, config.full_layers * 2 * kvBytes(options.context)); + errdefer kv_buf.free(); + var hidden_buf = try cuda.DeviceBuffer.alloc(d, R * H * 2); + errdefer hidden_buf.free(); + var logits_buf = try cuda.DeviceBuffer.alloc(d, weights.head_cols * 4); + errdefer logits_buf.free(); + const tokens = try cuda.HostBuffer.alloc(d, R * 4); + return .{ + .hidden = H, + .semantic_start = c.semantic_start, + .semantic_end = c.semantic_end, + .eos = c.eos, + .gpa = gpa, + .d = d, + .options = options, + .k = k, + .w = w, + .scratch_buf = scratch_buf, + .state_buf = state_buf, + .kv_buf = kv_buf, + .hidden_buf = hidden_buf, + .logits_buf = logits_buf, + .tokens = tokens, + .s = s, + .gdn_ws = gdn_ws, + .gdn_states = gdn_states, + }; + } + + pub fn deinit(self: *Model) void { + self.tokens.free(); + self.logits_buf.free(); + self.hidden_buf.free(); + self.kv_buf.free(); + self.state_buf.free(); + self.scratch_buf.free(); + self.w.deinit(); + self.k.unload(); + self.* = undefined; + } + + /// Clears conv and recurrent states, row caches and chunk metadata to position 0; the KV cache is overwritten. + pub fn reset(self: *Model, stream: cuda.Stream) !void { + try self.state_buf.fill8(0, stream.handle); + try stream.synchronize(); + for (&self.gdn_states) |*st| st.resetMetadata(); + self.pos = 0; + self.poisoned = false; + } + + fn kvBytes(context: usize) usize { + return context * config.kv_heads * config.head_dim * 2; + } + + fn convState(self: *const Model, slot: usize) u64 { + return self.state_buf.ptr + slot * conv_state_bytes; + } + + fn kCache(self: *const Model, slot: usize) u64 { + return self.kv_buf.ptr + (2 * slot) * kvBytes(self.options.context); + } + + fn vCache(self: *const Model, slot: usize) u64 { + return self.kv_buf.ptr + (2 * slot + 1) * kvBytes(self.options.context); + } + + // Appends rows; semantic rows mix in extra (the codebook-1 embedding) times 1/sqrt(2); overflow is refused first. + pub fn run(self: *Model, stream: cuda.Stream, phase: Phase, tokens: []const u32, extra: ?cuda.DeviceBuffer) !Rows { + return self.runTraced(stream, phase, tokens, extra, {}); + } + + /// run with stage captures: trace is {} (compiled out) or a tracer reading each stage on stream before returning. + pub fn runTraced(self: *Model, stream: cuda.Stream, phase: Phase, tokens: []const u32, extra: ?cuda.DeviceBuffer, trace: anytype) !Rows { + if (self.poisoned) return error.DramaStateNeedsReset; + const n = tokens.len; + if (n == 0) return error.EmptyDramaRun; + if (n > self.options.max_rows) return error.TooManyDramaRows; + if (self.pos + n > self.options.context) return error.DramaContextOverflow; + for (tokens) |t| if (t >= config.vocab) return error.DramaTokenOutOfRange; + if (extra) |e| if (e.len < n * H * 2) return error.DramaExtraRowsShort; + self.poisoned = true; + errdefer stream.synchronize() catch {}; // queued kernels may still read tokens/extra; drain before returning + const ids = self.tokens.slice(i32)[0..n]; + for (ids, tokens) |*o, t| o.* = @intCast(t); + try self.d.check(self.d.api.cuMemcpyHtoDAsync_v2(self.s.ids, ids.ptr, n * 4, stream.handle), "cuMemcpyHtoDAsync"); + try self.forward(stream, phase, n, extra, trace); + try stream.synchronize(); + self.pos += n; + self.poisoned = false; + return .{ + .hidden = .{ .d = self.d, .ptr = self.hidden_buf.ptr, .len = n * H * 2, .borrowed = true }, + .semantic_logits = .{ .d = self.d, .ptr = self.logits_buf.ptr, .len = weights.head_cols * 4, .borrowed = true }, + .rows = n, + }; + } + + fn forward(self: *Model, s: cuda.Stream, phase: Phase, n: usize, extra: ?cuda.DeviceBuffer, trace: anytype) !void { + const k = &self.k; + const sc = &self.s; + try k.embed.bf16(s, sc.ids, self.w.embed, sc.x, n, H); + if (extra) |e| try k.semanticMix(s, sc.ids, sc.x, e.ptr, n, H, self.semantic_start, self.semantic_end); + for (&self.w.layers, 0..) |*l, i| { + try k.addNorm(s, sc.x, sc.residual, l.ln1, sc.normed, null, null, n, H, config.eps, i == 0); + try self.stage(trace, s, i, .attention_input, sc.normed, n); + try self.stage(trace, s, i, .attention_residual, sc.residual, n); + if (config.linear(i)) try self.deltaNet(s, phase, l, config.slot(i), n) else try self.fullAttention(s, l, config.slot(i), n); + try self.stage(trace, s, i, .attention_output, sc.x, n); + try k.addNorm(s, sc.x, sc.residual, l.ln2, sc.normed, sc.xq, sc.xs, n, H, config.eps, false); + try self.stage(trace, s, i, .mlp_input, sc.normed, n); + try self.stage(trace, s, i, .mlp_residual, sc.residual, n); + try self.moe(s, l, n); + try self.stage(trace, s, i, .mlp_output, sc.x, n); + } + try k.addNorm(s, sc.x, sc.residual, self.w.final_norm, self.hidden_buf.ptr, null, null, n, H, config.eps, false); + try k.head(s, self.hidden_buf.ptr + (n - 1) * H * 2, self.w.head, weights.head_cols, H, self.logits_buf.ptr); + } + + /// One capture point; with a void trace the comptime-false branch is never analyzed and emits nothing. + inline fn stage(self: *const Model, trace: anytype, s: cuda.Stream, layer: usize, comptime which: Stage, ptr: u64, n: usize) !void { + if (@TypeOf(trace) != void) try trace.capture(s, layer, which, cuda.DeviceBuffer{ .d = self.d, .ptr = ptr, .len = n * H * 2, .borrowed = true }, self.pos); + } + + /// Diagnostic: one layer's production operator on uploaded chunks after a fresh reset; leaves the model poisoned. + pub fn replayOperator(self: *Model, stream: cuda.Stream, layer: usize, operator: ReplayOperator, chunks: []const usize, input: []const u8, output: []u8) !void { + if (self.poisoned) return error.DramaStateNeedsReset; + if (self.pos != 0) return error.DramaReplayNeedsReset; + if (layer >= self.w.layers.len) return error.DramaReplayLayerOutOfRange; + var rows: usize = 0; + for (chunks) |n| { + if (n == 0) return error.EmptyDramaRun; + if (n > self.options.max_rows) return error.TooManyDramaRows; + rows += n; + } + if (rows == 0) return error.EmptyDramaRun; + if (rows > self.options.context) return error.DramaContextOverflow; + if (input.len != rows * H * 2 or output.len != rows * H * 2) return error.DramaReplayRowsMismatch; + self.poisoned = true; // never cleared here: the other layers' state no longer matches pos + errdefer stream.synchronize() catch {}; // queued copies may still touch input/output; drain before returning + const l = &self.w.layers[layer]; + var row0: usize = 0; + for (chunks) |n| { + const at = row0 * H * 2; + const bytes = n * H * 2; + const normed: cuda.DeviceBuffer = .{ .d = self.d, .ptr = self.s.normed, .len = bytes, .borrowed = true }; + try normed.uploadAsync(0, input[at..][0..bytes], stream.handle); + self.pos = row0; + switch (operator) { + .attention => if (config.linear(layer)) + try self.deltaNet(stream, .prefill, l, config.slot(layer), n) + else + try self.fullAttention(stream, l, config.slot(layer), n), + .moe => { + try self.k.actQuant(stream, self.s.normed, H, self.s.xq, self.s.xs, n, H); + try self.moe(stream, l, n); + }, + } + const x: cuda.DeviceBuffer = .{ .d = self.d, .ptr = self.s.x, .len = bytes, .borrowed = true }; + try x.downloadAsync(0, output[at..][0..bytes], stream.handle); + row0 += n; + } + try stream.synchronize(); + self.pos = row0; + } + + /// Qwen3.5 GatedDeltaNet: in projection, causal conv + silu, gated delta rule, RMSNormGated * silu(z), out_proj. + fn deltaNet(self: *Model, s: cuda.Stream, phase: Phase, l: *const weights.Layer, slot: usize, n: usize) !void { + const k = &self.k; + const sc = &self.s; + const ld = weights.gdn_in_rows; + try k.gemm(s, sc.normed, H, n, l.gdn_in, ld, H, sc.proj, ld); + const recurrence: gdn.Run = .{ + .qkv = sc.conv, + .ld_qkv = config.conv_dim, + .ba = sc.proj + weights.gdn_b_col * 2, + .ld_ba = ld, + .a_log = l.a_log, + .dt_bias = l.dt_bias, + .y = sc.core, + .rows = n, + .nk = config.linear_key_heads, + .nv = config.linear_value_heads, + .dv = config.linear_dim, + .scale = @floatCast(1.0 / @sqrt(@as(f64, config.linear_dim))), + }; + const state = &self.gdn_states[slot]; + switch (phase) { + .prefill => { + try k.convPrefill(s, sc.proj, ld, l.conv, self.convState(slot), sc.conv, n, config.conv_dim); + try k.gdn.prefill(s, state, self.gdn_ws, recurrence); + }, + .decode => { + try k.conv(s, sc.proj, ld, l.conv, self.convState(slot), sc.conv, n, config.conv_dim); + try k.gdn.decode(s, state, recurrence); + }, + } + try k.gatedRms(s, sc.core, config.value_dim, sc.proj + weights.gdn_z_col * 2, ld, l.gnorm, sc.gated, n, config.eps); + try k.gemm(s, sc.gated, config.value_dim, n, l.gdn_out, H, config.value_dim, sc.x, H); + } + + /// Gated full attention: q|gate, k, v projection; q/k Gemma norm + partial RoPE; causal GQA; sigmoid gate; o_proj. + fn fullAttention(self: *Model, s: cuda.Stream, l: *const weights.Layer, slot: usize, n: usize) !void { + const k = &self.k; + const sc = &self.s; + const ld = weights.attn_in_rows; + const width = config.query_heads * config.head_dim; + try k.gemm(s, sc.normed, H, n, l.attn_in, ld, H, sc.proj, ld); + try k.attention(s, .{ + .qkv = sc.proj, + .ld_qkv = ld, + .q_norm = l.q_norm, + .k_norm = l.k_norm, + .inv_freq = self.w.inv_freq, + .q = sc.q, + .kc = self.kCache(slot), + .vc = self.vCache(slot), + .out = sc.gated, + .pos0 = self.pos, + .rows = n, + .heads = config.query_heads, + .kv_heads = config.kv_heads, + .eps = config.eps, + .scale = 1.0 / 16.0, // head_dim ** -0.5 + }); + try k.gemm(s, sc.gated, width, n, l.attn_out, H, width, sc.x, H); + } + + /// Top-8 block-FP8 experts and the gated shared expert on Scratch.normed and its FP8 groups in xq / xs. + fn moe(self: *Model, s: cuda.Stream, l: *const weights.Layer, n: usize) !void { + const k = &self.k; + const sc = &self.s; + const pairs = n * top; + const ld = weights.moe_in_rows; + const I = config.expert_inner; + comptime std.debug.assert(config.shared_inner == I); // one SwiGLU launch serves both experts + try k.gemm(s, sc.normed, H, n, l.moe_in, ld, H, sc.moe_in, ld); + try k.topk(s, sc.moe_in + weights.router_col * 2, ld, sc.picks, sc.routed, n, top); + const plan: cuda.grouped.Plan = .{ .members = sc.members, .items = sc.items, .counts = sc.counts, .rank = sc.rank, .hist = sc.hist }; + try k.router.route(s, sc.picks, pairs, config.experts, tile, plan); + const items = cuda.grouped.maxItems(pairs, config.experts, tile); + try k.expert(s, plan, pairs, .{ + .a = sc.xq, + .a_div = top, + .a_scales = sc.xs, + .w = l.gu, + .w_scales = l.gu_s, + .n = weights.gu_rows, + .kdim = H, + .max_items = items, + .routed = null, + .y = sc.gu, + }); + try k.siluMul(s, sc.gu, weights.gu_rows, sc.hq, sc.hs, pairs, sc.moe_in, ld, sc.shared_h, n, I); + try k.expert(s, plan, pairs, .{ + .a = sc.hq, + .a_div = 1, + .a_scales = sc.hs, + .w = l.dn, + .w_scales = l.dn_s, + .n = H, + .kdim = I, + .max_items = items, + .routed = sc.routed, + .y = sc.down, + }); + try k.gemm(s, sc.shared_h, config.shared_inner, n, l.shared_down, H, config.shared_inner, sc.shared_out, H); + try k.combine(s, sc.down, top, sc.normed, l.shared_gate, sc.shared_out, sc.x, n, H); + } +}; + +test "scratch layout keeps every region 256-byte aligned and disjoint" { + const s, const total = Scratch.layout(128); + var last: u64 = 0; + inline for (@typeInfo(Scratch).@"struct".field_names, 0..) |name, i| { + const at = @field(s, name); + try std.testing.expect(at % 256 == 0); + if (i > 0) try std.testing.expect(at > last); + last = at; + } + try std.testing.expect(total > last); +} diff --git a/zig/src/families/drama/backbone_config.zig b/zig/src/families/drama/backbone_config.zig new file mode 100644 index 00000000000..03ea0cd5d2e --- /dev/null +++ b/zig/src/families/drama/backbone_config.zig @@ -0,0 +1,155 @@ +//! Admission for the Drama 3 (fish_omni) text backbone: the pinned Qwen3.5-35B-A3B hybrid geometry, block-FP8 experts. +const std = @import("std"); + +pub const hidden = 2048; +pub const vocab = 252288; +pub const layers = 40; +pub const full_interval = 4; // layers 3, 7, ..., 39 are full attention, the rest Gated DeltaNet +pub const full_layers = layers / full_interval; +pub const linear_layers = layers - full_layers; + +pub const linear_key_heads = 16; +pub const linear_value_heads = 32; +pub const linear_dim = 128; // key and value head width +pub const conv_taps = 4; +pub const conv_dim = 2 * linear_key_heads * linear_dim + linear_value_heads * linear_dim; // q | k | v = 8192 +pub const value_dim = linear_value_heads * linear_dim; // 4096 (z and the recurrence output) + +pub const query_heads = 16; +pub const kv_heads = 2; +pub const head_dim = 256; +pub const rotary_dim = 64; +pub const theta: f64 = 10000000; + +pub const experts = 256; +pub const top_k = 8; +pub const expert_inner = 512; +pub const shared_inner = 512; +pub const block = 128; // FP8 weight block rows and columns; activation group width + +pub const eps: f32 = 1e-6; + +pub const Config = struct { + eos: u32, + semantic_start: u32, + semantic_end: u32, + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + return parse(gpa, bytes); + } +}; + +/// Whether layer `index` is a Gated DeltaNet ("linear_attention") layer. +pub fn linear(index: usize) bool { + return index % full_interval != full_interval - 1; +} + +/// The layer's slot among its kind (DeltaNet state or attention cache index). +pub fn slot(index: usize) usize { + return if (linear(index)) index - index / full_interval else index / full_interval; +} + +fn object(v: std.json.Value) !std.json.ObjectMap { + return if (v == .object) v.object else error.BadDramaConfig; +} + +fn field(o: std.json.ObjectMap, key: []const u8) !std.json.Value { + return o.get(key) orelse error.BadDramaConfig; +} + +fn number(v: std.json.Value) !f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.BadDramaConfig, + }; +} + +fn integer(o: std.json.ObjectMap, key: []const u8) !u64 { + const v = try field(o, key); + if (v != .integer or v.integer < 0) return error.BadDramaConfig; + return @intCast(v.integer); +} + +fn string(o: std.json.ObjectMap, key: []const u8, expected: []const u8) !void { + const v = try field(o, key); + if (v != .string or !std.mem.eql(u8, v.string, expected)) return error.UnsupportedDramaConfig; +} + +fn boolean(o: std.json.ObjectMap, key: []const u8, expected: bool) !void { + const v = try field(o, key); + if (v != .bool or v.bool != expected) return error.UnsupportedDramaConfig; +} + +fn quantization(o: std.json.ObjectMap) !void { + try string(o, "quant_method", "bsgemm-moe"); + try string(o, "activation_scheme", "dynamic"); + const size = try field(o, "weight_block_size"); + if (size != .array or size.array.items.len != 2) return error.UnsupportedDramaQuantization; + for (size.array.items) |s| if (s != .integer or s.integer != block) return error.UnsupportedDramaQuantization; +} + +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config { + const parsed = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); + defer parsed.deinit(); + const root = try object(parsed.value); + try string(root, "model_type", "fish_omni"); + try quantization(try object(try field(root, "quantization_config"))); + const text = try object(try field(root, "text_config")); + try string(text, "model_type", "fish_omni_text"); + try boolean(text, "tie_word_embeddings", false); + try boolean(text, "attention_bias", false); + try boolean(text, "attn_output_gate", true); + try boolean(text, "use_qk_norm", true); + try boolean(text, "layernorm_zero_centered_gamma", true); + try boolean(text, "shared_expert_gate", true); + // absent in the pinned text_config: Qwen3_5MoeTextConfig's default (true) applies, as SGLang's TopK reads it + if (text.get("norm_topk_prob")) |v| if (v != .bool or !v.bool) return error.UnsupportedDramaConfig; + try boolean(text, "rotary_interleaved", false); + try string(text, "hidden_act", "silu"); + try string(text, "mamba_ssm_dtype", "float32"); + const dims = .{ + .{ "hidden_size", hidden }, .{ "vocab_size", vocab }, .{ "num_hidden_layers", layers }, + .{ "linear_num_key_heads", linear_key_heads }, .{ "linear_num_value_heads", linear_value_heads }, .{ "linear_key_head_dim", linear_dim }, + .{ "linear_value_head_dim", linear_dim }, .{ "linear_conv_kernel_dim", conv_taps }, .{ "num_attention_heads", query_heads }, + .{ "num_key_value_heads", kv_heads }, .{ "head_dim", head_dim }, .{ "num_experts", experts }, + .{ "num_experts_per_tok", top_k }, .{ "moe_intermediate_size", expert_inner }, .{ "shared_expert_intermediate_size", shared_inner }, + }; + inline for (dims) |d| if (try integer(text, d[0]) != d[1]) return error.UnsupportedDramaGeometry; + if (try number(try field(text, "rms_norm_eps")) != 1e-6) return error.UnsupportedDramaConfig; + const types = try field(text, "layer_types"); + if (types != .array or types.array.items.len != layers) return error.UnsupportedDramaGeometry; + for (types.array.items, 0..) |kind, i| { + if (kind != .string or !std.mem.eql(u8, kind.string, if (linear(i)) "linear_attention" else "full_attention")) + return error.UnsupportedDramaGeometry; + } + const mlp = try field(text, "mlp_layer_types"); + if (mlp != .array or mlp.array.items.len != layers) return error.UnsupportedDramaGeometry; + for (mlp.array.items) |kind| if (kind != .string or !std.mem.eql(u8, kind.string, "moe")) return error.UnsupportedDramaGeometry; + const rope = try object(try field(text, "rope_parameters")); + try string(rope, "rope_type", "default"); + if (try number(try field(rope, "rope_theta")) != theta or + try number(try field(rope, "partial_rotary_factor")) != 0.25) return error.UnsupportedDramaRotary; + const audio = try object(try field(root, "audio_decoder_config")); + if (try integer(audio, "vq_backbone_codebooks") != 1) return error.UnsupportedDramaConfig; + try string(audio, "vq_feature_placement", "backbone_partial"); + const eos = try integer(root, "eos_token_id"); + const start = try integer(root, "semantic_start_token_id"); + const end = try integer(root, "semantic_end_token_id"); + if (try integer(text, "eos_token_id") != eos) return error.BadDramaConfig; + // semantic logits are EOS then the 4096-code band; the band sits above EOS inside the vocabulary + if (end < start or end - start + 1 != 4096 or end >= vocab or eos >= start) return error.UnsupportedDramaConfig; + return .{ .eos = @intCast(eos), .semantic_start = @intCast(start), .semantic_end = @intCast(end) }; +} + +test "layer kinds and slots follow the 3 DeltaNet : 1 attention pattern" { + try std.testing.expect(linear(0) and linear(2) and !linear(3) and !linear(39)); + try std.testing.expectEqual(@as(usize, 2), slot(2)); + try std.testing.expectEqual(@as(usize, 3), slot(4)); // the fourth DeltaNet layer + try std.testing.expectEqual(@as(usize, 9), slot(39)); // the tenth attention layer + try std.testing.expectEqual(@as(usize, linear_layers - 1), slot(38)); +} diff --git a/zig/src/families/drama/backbone_gdn.zig b/zig/src/families/drama/backbone_gdn.zig new file mode 100644 index 00000000000..6df0cf36945 --- /dev/null +++ b/zig/src/families/drama/backbone_gdn.zig @@ -0,0 +1,343 @@ +//! Gated DeltaNet for one layer: canonical 64-row chunked prefill (after SGLang/FLA) and the packed decode recurrence. +const std = @import("std"); +const cuda = @import("cuda"); + +/// Prefill chunk length (fla chunk.py CHUNK_SIZE); the row cache holds one chunk. +pub const chunk_rows: usize = 64; +/// Key and value head width the kernels are written for. +const head_dim: usize = 128; +/// l2norm_fwd's eps. +const l2norm_eps: f32 = 1e-6; +const max_int: usize = std.math.maxInt(i32); +/// Grid y / z limit. +const max_grid_yz: usize = 65535; + +/// One layer's recurrent state. All addresses are caller device memory; resetMetadata never touches it. +pub const State = struct { + banks: [2]u64, // FP32 [nv][128 v][128 k] each, distinct, 16-byte aligned + qkv_cache: u64, // BF16 [64, (2*nk+nv)*128] + ba_cache: u64, // BF16 [64, 2*nv] + pending: usize = 0, // rows of the unfinished chunk in the caches + committed_bank: u1 = 0, + + /// The latest state: the trial bank while a chunk is unfinished, else the committed bank. + pub fn current(self: *const State) u64 { + return self.banks[if (self.pending > 0) ~self.committed_bank else self.committed_bank]; + } + + /// Back to an empty state's metadata. DOES NOT zero device memory: the caller zeroes the banks first. + pub fn resetMetadata(self: *State) void { + self.pending = 0; + self.committed_bank = 0; + } + + fn committed(self: *const State) u64 { + return self.banks[self.committed_bank]; + } + + fn other(self: *const State) u64 { + return self.banks[~self.committed_bank]; + } + + fn commit(self: *State) void { + self.committed_bank = ~self.committed_bank; + self.pending = 0; + } +}; + +/// Prefill intermediates for segments of up to rows rows, reusable across layers on one stream. +pub const Workspace = struct { + rows: usize, // capacity, a multiple of chunk_rows + nk: usize, + nv: usize, + qk: u64 = 0, // bf16 [rows][2 nk][128] normalized q heads then k heads + g: u64 = 0, // f32 [rows][nv] + gc: u64 = 0, // f32 [rows][nv] chunk-local cumsum of g + beta: u64 = 0, // f32 [rows][nv] bf16 values + a: u64 = 0, // bf16 [rows][nv][64] (I + A)^-1 + w: u64 = 0, // bf16 [rows][nv][128] + u: u64 = 0, // bf16 [rows][nv][128] + vn: u64 = 0, // bf16 [rows][nv][128] v_new + h: u64 = 0, // bf16 [rows / 64][nv][128 v][128 k] state at each chunk start + + const device = .{ "qk", "g", "gc", "beta", "a", "w", "u", "vn", "h" }; + + /// Region offsets (256-byte aligned) and size for max(64, floor(max_rows / 64) * 64) rows. + pub fn layout(max_rows: usize, nk: usize, nv: usize) struct { Workspace, usize } { + const rows = @max(chunk_rows, max_rows / chunk_rows * chunk_rows); + const vec = rows * nv * head_dim * 2; + var used: usize = 0; + var ws: Workspace = .{ .rows = rows, .nk = nk, .nv = nv }; + ws.qk = take(&used, rows * 2 * nk * head_dim * 2); + ws.g = take(&used, rows * nv * 4); + ws.gc = take(&used, rows * nv * 4); + ws.beta = take(&used, rows * nv * 4); + ws.a = take(&used, rows * nv * chunk_rows * 2); + ws.w = take(&used, vec); + ws.u = take(&used, vec); + ws.vn = take(&used, vec); + ws.h = take(&used, rows / chunk_rows * nv * head_dim * head_dim * 2); + return .{ ws, used }; + } + + /// The same layout at device address `base`. + pub fn place(self: Workspace, base: u64) Workspace { + var ws = self; + inline for (device) |name| @field(ws, name) += base; + return ws; + } + + fn take(used: *usize, bytes: usize) u64 { + const at = std.mem.alignForward(usize, used.*, 256); + used.* = at + bytes; + return at; + } +}; + +/// One call's rows: qkv post-convolution, ba = [b | a], a_log and dt_bias FP32, y BF16 [rows][nv][dv]. +pub const Run = struct { + qkv: u64, + ld_qkv: usize, + ba: u64, + ld_ba: usize, + a_log: u64, + dt_bias: u64, + y: u64, + rows: usize, + nk: usize, + nv: usize, + dv: usize, + scale: f32, +}; + +/// One six-kernel segment from a chunk boundary, state_in -> state_out, emitting rows emit_from.. to y. +const Segment = struct { + qkv: u64, + ld_qkv: usize, + ba: u64, + ld_ba: usize, + rows: usize, + emit_from: usize, + y: u64, + state_in: u64, + state_out: u64, +}; + +fn go(s: cuda.Stream, f: cuda.Function, grid: [3]usize, block: u32, a: *cuda.Args) !void { + const g: cuda.Dim3 = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }; + try cuda.launch.launch(f, .{ .grid = g, .block = .{ .x = block } }, s, a); +} + +fn int(v: usize) i32 { + return @intCast(v); +} + +fn checkRun(r: Run) !void { + if (r.dv != head_dim or r.nk == 0 or r.nv == 0 or r.nv % r.nk != 0 or r.nv > max_grid_yz) return error.DramaGdnShape; + if (r.rows == 0 or r.rows > max_int / (2 * r.nk)) return error.DramaGdnShape; + if (r.ld_qkv < (2 * r.nk + r.nv) * head_dim or r.ld_qkv > max_int or r.ld_ba < 2 * r.nv or r.ld_ba > max_int) return error.DramaGdnShape; +} + +fn checkBanks(st: *const State, nv: usize) !void { + const bytes = nv * head_dim * head_dim * 4; + const lo = @min(st.banks[0], st.banks[1]); + const hi = @max(st.banks[0], st.banks[1]); + if (st.banks[0] % 16 != 0 or st.banks[1] % 16 != 0 or hi - lo < bytes) return error.DramaGdnState; + if (st.pending >= chunk_rows) return error.DramaGdnState; +} + +pub const Kernels = struct { + l2norm_fn: cuda.Function, + gate_fn: cuda.Function, + kkt_fn: cuda.Function, + wu_fn: cuda.Function, + h_fn: cuda.Function, + o_fn: cuda.Function, + append_fn: cuda.Function, + decode_fn: cuda.Function, + + /// Resolves the exports of the drama_backbone glue image. + pub fn init(module: *cuda.Module) !Kernels { + return .{ + .l2norm_fn = try module.function("drama_gdn_chunk_l2norm"), + .gate_fn = try module.function("drama_gdn_chunk_gate"), + .kkt_fn = try module.function("drama_gdn_chunk_kkt"), + .wu_fn = try module.function("drama_gdn_chunk_wu"), + .h_fn = try module.function("drama_gdn_chunk_h"), + .o_fn = try module.function("drama_gdn_chunk_o"), + .append_fn = try module.function("drama_gdn_chunk_append"), + .decode_fn = try module.function("drama_gdn_recur"), + }; + } + + /// Prefill rows on canonical chunk boundaries (see the file comment). Validates everything before the first launch. + pub fn prefill(self: *const Kernels, stream: cuda.Stream, state: *State, workspace: Workspace, run: Run) !void { + try checkRun(run); + try checkBanks(state, run.nv); + if (state.qkv_cache == 0 or state.ba_cache == 0) return error.DramaGdnState; + if (workspace.nk != run.nk or workspace.nv != run.nv or workspace.rows == 0 or workspace.rows % chunk_rows != 0) return error.DramaGdnWorkspace; + const head = if (state.pending > 0) @min(chunk_rows - state.pending, run.rows) else 0; + const bulk = (run.rows - head) / chunk_rows * chunk_rows; + if (bulk > workspace.rows or bulk / chunk_rows > max_grid_yz) return error.DramaGdnWorkspace; + const y_row = run.nv * run.dv * 2; + var done: usize = 0; + if (head > 0) { + try self.unfinished(stream, state, workspace, run, 0, head); + done = head; + } + if (bulk > 0) { + try self.chain(stream, workspace, run, .{ + .qkv = run.qkv + done * run.ld_qkv * 2, + .ld_qkv = run.ld_qkv, + .ba = run.ba + done * run.ld_ba * 2, + .ld_ba = run.ld_ba, + .rows = bulk, + .emit_from = 0, + .y = run.y + done * y_row, + .state_in = state.committed(), + .state_out = state.other(), + }); + state.commit(); + done += bulk; + } + if (done < run.rows) try self.unfinished(stream, state, workspace, run, done, run.rows - done); + } + + /// Packed decode recurrence in place on the latest state, adopting an unfinished chunk's trial bank first. + pub fn decode(self: *const Kernels, stream: cuda.Stream, state: *State, run: Run) !void { + try checkRun(run); + try checkBanks(state, run.nv); + if (state.pending > 0) state.commit(); + var a: cuda.Args = .{}; + a.add(run.qkv); + a.add(int(run.ld_qkv)); + a.add(run.ba); + a.add(int(run.ld_ba)); + a.add(run.a_log); + a.add(run.dt_bias); + a.add(state.committed()); + a.add(run.y); + a.add(int(run.rows)); + a.add(int(run.nk)); + a.add(int(run.nv)); + a.add(run.scale); + try go(stream, self.decode_fn, .{ run.dv / 32, run.nv, 1 }, 128, &a); + } + + /// Appends run rows to the unfinished chunk and recomputes it into the other bank; a full chunk commits. + fn unfinished(self: *const Kernels, stream: cuda.Stream, state: *State, ws: Workspace, run: Run, from: usize, count: usize) !void { + const at = state.pending; + const qkv_cols = (2 * run.nk + run.nv) * head_dim; + const ba_cols = 2 * run.nv; + var a: cuda.Args = .{}; + a.add(run.qkv + from * run.ld_qkv * 2); + a.add(int(run.ld_qkv)); + a.add(run.ba + from * run.ld_ba * 2); + a.add(int(run.ld_ba)); + a.add(state.qkv_cache); + a.add(state.ba_cache); + a.add(int(at)); + a.add(int(qkv_cols)); + a.add(int(ba_cols)); + try go(stream, self.append_fn, .{ count, 1, 1 }, 256, &a); + const rows = at + count; + try self.chain(stream, ws, run, .{ + .qkv = state.qkv_cache, + .ld_qkv = qkv_cols, + .ba = state.ba_cache, + .ld_ba = ba_cols, + .rows = rows, + .emit_from = at, + .y = run.y + from * run.nv * run.dv * 2, + .state_in = state.committed(), + .state_out = state.other(), + }); + if (rows == chunk_rows) state.commit() else state.pending = rows; + } + + /// l2norm -> gate -> kkt -> wu -> h -> o over one segment. + fn chain(self: *const Kernels, stream: cuda.Stream, ws: Workspace, run: Run, seg: Segment) !void { + const nt = (seg.rows + chunk_rows - 1) / chunk_rows; + const rows = int(seg.rows); + const nk = int(run.nk); + const nv = int(run.nv); + { + var a: cuda.Args = .{}; + a.add(seg.qkv); + a.add(int(seg.ld_qkv)); + a.add(ws.qk); + a.add(rows); + a.add(nk); + a.add(l2norm_eps); + try go(stream, self.l2norm_fn, .{ (seg.rows * 2 * run.nk + 15) / 16, 1, 1 }, 256, &a); + } + { + var a: cuda.Args = .{}; + a.add(seg.ba); + a.add(int(seg.ld_ba)); + a.add(run.a_log); + a.add(run.dt_bias); + a.add(ws.g); + a.add(ws.gc); + a.add(ws.beta); + a.add(rows); + a.add(nv); + try go(stream, self.gate_fn, .{ nt, run.nv, 1 }, 64, &a); + } + { + var a: cuda.Args = .{}; + a.add(ws.qk); + a.add(ws.gc); + a.add(ws.beta); + a.add(ws.a); + a.add(rows); + a.add(nk); + a.add(nv); + try go(stream, self.kkt_fn, .{ nt, run.nv, 1 }, 32, &a); + } + { + var a: cuda.Args = .{}; + a.add(seg.qkv); + a.add(int(seg.ld_qkv)); + a.add(ws.qk); + a.add(ws.gc); + a.add(ws.beta); + a.add(ws.a); + a.add(ws.w); + a.add(ws.u); + a.add(rows); + a.add(nk); + a.add(nv); + try go(stream, self.wu_fn, .{ nt, run.nv, 1 }, 128, &a); + } + { + var a: cuda.Args = .{}; + a.add(ws.qk); + a.add(ws.w); + a.add(ws.u); + a.add(ws.gc); + a.add(seg.state_in); + a.add(seg.state_out); + a.add(ws.h); + a.add(ws.vn); + a.add(rows); + a.add(nk); + a.add(nv); + try go(stream, self.h_fn, .{ head_dim / 32, run.nv, 1 }, 128, &a); + } + { + var a: cuda.Args = .{}; + a.add(ws.qk); + a.add(ws.vn); + a.add(ws.h); + a.add(ws.gc); + a.add(seg.y); + a.add(rows); + a.add(int(seg.emit_from)); + a.add(nk); + a.add(nv); + a.add(run.scale); + try go(stream, self.o_fn, .{ head_dim / 64, nt, run.nv }, 128, &a); + } + } +}; diff --git a/zig/src/families/drama/backbone_kernels.zig b/zig/src/families/drama/backbone_kernels.zig new file mode 100644 index 00000000000..e1289fb68e9 --- /dev/null +++ b/zig/src/families/drama/backbone_kernels.zig @@ -0,0 +1,361 @@ +//! Drama backbone glue and GEMM kernels: the embedded images, or a kernel directory's for numerical-oracle tooling. +const std = @import("std"); +const cuda = @import("cuda"); +const backbone_gdn = @import("backbone_gdn.zig"); + +pub const glue_file = "drama_backbone.fatbin"; +pub const gemm_file = "drama_backbone_gemm.fatbin"; + +/// The bf16 product tilings: (rows a tile, 8-column tiles a warp) for up to 16, 32 and more rows. +const tilings = [_][2]usize{ .{ 1, 1 }, .{ 2, 2 }, .{ 4, 2 } }; +const gemm_symbols = [3][:0]const u8{ "drama_gemm_bf16_r1_n1_o0", "drama_gemm_bf16_r2_n2_o0", "drama_gemm_bf16_r4_n2_o0" }; +/// One row, fp32 out holding bf16-rounded values (the lm_head's bf16 logits read as float). +const head_symbol = "drama_gemv_bf16_r1_o2"; +/// One row through a staged weight path, bit-identical to the r1 tiling; needs k % gemv_chunk == 0. +const gemv_symbol = "drama_gemv_bf16_r1_o0"; +const gemv_chunk = 256; +/// Expert products: [mode][column tiles a warp - 1]; mode 1 scales by the routed weight. +const expert_symbols = [2][2][:0]const u8{ + .{ "drama_expert_fp8_n1_m0", "drama_expert_fp8_n2_m0" }, + .{ "drama_expert_fp8_n1_m1", "drama_expert_fp8_n2_m1" }, +}; +const warps = 4; + +fn readImage(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8) ![]align(16) u8 { + const path = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(path); + return std.Io.Dir.cwd().readFileAllocOptions(io, path, gpa, .limited(1 << 28), .@"16", null) catch |e| { + std.log.err("drama backbone: cannot read kernel image {s}: {s}", .{ path, @errorName(e) }); + return e; + }; +} + +fn loadImage(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, name: []const u8) !cuda.Module { + const image = try readImage(gpa, io, dir, name); + defer gpa.free(image); + return cuda.Module.load(d, image); +} + +fn go(s: cuda.Stream, f: cuda.Function, grid: [3]usize, block: u32, a: *cuda.Args) !void { + const g: cuda.Dim3 = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }; + try cuda.launch.launch(f, .{ .grid = g, .block = .{ .x = block } }, s, a); +} + +fn int(v: usize) i32 { + return @intCast(v); +} + +pub const Kernels = struct { + glue: cuda.Module, + gemm_mod: cuda.Module, + experts_mod: cuda.Module, + embed: cuda.embed_rows.EmbedRows, + router: cuda.grouped.Router, + semantic_mix_fn: cuda.Function, + add_norm_fn: cuda.Function, + gated_rms_fn: cuda.Function, + conv_fn: cuda.Function, + conv_prefill_fn: cuda.Function, + gdn: backbone_gdn.Kernels, + attn_prep_fn: cuda.Function, + attention_fn: cuda.Function, + topk_fn: cuda.Function, + act_quant_fn: cuda.Function, + silu_mul_fn: cuda.Function, + combine_fn: cuda.Function, + gemms: [3]cuda.Function, + head_fn: cuda.Function, + gemv_fn: cuda.Function, + experts: [2][2]cuda.Function, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, kernel_dir: []const u8) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var glue = if (kernel_dir.len == 0) try cuda.Module.load(d, cuda.kernels.drama_backbone) else try loadImage(gpa, io, d, kernel_dir, glue_file); + errdefer glue.unload(); + var gemm_mod = if (kernel_dir.len == 0) try cuda.Module.load(d, cuda.kernels.drama_backbone_gemm) else try loadImage(gpa, io, d, kernel_dir, gemm_file); + errdefer gemm_mod.unload(); + var experts_mod = try cuda.Module.load(d, cuda.kernels.experts); + errdefer experts_mod.unload(); + var embed = try cuda.embed_rows.EmbedRows.load(d); + errdefer embed.unload(); + var k: Kernels = .{ + .glue = glue, + .gemm_mod = gemm_mod, + .experts_mod = experts_mod, + .embed = embed, + .router = try cuda.grouped.Router.resolve(experts_mod), + .semantic_mix_fn = try glue.function("drama_semantic_mix"), + .add_norm_fn = try glue.function("drama_add_norm"), + .gated_rms_fn = try glue.function("drama_gated_rms_128"), + .conv_fn = try glue.function("drama_gdn_conv"), + .conv_prefill_fn = try glue.function("drama_gdn_conv_prefill"), + .gdn = try backbone_gdn.Kernels.init(&glue), + .attn_prep_fn = try glue.function("drama_attn_prep"), + .attention_fn = try glue.function("drama_attention"), + .topk_fn = try glue.function("drama_topk"), + .act_quant_fn = try glue.function("drama_act_quant"), + .silu_mul_fn = try glue.function("drama_silu_mul"), + .combine_fn = try glue.function("drama_moe_combine"), + .gemms = undefined, + .head_fn = undefined, + .gemv_fn = undefined, + .experts = undefined, + }; + for (gemm_symbols, 0..) |sym, v| k.gemms[v] = try gemm_mod.function(sym); + k.head_fn = try gemm_mod.function(head_symbol); + k.gemv_fn = try gemm_mod.function(gemv_symbol); + for (expert_symbols, 0..) |row, m| for (row, 0..) |sym, n| { + k.experts[m][n] = try gemm_mod.function(sym); + }; + return k; + } + + pub fn unload(k: *Kernels) void { + k.embed.unload(); + k.experts_mod.unload(); + k.gemm_mod.unload(); + k.glue.unload(); + k.* = undefined; + } + + fn product(f: cuda.Function, s: cuda.Stream, rt: usize, nt: usize, x: u64, ldx: usize, m: usize, w: u64, n: usize, kdim: usize, y: u64, ldy: usize) !void { + if (m == 0) return; + if (kdim % 32 != 0 or ldx % 8 != 0 or x % 16 != 0 or w % 16 != 0) return error.DramaGemmShape; + var a: cuda.Args = .{}; + a.add(x); + a.add(int(ldx)); + a.add(int(m)); + a.add(w); + a.add(int(n)); + a.add(int(kdim)); + a.add(y); + a.add(int(ldy)); + const cols = 8 * nt * warps; + try go(s, f, .{ (n + cols - 1) / cols, (m + 16 * rt - 1) / (16 * rt), 1 }, 32 * warps, &a); + } + + /// Y[m, n] = bf16(X[m, :] . W[n, :]) (fp32 accumulate). W has ceil8(n) rows; k % 32 == 0; rows 16-byte aligned. + pub fn gemm(k: *const Kernels, s: cuda.Stream, x: u64, ldx: usize, m: usize, w: u64, n: usize, kdim: usize, y: u64, ldy: usize) !void { + if (m == 1 and kdim % gemv_chunk == 0) return gemv(k.gemv_fn, s, x, w, n, kdim, y); + const v: usize = if (m <= 16) 0 else if (m <= 32) 1 else 2; + try product(k.gemms[v], s, tilings[v][0], tilings[v][1], x, ldx, m, w, n, kdim, y, ldy); + } + + fn gemv(f: cuda.Function, s: cuda.Stream, x: u64, w: u64, n: usize, kdim: usize, y: u64) !void { + if (kdim % gemv_chunk != 0 or x % 16 != 0 or w % 16 != 0) return error.DramaGemmShape; + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(int(n)); + a.add(int(kdim)); + a.add(y); + try go(s, f, .{ (n + 7) / 8, 1, 1 }, 32, &a); + } + + /// y[n] = float(bf16(x . W[n, :])) for one row x. + pub fn head(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, n: usize, kdim: usize, y: u64) !void { + try gemv(k.head_fn, s, x, w, n, kdim, y); + } + + pub const ExpertCall = struct { + a: u64, // e4m3 rows of kdim bytes + a_div: usize, // pair p reads row p / a_div + a_scales: u64, // f32 [rows][kdim / 128] + w: u64, // e4m3 [experts][n][kdim] + w_scales: u64, // f32 [experts][n / 128][kdim / 128] + n: usize, + kdim: usize, + max_items: usize, + routed: ?u64, // f32 [pairs] routed weights: scale before the bf16 store + y: u64, // bf16 [pairs][n] + }; + + pub fn expert(k: *const Kernels, s: cuda.Stream, plan: cuda.grouped.Plan, pairs: usize, c: ExpertCall) !void { + if (c.n % 128 != 0 or c.kdim % 128 != 0) return error.DramaGemmShape; + const nt: usize = if (pairs > 64) 2 else 1; + var a: cuda.Args = .{}; + a.add(c.a); + a.add(int(c.a_div)); + a.add(c.a_scales); + a.add(c.w); + a.add(c.w_scales); + a.add(int(c.n)); + a.add(int(c.kdim)); + a.add(plan.items); + a.add(plan.counts); + a.add(plan.members); + a.add(c.routed orelse 0); + a.add(c.y); + const cols = 8 * nt * warps; + const f = k.experts[@intFromBool(c.routed != null)][nt - 1]; + try go(s, f, .{ c.max_items, c.n / cols, 1 }, 32 * warps, &a); + } + + pub fn semanticMix(k: *const Kernels, s: cuda.Stream, ids: u64, out: u64, extra: u64, rows: usize, width: usize, lo: u32, hi: u32) !void { + var a: cuda.Args = .{}; + a.add(ids); + a.add(out); + a.add(extra); + a.add(int(width)); + a.add(@as(i32, @intCast(lo))); + a.add(@as(i32, @intCast(hi))); + try go(s, k.semantic_mix_fn, .{ rows, 1, 1 }, 256, &a); + } + + /// res = x (first) or bf16(x + res); y = bf16(norm(x + res) * (1 + w)), with q / scales also y's FP8 groups. + pub fn addNorm(k: *const Kernels, s: cuda.Stream, x: u64, res: u64, w: u64, y: u64, q: ?u64, scales: ?u64, rows: usize, width: usize, eps: f32, first: bool) !void { + if (width % 256 != 0 or (x | res | w | y | (q orelse 0)) % 16 != 0) return error.DramaRowShape; + var a: cuda.Args = .{}; + a.add(x); + a.add(res); + a.add(w); + a.add(y); + a.add(q orelse 0); + a.add(scales orelse 0); + a.add(int(width)); + a.add(eps); + a.add(@as(i32, @intFromBool(first))); + try go(s, k.add_norm_fn, .{ rows, 1, 1 }, 256, &a); + } + + /// Drama-only 32 x 128 gated RMS; fixed full-extend reduction, independent of token count. + pub fn gatedRms(k: *const Kernels, s: cuda.Stream, y: u64, y_ld: usize, z: u64, z_ld: usize, w: u64, out: u64, rows: usize, eps: f32) !void { + if (rows == 0) return; + var a: cuda.Args = .{}; + a.add(y); + a.add(@as(i64, @intCast(y_ld))); + a.add(z); + a.add(@as(i64, @intCast(z_ld))); + a.add(w); + a.add(out); + a.add(eps); + const threads = cuda.launch.rowThreads(rows, 256, 32); + try go(s, k.gated_rms_fn, .{ rows, 32 / (threads / 16), 1 }, threads, &a); + } + + pub fn conv(k: *const Kernels, s: cuda.Stream, in: u64, ld_in: usize, w: u64, state: u64, out: u64, rows: usize, channels: usize) !void { + try convUsing(k.conv_fn, s, in, ld_in, w, state, out, rows, channels); + } + + pub fn convPrefill(k: *const Kernels, s: cuda.Stream, in: u64, ld_in: usize, w: u64, state: u64, out: u64, rows: usize, channels: usize) !void { + try convUsing(k.conv_prefill_fn, s, in, ld_in, w, state, out, rows, channels); + } + + fn convUsing(kernel: cuda.Function, s: cuda.Stream, in: u64, ld_in: usize, w: u64, state: u64, out: u64, rows: usize, channels: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(int(ld_in)); + a.add(w); + a.add(state); + a.add(out); + a.add(int(rows)); + a.add(int(channels)); + try go(s, kernel, .{ (channels + 255) / 256, 1, 1 }, 256, &a); + } + + pub const Attn = struct { + qkv: u64, + ld_qkv: usize, + q_norm: u64, + k_norm: u64, + inv_freq: u64, + q: u64, + kc: u64, + vc: u64, + out: u64, + pos0: usize, + rows: usize, + heads: usize, + kv_heads: usize, + eps: f32, + scale: f32, + }; + + /// q/k norm + RoPE + cache append, then causal attention with the output gate; one row takes a single launch. + pub fn attention(k: *const Kernels, s: cuda.Stream, t: Attn) !void { + const one = t.rows == 1; + if (!one) { + var a: cuda.Args = .{}; + a.add(t.qkv); + a.add(int(t.ld_qkv)); + a.add(t.q_norm); + a.add(t.k_norm); + a.add(t.inv_freq); + a.add(t.q); + a.add(t.kc); + a.add(t.vc); + a.add(int(t.pos0)); + a.add(int(t.heads)); + a.add(int(t.kv_heads)); + a.add(t.eps); + try go(s, k.attn_prep_fn, .{ t.rows, t.heads + t.kv_heads, 1 }, 32, &a); + } + var b: cuda.Args = .{}; + b.add(t.q); + b.add(t.kc); + b.add(t.vc); + b.add(t.qkv); + b.add(int(t.ld_qkv)); + b.add(t.out); + b.add(int(t.pos0)); + b.add(int(t.heads)); + b.add(int(t.kv_heads)); + b.add(t.scale); + b.add(if (one) t.q_norm else 0); + b.add(if (one) t.k_norm else 0); + b.add(t.inv_freq); + b.add(t.eps); + try go(s, k.attention_fn, .{ t.rows, t.heads, 1 }, 256, &b); + } + + pub fn topk(k: *const Kernels, s: cuda.Stream, logits: u64, ld: usize, ids: u64, wts: u64, rows: usize, top: usize) !void { + if (top == 0 or top > 8) return error.DramaRowShape; // drama_topk keeps at most 8 picks in shared memory + var a: cuda.Args = .{}; + a.add(logits); + a.add(int(ld)); + a.add(ids); + a.add(wts); + a.add(int(top)); + try go(s, k.topk_fn, .{ rows, 1, 1 }, 256, &a); + } + + pub fn actQuant(k: *const Kernels, s: cuda.Stream, x: u64, ld_x: usize, q: u64, scales: u64, rows: usize, kdim: usize) !void { + if (kdim % 512 != 0) return error.DramaRowShape; + var a: cuda.Args = .{}; + a.add(x); + a.add(int(ld_x)); + a.add(q); + a.add(scales); + a.add(int(kdim)); + try go(s, k.act_quant_fn, .{ rows, kdim / 512, 1 }, 128, &a); + } + + /// One launch: the routed rows of gu FP8-quantized into hq / hs, the shared expert's rows of shared_gu stored to h. + pub fn siluMul(k: *const Kernels, s: cuda.Stream, gu: u64, ld_gu: usize, hq: u64, hs: u64, routed: usize, shared_gu: u64, ld_shared: usize, h: u64, shared: usize, inner: usize) !void { + if (inner % 512 != 0) return error.DramaRowShape; + var a: cuda.Args = .{}; + a.add(gu); + a.add(int(ld_gu)); + a.add(int(routed)); + a.add(hq); + a.add(hs); + a.add(shared_gu); + a.add(int(ld_shared)); + a.add(h); + a.add(int(inner)); + try go(s, k.silu_mul_fn, .{ routed + shared, inner / 512, 1 }, 128, &a); + } + + pub fn combine(k: *const Kernels, s: cuda.Stream, down: u64, top: usize, x: u64, wg: u64, shared: u64, out: u64, rows: usize, width: usize) !void { + if (width % 8 != 0 or (down | shared | out) % 16 != 0) return error.DramaRowShape; + var a: cuda.Args = .{}; + a.add(down); + a.add(int(top)); + a.add(x); + a.add(wg); + a.add(shared); + a.add(out); + a.add(int(width)); + try go(s, k.combine_fn, .{ rows, 1, 1 }, 256, &a); + } +}; diff --git a/zig/src/families/drama/backbone_weights.zig b/zig/src/families/drama/backbone_weights.zig new file mode 100644 index 00000000000..792ba15a893 --- /dev/null +++ b/zig/src/families/drama/backbone_weights.zig @@ -0,0 +1,423 @@ +//! Drama backbone checkpoint tensors on the GPU as stored; fused projections concatenate rows, none is requantized. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("backbone_config.zig"); + +const Io = std.Io; + +pub const prefix = "model.language_model."; +pub const head_name = "lm_head.weight"; + +/// Rows of the GDN input projection: in_proj_qkv (8192) | in_proj_z (4096) | in_proj_b (32) | in_proj_a (32). +pub const gdn_in_rows = cfg.conv_dim + cfg.value_dim + 2 * cfg.linear_value_heads; +pub const gdn_z_col = cfg.conv_dim; +pub const gdn_b_col = cfg.conv_dim + cfg.value_dim; +/// Rows of the attention input projection: q_proj (16 x [q 256 | gate 256]) | k_proj (512) | v_proj (512). +pub const attn_in_rows = 2 * cfg.query_heads * cfg.head_dim + 2 * cfg.kv_heads * cfg.head_dim; +/// Rows of the MoE input projection: shared gate_proj (512) | shared up_proj (512) | router gate (256). +pub const moe_in_rows = 2 * cfg.shared_inner + cfg.experts; +pub const router_col = 2 * cfg.shared_inner; +/// Semantic head rows: EOS, the 4096-code band, zero rows to a multiple of 8. +pub const head_cols = 1 + 4096; +pub const head_rows = (head_cols + 7) / 8 * 8; +/// One expert's gate | up rows and their scale blocks. +pub const gu_rows = 2 * cfg.expert_inner; +pub const gu_scales = (gu_rows / cfg.block) * (cfg.hidden / cfg.block); +pub const dn_scales = (cfg.hidden / cfg.block) * (cfg.expert_inner / cfg.block); + +pub const Layer = struct { + ln1: u64 = 0, // bf16 [hidden] input_layernorm (zero-centered) + ln2: u64 = 0, // bf16 [hidden] post_attention_layernorm (zero-centered) + // Gated DeltaNet + gdn_in: u64 = 0, // bf16 [gdn_in_rows][hidden] + conv: u64 = 0, // bf16 [conv_dim][4] + a_log: u64 = 0, // f32 [32], widened from the stored bf16 + dt_bias: u64 = 0, // f32 [32], widened from the stored bf16 + gnorm: u64 = 0, // bf16 [128] RMSNormGated weight (plain, not zero-centered) + gdn_out: u64 = 0, // bf16 [hidden][value_dim] + // full attention + attn_in: u64 = 0, // bf16 [attn_in_rows][hidden] + q_norm: u64 = 0, // bf16 [256] (zero-centered) + k_norm: u64 = 0, // bf16 [256] (zero-centered) + attn_out: u64 = 0, // bf16 [hidden][query_heads * head_dim] + // MoE + moe_in: u64 = 0, // bf16 [moe_in_rows][hidden] + shared_down: u64 = 0, // bf16 [hidden][shared_inner] + shared_gate: u64 = 0, // bf16 [hidden] + gu: u64 = 0, // e4m3 [experts][gu_rows][hidden] + gu_s: u64 = 0, // f32 [experts][gu_rows / 128][hidden / 128] + dn: u64 = 0, // e4m3 [experts][hidden][expert_inner] + dn_s: u64 = 0, // f32 [experts][hidden / 128][expert_inner / 128] +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + embed: u64 = 0, // bf16 [vocab][hidden] + final_norm: u64 = 0, // bf16 [hidden] (zero-centered) + head: u64 = 0, // bf16 [head_rows][hidden] + inv_freq: u64 = 0, // f32 [rotary_dim / 2] + layers: [cfg.layers]Layer = @splat(.{}), + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.* = undefined; + } + + fn alloc(w: *Weights, d: *const cuda.Driver, bytes: usize) !u64 { + try w.buffers.ensureUnusedCapacity(w.gpa, 1); + const b = try cuda.DeviceBuffer.alloc(d, bytes); + w.buffers.appendAssumeCapacity(b); + w.bytes += bytes; + return b.ptr; + } +}; + +const DType = enum { bf16, f32, f8_e4m3 }; + +fn parseDType(s: []const u8) ?DType { + if (std.mem.eql(u8, s, "BF16")) return .bf16; + if (std.mem.eql(u8, s, "F32")) return .f32; + if (std.mem.eql(u8, s, "F8_E4M3")) return .f8_e4m3; + return null; +} + +fn size(t: DType) usize { + return switch (t) { + .bf16 => 2, + .f32 => 4, + .f8_e4m3 => 1, + }; +} + +const Entry = struct { shard: usize, dtype: ?DType, rank: usize, shape: [3]usize, begin: usize, end: usize }; + +const Shard = struct { file: Io.File, map: Io.File.MemoryMap, data: usize }; + +/// The checkpoint's shards mapped read-only, every header entry indexed by name. +const Source = struct { + gpa: std.mem.Allocator, + io: Io, + arena: std.heap.ArenaAllocator, + shards: std.ArrayList(Shard) = .empty, + names: std.StringHashMapUnmanaged(Entry) = .empty, + backbone: usize = 0, // entries under `prefix` + used: usize = 0, // of those, consumed + + fn open(gpa: std.mem.Allocator, io: Io, dir: []const u8) !Source { + var s: Source = .{ .gpa = gpa, .io = io, .arena = .init(gpa) }; + errdefer s.close(); + const a = s.arena.allocator(); + const index = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + const text = try Io.Dir.cwd().readFileAlloc(io, index, a, .limited(1 << 26)); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}); + if (doc != .object) return error.BadDramaCheckpoint; + const map = doc.object.get("weight_map") orelse return error.BadDramaCheckpoint; + if (map != .object) return error.BadDramaCheckpoint; + var files: std.StringArrayHashMapUnmanaged(void) = .empty; + var it = map.object.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .string) return error.BadDramaCheckpoint; + try files.put(a, e.value_ptr.string, {}); + } + for (files.keys(), 0..) |name, i| { + const path = try std.fs.path.join(a, &.{ dir, name }); + try s.mapShard(path, i); + } + // every name the index lists must be in its shard's header + it = map.object.iterator(); + while (it.next()) |e| { + const got = s.names.get(e.key_ptr.*) orelse return error.BadDramaCheckpoint; + if (!std.mem.eql(u8, files.keys()[got.shard], e.value_ptr.string)) return error.BadDramaCheckpoint; + } + return s; + } + + fn mapShard(s: *Source, path: []const u8, index: usize) !void { + const a = s.arena.allocator(); + // the file and its map belong to `shards` once appended; the errdefers cover only the steps before + const sh = blk: { + var file = try Io.Dir.cwd().openFile(s.io, path, .{}); + errdefer file.close(s.io); + const len: usize = @intCast(try file.length(s.io)); + if (len < 8) return error.BadDramaCheckpoint; + var map = try Io.File.MemoryMap.create(s.io, file, .{ .len = len, .protection = .{ .read = true, .write = false }, .populate = false }); + errdefer map.destroy(s.io); + const header_len: usize = @intCast(std.mem.readInt(u64, map.memory[0..8], .little)); + if (header_len > len - 8) return error.BadDramaCheckpoint; + try s.shards.append(s.gpa, .{ .file = file, .map = map, .data = 8 + header_len }); + break :blk s.shards.items[s.shards.items.len - 1]; + }; + const data_len = sh.map.memory.len - sh.data; + const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, sh.map.memory[8..sh.data], .{ .allocate = .alloc_always }); + if (doc != .object) return error.BadDramaCheckpoint; + var it = doc.object.iterator(); + while (it.next()) |kv| { + if (std.mem.eql(u8, kv.key_ptr.*, "__metadata__")) continue; + const o = if (kv.value_ptr.* == .object) kv.value_ptr.object else return error.BadDramaCheckpoint; + const dt = o.get("dtype") orelse return error.BadDramaCheckpoint; + const shape = o.get("shape") orelse return error.BadDramaCheckpoint; + const offs = o.get("data_offsets") orelse return error.BadDramaCheckpoint; + if (dt != .string or shape != .array or offs != .array or offs.array.items.len != 2) return error.BadDramaCheckpoint; + var e: Entry = .{ .shard = index, .dtype = parseDType(dt.string), .rank = shape.array.items.len, .shape = @splat(1), .begin = 0, .end = 0 }; + if (e.rank > 3) e.dtype = null; // not a backbone layout; refused if anything asks for it + for (shape.array.items, 0..) |d, i| { + if (d != .integer or d.integer < 0) return error.BadDramaCheckpoint; + if (i < 3) e.shape[i] = @intCast(d.integer); + } + for (offs.array.items, 0..) |d, i| { + if (d != .integer or d.integer < 0) return error.BadDramaCheckpoint; + if (i == 0) e.begin = @intCast(d.integer) else e.end = @intCast(d.integer); + } + if (e.end < e.begin or e.end > data_len) return error.BadDramaCheckpoint; + if (std.mem.startsWith(u8, kv.key_ptr.*, prefix)) s.backbone += 1; + const got = try s.names.getOrPut(s.gpa, kv.key_ptr.*); + if (got.found_existing) return error.BadDramaCheckpoint; + got.value_ptr.* = e; + } + } + + fn close(s: *Source) void { + for (s.shards.items) |*sh| { + sh.map.destroy(s.io); + sh.file.close(s.io); + } + s.shards.deinit(s.gpa); + s.names.deinit(s.gpa); + s.arena.deinit(); + s.* = undefined; + } + + /// The bytes of `name`, refused unless its dtype and shape are exactly these. + fn get(s: *Source, name: []const u8, dtype: DType, shape: []const usize) ![]const u8 { + const e = s.names.get(name) orelse { + std.log.err("drama backbone: checkpoint has no {s}", .{name}); + return error.MissingDramaTensor; + }; + var ok = e.dtype != null and e.dtype.? == dtype and e.rank == shape.len; + var n: usize = size(dtype); + for (shape, 0..) |d, i| { + ok = ok and e.shape[i] == d; + n *= d; + } + if (!ok or e.end - e.begin != n) { + std.log.err("drama backbone: {s} is not {s} {any}", .{ name, @tagName(dtype), shape }); + return error.UnexpectedDramaTensor; + } + if (std.mem.startsWith(u8, name, prefix)) s.used += 1; + const sh = s.shards.items[e.shard]; + return sh.map.memory[sh.data + e.begin .. sh.data + e.end]; + } +}; + +/// Host-to-device copies through two pinned slots on one stream: a slot is refilled only after its copies land. +const Stager = struct { + const slot_bytes = 64 << 20; + + d: *const cuda.Driver, + stream: cuda.Stream, + slots: [2]cuda.HostBuffer, + events: [2]cuda.Event, + pending: [2]bool = .{ false, false }, + cur: usize = 0, + used: usize = 0, + + fn init(d: *const cuda.Driver, stream: cuda.Stream) !Stager { + var a = try cuda.HostBuffer.alloc(d, slot_bytes); + errdefer a.free(); + var b = try cuda.HostBuffer.alloc(d, slot_bytes); + errdefer b.free(); + var ea = try cuda.Event.init(d, false); + errdefer ea.deinit(); + const eb = try cuda.Event.init(d, false); + return .{ .d = d, .stream = stream, .slots = .{ a, b }, .events = .{ ea, eb } }; + } + + fn deinit(st: *Stager) void { + st.stream.synchronize() catch {}; + for (&st.slots) |*s| s.free(); + for (&st.events) |*e| e.deinit(); + st.* = undefined; + } + + fn swap(st: *Stager) !void { + try st.events[st.cur].record(st.stream); + st.pending[st.cur] = true; + st.cur ^= 1; + if (st.pending[st.cur]) try st.events[st.cur].synchronize(); + st.pending[st.cur] = false; + st.used = 0; + } + + fn put(st: *Stager, dst: u64, bytes: []const u8) !void { + var off: usize = 0; + while (off < bytes.len) { + if (st.used == slot_bytes) try st.swap(); + const n = @min(bytes.len - off, slot_bytes - st.used); + const host = st.slots[st.cur].bytes[st.used..][0..n]; + @memcpy(host, bytes[off..][0..n]); + try st.d.check(st.d.api.cuMemcpyHtoDAsync_v2(dst + off, host.ptr, n, st.stream.handle), "cuMemcpyHtoDAsync"); + st.used += n; + off += n; + } + } + + fn zero(st: *Stager, dst: u64, n: usize) !void { + try st.d.check(st.d.api.cuMemsetD8Async(dst, 0, n, st.stream.handle), "cuMemsetD8Async"); + } + + fn finish(st: *Stager) !void { + try st.stream.synchronize(); + st.pending = .{ false, false }; + st.used = 0; + } +}; + +fn widenBf16(out: []f32, bytes: []const u8) void { + for (out, 0..) |*o, i| o.* = @bitCast(@as(u32, std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)) << 16); +} + +const Loader = struct { + src: *Source, + st: *Stager, + w: *Weights, + d: *const cuda.Driver, + name_buf: [192]u8 = undefined, + + fn name(L: *Loader, comptime fmt: []const u8, args: anytype) ![]const u8 { + return std.fmt.bufPrint(&L.name_buf, fmt, args); + } + + /// A fresh device tensor holding `name` as stored. + fn raw(L: *Loader, n: []const u8, dtype: DType, shape: []const usize) !u64 { + const bytes = try L.src.get(n, dtype, shape); + const p = try L.w.alloc(L.d, bytes.len); + try L.st.put(p, bytes); + return p; + } + + /// `name` as stored at `dst` (part of a fused tensor). + fn into(L: *Loader, dst: u64, n: []const u8, dtype: DType, shape: []const usize) !void { + try L.st.put(dst, try L.src.get(n, dtype, shape)); + } + + fn layerRaw(L: *Loader, i: usize, comptime suffix: []const u8, dtype: DType, shape: []const usize) !u64 { + return L.raw(try L.name(prefix ++ "layers.{d}." ++ suffix, .{i}), dtype, shape); + } + + fn layerInto(L: *Loader, dst: u64, i: usize, comptime suffix: []const u8, dtype: DType, shape: []const usize) !void { + try L.into(dst, try L.name(prefix ++ "layers.{d}." ++ suffix, .{i}), dtype, shape); + } + + fn widened(L: *Loader, i: usize, comptime suffix: []const u8) !u64 { + const n = cfg.linear_value_heads; + const bytes = try L.src.get(try L.name(prefix ++ "layers.{d}." ++ suffix, .{i}), .bf16, &.{n}); + var host: [n]f32 = undefined; + widenBf16(&host, bytes); + const p = try L.w.alloc(L.d, n * 4); + try L.st.put(p, std.mem.sliceAsBytes(&host)); + return p; + } +}; + +const H = cfg.hidden; + +fn loadLinear(L: *Loader, i: usize, l: *Layer) !void { + const row = H * 2; + l.gdn_in = try L.w.alloc(L.d, gdn_in_rows * row); + try L.layerInto(l.gdn_in, i, "linear_attn.in_proj_qkv.weight", .bf16, &.{ cfg.conv_dim, H }); + try L.layerInto(l.gdn_in + gdn_z_col * row, i, "linear_attn.in_proj_z.weight", .bf16, &.{ cfg.value_dim, H }); + try L.layerInto(l.gdn_in + gdn_b_col * row, i, "linear_attn.in_proj_b.weight", .bf16, &.{ cfg.linear_value_heads, H }); + try L.layerInto(l.gdn_in + (gdn_b_col + cfg.linear_value_heads) * row, i, "linear_attn.in_proj_a.weight", .bf16, &.{ cfg.linear_value_heads, H }); + l.conv = try L.layerRaw(i, "linear_attn.conv1d.weight", .bf16, &.{ cfg.conv_dim, 1, cfg.conv_taps }); + l.a_log = try L.widened(i, "linear_attn.A_log"); + l.dt_bias = try L.widened(i, "linear_attn.dt_bias"); + l.gnorm = try L.layerRaw(i, "linear_attn.norm.weight", .bf16, &.{cfg.linear_dim}); + l.gdn_out = try L.layerRaw(i, "linear_attn.out_proj.weight", .bf16, &.{ H, cfg.value_dim }); +} + +fn loadFull(L: *Loader, i: usize, l: *Layer) !void { + const row = H * 2; + const q_rows = 2 * cfg.query_heads * cfg.head_dim; + const kv_rows = cfg.kv_heads * cfg.head_dim; + l.attn_in = try L.w.alloc(L.d, attn_in_rows * row); + try L.layerInto(l.attn_in, i, "self_attn.q_proj.weight", .bf16, &.{ q_rows, H }); + try L.layerInto(l.attn_in + q_rows * row, i, "self_attn.k_proj.weight", .bf16, &.{ kv_rows, H }); + try L.layerInto(l.attn_in + (q_rows + kv_rows) * row, i, "self_attn.v_proj.weight", .bf16, &.{ kv_rows, H }); + l.q_norm = try L.layerRaw(i, "self_attn.q_norm.weight", .bf16, &.{cfg.head_dim}); + l.k_norm = try L.layerRaw(i, "self_attn.k_norm.weight", .bf16, &.{cfg.head_dim}); + l.attn_out = try L.layerRaw(i, "self_attn.o_proj.weight", .bf16, &.{ H, cfg.query_heads * cfg.head_dim }); +} + +fn loadMoe(L: *Loader, i: usize, l: *Layer) !void { + const row = H * 2; + const I = cfg.expert_inner; + l.moe_in = try L.w.alloc(L.d, moe_in_rows * row); + try L.layerInto(l.moe_in, i, "mlp.shared_expert.gate_proj.weight", .bf16, &.{ cfg.shared_inner, H }); + try L.layerInto(l.moe_in + cfg.shared_inner * row, i, "mlp.shared_expert.up_proj.weight", .bf16, &.{ cfg.shared_inner, H }); + try L.layerInto(l.moe_in + router_col * row, i, "mlp.gate.weight", .bf16, &.{ cfg.experts, H }); + l.shared_down = try L.layerRaw(i, "mlp.shared_expert.down_proj.weight", .bf16, &.{ H, cfg.shared_inner }); + l.shared_gate = try L.layerRaw(i, "mlp.shared_expert_gate.weight", .bf16, &.{ 1, H }); + const E = cfg.experts; + l.gu = try L.w.alloc(L.d, E * gu_rows * H); + l.gu_s = try L.w.alloc(L.d, E * gu_scales * 4); + l.dn = try L.w.alloc(L.d, E * H * I); + l.dn_s = try L.w.alloc(L.d, E * dn_scales * 4); + const gs = &[_]usize{ I / cfg.block, H / cfg.block }; + const ds = &[_]usize{ H / cfg.block, I / cfg.block }; + for (0..E) |e| { + const gu = l.gu + e * gu_rows * H; + const gu_s = l.gu_s + e * gu_scales * 4; + try L.into(gu, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.gate_proj.weight", .{ i, e }), .f8_e4m3, &.{ I, H }); + try L.into(gu + I * H, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.up_proj.weight", .{ i, e }), .f8_e4m3, &.{ I, H }); + try L.into(gu_s, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.gate_proj.weight_scale_inv", .{ i, e }), .f32, gs); + try L.into(gu_s + gu_scales * 2, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.up_proj.weight_scale_inv", .{ i, e }), .f32, gs); + try L.into(l.dn + e * H * I, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.down_proj.weight", .{ i, e }), .f8_e4m3, &.{ H, I }); + try L.into(l.dn_s + e * dn_scales * 4, try L.name(prefix ++ "layers.{d}.mlp.experts.{d}.down_proj.weight_scale_inv", .{ i, e }), .f32, ds); + } +} + +/// Uploads the backbone tensors and lm_head's semantic rows; refuses missing, mis-shaped or unconsumed tensors. +pub fn load(gpa: std.mem.Allocator, io: Io, d: *const cuda.Driver, stream: cuda.Stream, dir: []const u8, c: cfg.Config) !Weights { + var src = try Source.open(gpa, io, dir); + defer src.close(); + var st = try Stager.init(d, stream); + defer st.deinit(); + var w: Weights = .{ .gpa = gpa }; + errdefer { + stream.synchronize() catch {}; + w.deinit(); + } + var L: Loader = .{ .src = &src, .st = &st, .w = &w, .d = d }; + w.embed = try L.raw(prefix ++ "embed_tokens.weight", .bf16, &.{ cfg.vocab, H }); + w.final_norm = try L.raw(prefix ++ "norm.weight", .bf16, &.{H}); + for (&w.layers, 0..) |*l, i| { + l.ln1 = try L.layerRaw(i, "input_layernorm.weight", .bf16, &.{H}); + l.ln2 = try L.layerRaw(i, "post_attention_layernorm.weight", .bf16, &.{H}); + if (cfg.linear(i)) try loadLinear(&L, i, l) else try loadFull(&L, i, l); + try loadMoe(&L, i, l); + } + // lm_head: only the rows the semantic logits read (EOS, then semantic_start..semantic_end), zero padded. + const head = try src.get(head_name, .bf16, &.{ cfg.vocab, H }); + const row = H * 2; + w.head = try w.alloc(d, head_rows * row); + try st.zero(w.head, head_rows * row); + try st.put(w.head, head[@as(usize, c.eos) * row ..][0..row]); + try st.put(w.head + row, head[@as(usize, c.semantic_start) * row ..][0 .. (head_cols - 1) * row]); + // RoPE inverse frequencies as SGLang computes them in fp32: 1 / theta^(2i / rotary_dim). + var inv: [cfg.rotary_dim / 2]f32 = undefined; + for (&inv, 0..) |*f, i| { + const e: f32 = @as(f32, @floatFromInt(2 * i)) / @as(f32, cfg.rotary_dim); + f.* = 1.0 / std.math.pow(f32, @floatCast(cfg.theta), e); + } + w.inv_freq = try w.alloc(d, inv.len * 4); + try st.put(w.inv_freq, std.mem.sliceAsBytes(&inv)); + if (src.used != src.backbone) { + std.log.err("drama backbone: {d} of {d} {s}* tensors left unused", .{ src.backbone - src.used, src.backbone, prefix }); + return error.UnusedDramaTensors; + } + try st.finish(); + return w; +} diff --git a/zig/src/families/drama/codec.zig b/zig/src/families/drama/codec.zig new file mode 100644 index 00000000000..a9efce0f142 --- /dev/null +++ b/zig/src/families/drama/codec.zig @@ -0,0 +1,328 @@ +//! Drama 3 codec on CUDA: ten codebooks a frame to 44.1 kHz mono PCM; decode is one pass, begin/advance chunked. + +const std = @import("std"); +const cuda = @import("cuda"); +const pth = @import("codec_pth.zig"); +const kern = @import("codec_kernels.zig"); +const load = @import("codec_load.zig"); + +const Allocator = std.mem.Allocator; + +pub const Options = struct { max_frames: usize = 1024 }; + +const latent = load.latent; +const codebooks = load.codebooks; +const layers = load.layers; +const heads = load.heads; +const head_dim = load.head_dim; +const window = load.window; +const ffn = load.ffn; +const rms_eps = load.rms_eps; +const layer_norm_eps = load.layer_norm_eps; +const convnext_hidden = load.convnext_hidden; +const upsample_stages = load.upsample_stages; +const decoder_dim = load.decoder_dim; +const rates = load.rates; +const dilations = load.dilations; +const latent_rows_per_frame = load.latent_rows_per_frame; +const samples_per_frame = load.samples_per_frame; +const out_channels = load.out_channels; + +/// FP16 elements a frame each of the three activation buffers holds: the widest tensor of the decode. +const act_halves_per_frame = blk: { + var most: usize = latent_rows_per_frame * convnext_hidden; // ConvNeXt hidden at 4T rows + var rows: usize = latent_rows_per_frame; + var ch: usize = decoder_dim; + most = @max(most, rows * ch); + for (rates) |r| { + rows *= r; + ch /= 2; + most = @max(most, rows * ch); + } + break :blk most; +}; + +/// One causal consumer's kept rows: the last `rows` rows of `width` FP16 channels, right-aligned at `offset` in carry. +const Carry = struct { offset: usize, rows: usize, width: usize }; + +/// Every consumer that reads rows before a chunk's first: depthwise convs, conv0, transposed convs, conv7s, output. +const Carries = struct { + dwconv: [upsample_stages]Carry, + conv0: Carry, + blocks: [rates.len]struct { transconv: Carry, units: [dilations.len]Carry }, + out: Carry, + bytes: usize, +}; + +const carries: Carries = blk: { + var c: Carries = undefined; + var at: usize = 0; + for (&c.dwconv) |*d| d.* = keep(&at, 6, latent); + c.conv0 = keep(&at, 6, latent); + var ch: usize = decoder_dim; + for (&c.blocks) |*b| { + b.transconv = keep(&at, 1, ch); + ch /= 2; + for (&b.units, dilations) |*u, d| u.* = keep(&at, 6 * d, ch); + } + c.out = keep(&at, 6, out_channels); + c.bytes = at; + break :blk c; +}; + +fn keep(at: *usize, rows: usize, width: usize) Carry { + defer at.* += rows * width * 2; + return .{ .offset = at.*, .rows = rows, .width = width }; +} + +comptime { + std.debug.assert(samples_per_frame == 2048); + std.debug.assert(out_channels == 96); + // the transformer's scratch (2T rows of 1024 in one buffer, 9T in another) fits the same buffers + std.debug.assert(act_halves_per_frame >= 9 * latent); + std.debug.assert(carries.bytes == 268416); +} + +pub const Model = struct { + sample_rate: u32 = 44100, + frame_length: usize = samples_per_frame, + num_codebooks: usize = codebooks, + max_frames: usize, + ctx: *cuda.Context, + kernels: kern.Kernels, + weights: cuda.DeviceBuffer, + w: load.Weights, + acts: [3]cuda.DeviceBuffer, + codes_dev: cuda.DeviceBuffer, + audio_dev: cuda.DeviceBuffer, + codes_host: cuda.HostBuffer, + audio_host: cuda.HostBuffer, + /// Each transformer layer's qkv rows [max_frames][3 * latent]: attention reads earlier chunks' keys here. + kv: cuda.DeviceBuffer, + /// The rows each causal consumer reads before a chunk (`carries`). + carry: cuda.DeviceBuffer, + /// Frames of the utterance `advance` has decoded. + decoded: usize = 0, + + pub fn init(gpa: Allocator, io: std.Io, ctx: *cuda.Context, checkpoint_dir: []const u8, kernel_dir: []const u8, options: Options) !Model { + if (options.max_frames == 0) return error.Invalid; + try ctx.makeCurrent(); + const d = ctx.d; + var kernels = try kern.Kernels.load(gpa, io, d, kernel_dir); + errdefer kernels.unload(); + + const path = try std.fs.path.join(gpa, &.{ checkpoint_dir, "codec.pth" }); + defer gpa.free(path); + var archive = try pth.Archive.open(gpa, io, path); + defer archive.close(); + var names = std.heap.ArenaAllocator.init(gpa); + defer names.deinit(); + var stage: load.Stage = .{ .gpa = gpa }; + defer stage.bytes.deinit(gpa); + var loader: load.Loader = .{ .gpa = gpa, .names = names.allocator(), .archive = &archive, .stage = &stage }; + const w = try loader.weights(options.max_frames); + var weights = try cuda.DeviceBuffer.fromHost(d, stage.bytes.items); + errdefer weights.free(); + + var acts: [3]cuda.DeviceBuffer = undefined; + var made: usize = 0; + errdefer for (acts[0..made]) |*b| b.free(); + for (&acts) |*b| { + b.* = try cuda.DeviceBuffer.alloc(d, act_halves_per_frame * options.max_frames * 2); + made += 1; + } + var codes_dev = try cuda.DeviceBuffer.alloc(d, options.max_frames * codebooks * @sizeOf(u32)); + errdefer codes_dev.free(); + var audio_dev = try cuda.DeviceBuffer.alloc(d, options.max_frames * samples_per_frame * @sizeOf(f32)); + errdefer audio_dev.free(); + var codes_host = try cuda.HostBuffer.alloc(d, options.max_frames * codebooks * @sizeOf(u32)); + errdefer codes_host.free(); + var audio_host = try cuda.HostBuffer.alloc(d, options.max_frames * samples_per_frame * @sizeOf(f32)); + errdefer audio_host.free(); + var kv = try cuda.DeviceBuffer.alloc(d, layers * options.max_frames * 3 * latent * 2); + errdefer kv.free(); + const carry = try cuda.DeviceBuffer.alloc(d, carries.bytes); + return .{ + .max_frames = options.max_frames, + .ctx = ctx, + .kernels = kernels, + .weights = weights, + .w = w, + .acts = acts, + .codes_dev = codes_dev, + .audio_dev = audio_dev, + .codes_host = codes_host, + .audio_host = audio_host, + .kv = kv, + .carry = carry, + }; + } + + pub fn deinit(self: *Model) void { + self.ctx.makeCurrent() catch {}; + self.carry.free(); + self.kv.free(); + self.audio_host.free(); + self.codes_host.free(); + self.audio_dev.free(); + self.codes_dev.free(); + for (&self.acts) |*b| b.free(); + self.weights.free(); + self.kernels.unload(); + self.* = undefined; + } + + /// Starts an utterance for `advance`; `decode` and a failed `advance` also end one (the next starts at frame 0). + pub fn begin(self: *Model) void { + self.decoded = 0; + } + + /// The frames after those decoded into the same rows of `output`, bit-identical to `decode(codes)` there. + pub fn advance(self: *Model, stream: cuda.Stream, codes: []const [10]u32, output: []f32) !usize { + const first = self.decoded; + if (codes.len <= first) return error.NoFrames; + self.decoded = 0; + const samples = try self.run(stream, codes, first, true, output); + self.decoded = codes.len; + return samples; + } + + /// Decodes frame-major codes (clamped as rvq.py clamps them) to codes.len * 2048 FP32 samples, device work done. + pub fn decode(self: *Model, stream: cuda.Stream, codes: []const [10]u32, output: []f32) !usize { + self.decoded = 0; + return self.run(stream, codes, 0, false, output); + } + + /// Frames [first, codes.len) into output[first * 2048 ..]; `keep_rows`: save the rows the next chunk reads. + fn run(self: *Model, stream: cuda.Stream, codes: []const [10]u32, first: usize, keep_rows: bool, output: []f32) !usize { + const frames = codes.len; + if (frames == 0) return error.NoFrames; + if (frames > self.max_frames) return error.TooManyFrames; + const samples = frames * samples_per_frame; + if (output.len < samples) return error.OutputTooSmall; + try self.ctx.makeCurrent(); + const code_at = first * codebooks * @sizeOf(u32); + const code_bytes = std.mem.sliceAsBytes(codes[first..]); + const staged = self.codes_host.bytes[code_at..][0..code_bytes.len]; + @memcpy(staged, code_bytes); + try self.codes_dev.uploadAsync(code_at, staged, stream.handle); + try self.forward(stream, first, frames, keep_rows); + const audio = self.audio_host.slice(f32)[first * samples_per_frame .. samples]; + try self.audio_dev.downloadAsync(first * samples_per_frame * @sizeOf(f32), std.mem.sliceAsBytes(audio), stream.handle); + try stream.synchronize(); + @memcpy(output[first * samples_per_frame .. samples], audio); + return samples; + } + + fn wp(self: *const Model, offset: u64) u64 { + return self.weights.ptr + offset; + } + + /// Before a consumer reads rows [at, end) of `tensor`: restore the kept rows before `at`, then keep the last ones. + fn history(self: *Model, s: cuda.Stream, c: Carry, tensor: u64, at: usize, end: usize, keep_rows: bool) !void { + const row = c.width * 2; + const back = @min(c.rows, at); + if (back > 0) { + const into: cuda.DeviceBuffer = .{ .d = self.carry.d, .ptr = tensor + (at - back) * row, .len = back * row, .borrowed = true }; + try into.copyFrom(0, self.carry.ptr + c.offset + (c.rows - back) * row, back * row, s.handle); + } + if (!keep_rows) return; + const n = @min(c.rows, end); + try self.carry.copyFrom(c.offset + (c.rows - n) * row, tensor + (end - n) * row, n * row, s.handle); + } + + /// Frames [first, end): every stage computes only its new rows, at the absolute rows a whole decode uses. + fn forward(self: *Model, s: cuda.Stream, first: usize, end: usize, keep_rows: bool) !void { + const k = &self.kernels; + const w = &self.w; + const h = 2; // bytes an FP16 element + const p = [3]u64{ self.acts[0].ptr, self.acts[1].ptr, self.acts[2].ptr }; + const frames = end - first; + + // rvq.py decode: z = semantic + residual codebooks through out_proj + try k.rvqLatent(s, self.codes_dev.ptr + first * codebooks * @sizeOf(u32), self.wp(w.semantic_book), self.wp(w.residual_books), self.wp(w.out_w), self.wp(w.out_b), p[0] + first * latent * h, frames); + + // post_module (WindowLimitedTransformer): x in p[0], scratch in p[1] and p[2], each layer's qkv in kv + const x = p[0]; + const xn = p[1]; + const att = p[1] + end * latent * h; + const gu = p[2]; + const act = p[2] + end * 2 * ffn * h; + const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); + for (&w.layers, 0..) |*l, i| { + const qkv = self.kv.ptr + i * self.max_frames * 3 * latent * h; + try k.rmsNorm(s, x + first * latent * h, self.wp(l.attention_norm), xn + first * latent * h, frames, latent, rms_eps); + try k.gemm(s, .{ .x = xn, .w = self.wp(l.wqkv), .y = qkv, .first = first, .m = end, .n = 3 * latent, .cin = latent, .ldx = latent, .ldy = 3 * latent }); + try k.ropeQk(s, qkv + first * 3 * latent * h, self.wp(w.rope) + first * head_dim * h, frames, latent); + try k.windowAttention(s, qkv, att, first, end, heads, window, scale); + // h = x + attention_layer_scale(wo(y)), in place over x + try k.gemm(s, .{ .x = att, .w = self.wp(l.wo), .y = x, .first = first, .m = end, .n = latent, .cin = latent, .ldx = latent, .ldy = latent, .scale = self.wp(l.attention_scale), .residual = x, .ldr = latent }); + try k.rmsNorm(s, x + first * latent * h, self.wp(l.ffn_norm), xn + first * latent * h, frames, latent, rms_eps); + try k.gemm(s, .{ .x = xn, .w = self.wp(l.w13), .y = gu, .first = first, .m = end, .n = 2 * ffn, .cin = latent, .ldx = latent, .ldy = 2 * ffn }); + try k.siluMul(s, gu + first * 2 * ffn * h, act + first * ffn * h, frames, ffn); + try k.gemm(s, .{ .x = act, .w = self.wp(l.w2), .y = x, .first = first, .m = end, .n = latent, .cin = ffn, .ldx = ffn, .ldy = latent, .scale = self.wp(l.ffn_scale), .residual = x, .ldr = latent }); + } + try k.rmsNorm(s, x + first * latent * h, self.wp(w.norm), p[1] + first * latent * h, frames, latent, rms_eps); + + // upsample: (ConvTranspose1d k2 s2, ConvNeXtBlock) twice; rows [first, end) -> [4 first, 4 end) + var input = p[1]; + var spent = p[0]; + var from = first; + var to = end; + for (&w.upsample, carries.dwconv) |*u, carry| { + const y = spent; + try k.gemm(s, .{ .x = input, .w = self.wp(u.conv), .y = y, .first = from, .m = to, .n = 2 * latent, .cin = latent, .ldx = latent, .ldy = 2 * latent, .bias = self.wp(u.conv_b), .bias_mode = .separate, .period = latent }); + from *= 2; + to *= 2; + const dw = p[2]; + const normed = p[2] + to * latent * h; + try self.history(s, carry, y, from, to, keep_rows); + try k.dwconv(s, y, self.wp(u.dw), self.wp(u.dw_b), dw, from, to, latent); + try k.layerNorm(s, dw + from * latent * h, self.wp(u.norm_w), self.wp(u.norm_b), normed + from * latent * h, to - from, latent, layer_norm_eps); + const hidden = input; // the stage input is spent + try k.gemm(s, .{ .x = normed, .w = self.wp(u.pw1), .y = hidden, .first = from, .m = to, .n = convnext_hidden, .cin = latent, .ldx = latent, .ldy = convnext_hidden, .bias = self.wp(u.pw1_b), .bias_mode = .fused, .act = .gelu }); + // y = input + gamma * pwconv2(...), in place over y's new rows + try k.gemm(s, .{ .x = hidden, .w = self.wp(u.pw2), .y = y, .first = from, .m = to, .n = latent, .cin = convnext_hidden, .ldx = convnext_hidden, .ldy = latent, .bias = self.wp(u.pw2_b), .bias_mode = .fused, .scale = self.wp(u.gamma), .residual = y, .ldr = latent }); + input = y; + spent = hidden; + } + + // decoder.model: conv 1024 -> 1536 (kernel 7, causal); its kept rows replace the depthwise conv's in `input` + var cur = spent; + try self.history(s, carries.conv0, input, from, to, keep_rows); + try k.gemm(s, .{ .x = input, .w = self.wp(w.conv0), .y = cur, .first = from, .m = to, .n = decoder_dim, .cin = latent, .ldx = latent, .ldy = decoder_dim, .taps = 7, .bias = self.wp(w.conv0_b), .bias_mode = .separate }); + var spare = [2]u64{ input, p[2] }; + var ch: usize = decoder_dim; + for (&w.blocks, rates, carries.blocks) |*b, rate, kept| { + const out_ch = ch / 2; + // DecoderBlock: Snake, then ConvTranspose1d(kernel 2 * rate, stride rate) trimmed causally + try k.snake(s, cur + from * ch * h, self.wp(b.snake.alpha), self.wp(b.snake.inv), spare[0] + from * ch * h, to - from, ch); + try self.history(s, kept.transconv, spare[0], from, to, keep_rows); + try k.gemm(s, .{ .x = spare[0], .w = self.wp(b.conv), .y = spare[1], .first = from, .m = to, .n = rate * out_ch, .cin = ch, .ldx = ch, .ldy = rate * out_ch, .taps = 2, .bias = self.wp(b.conv_b), .bias_mode = .separate, .period = out_ch }); + from *= rate; + to *= rate; + ch = out_ch; + // ResidualUnits: x + conv1(snake(conv7(snake(x)))), rotating three buffers + var xb = spare[1]; + var sb = cur; + var tb = spare[0]; + for (&b.units, dilations, kept.units) |*u, dilation, carry| { + try k.snake(s, xb + from * ch * h, self.wp(u.snake1.alpha), self.wp(u.snake1.inv), sb + from * ch * h, to - from, ch); + try self.history(s, carry, sb, from, to, keep_rows); + try k.gemm(s, .{ .x = sb, .w = self.wp(u.conv7), .y = tb, .first = from, .m = to, .n = ch, .cin = ch, .ldx = ch, .ldy = ch, .taps = 7, .dilation = dilation, .bias = self.wp(u.conv7_b), .bias_mode = .separate }); + try k.snake(s, tb + from * ch * h, self.wp(u.snake2.alpha), self.wp(u.snake2.inv), tb + from * ch * h, to - from, ch); + try k.gemm(s, .{ .x = tb, .w = self.wp(u.conv1), .y = sb, .first = from, .m = to, .n = ch, .cin = ch, .ldx = ch, .ldy = ch, .bias = self.wp(u.conv1_b), .bias_mode = .separate, .residual = xb, .ldr = ch }); + const unit_out = sb; + sb = tb; + tb = xb; + xb = unit_out; + } + cur = xb; + spare = .{ sb, tb }; + } + // Snake, conv 96 -> 1 (kernel 7, causal), tanh + try k.snake(s, cur + from * ch * h, self.wp(w.out_snake.alpha), self.wp(w.out_snake.inv), cur + from * ch * h, to - from, ch); + try self.history(s, carries.out, cur, from, to, keep_rows); + try k.convOutTanh(s, cur, self.wp(w.out_conv), self.wp(w.out_conv_b), self.audio_dev.ptr, from, to, ch); + } +}; diff --git a/zig/src/families/drama/codec_kernels.zig b/zig/src/families/drama/codec_kernels.zig new file mode 100644 index 00000000000..b552e6f632b --- /dev/null +++ b/zig/src/families/drama/codec_kernels.zig @@ -0,0 +1,259 @@ +//! drama_codec.cu's kernels: loaded from `/drama_codec.fatbin`, launched with their exact C argument types. + +const std = @import("std"); +const cuda = @import("cuda"); + +pub const fatbin_name = "drama_codec.fatbin"; + +pub const BiasMode = enum(i32) { + none = 0, + /// cuBLASLt's bias epilogue: h(acc + b). + fused = 1, + /// cuDNN then add_: h(h(acc) + b). + separate = 2, +}; + +pub const Act = enum(i32) { none = 0, gelu = 1 }; + +/// drama_codec.cu's GemmParams, field for field. +const GemmParams = extern struct { + x: u64, + w: u64, + bias: u64, + scale: u64, + residual: u64, + y: u64, + m: i64, + m_begin: i64, + n: i32, + cin: i32, + taps: i32, + dilation: i32, + ldx: i32, + ldy: i32, + ldr: i32, + period: i32, + bias_mode: i32, + act: i32, +}; + +/// One drama_codec_conv_gemm call: rows [first, m) of n columns from taps shifted reads of cin channels. +pub const Gemm = struct { + x: u64, + w: u64, + y: u64, + m: usize, + n: usize, + cin: usize, + ldx: usize, + ldy: usize, + /// Rows before it are neither read nor written (an incremental decode's earlier chunks). + first: usize = 0, + taps: usize = 1, + dilation: usize = 1, + bias: u64 = 0, + bias_mode: BiasMode = .none, + /// Bias and scale index n % period; 0 means n. + period: usize = 0, + act: Act = .none, + scale: u64 = 0, + residual: u64 = 0, + ldr: usize = 0, +}; + +fn small(v: usize) !i32 { + if (v > std.math.maxInt(i32)) return error.Invalid; + return @intCast(v); +} + +fn blocks(n: usize, per: usize) !u32 { + const b = (n + per - 1) / per; + if (b == 0 or b > std.math.maxInt(i32)) return error.Invalid; + return @intCast(b); +} + +pub const Kernels = struct { + module: cuda.Module, + rvq: cuda.Function, + rms_norm: cuda.Function, + rope: cuda.Function, + attention: cuda.Function, + silu_mul: cuda.Function, + layer_norm: cuda.Function, + dwconv7: cuda.Function, + snake_fn: cuda.Function, + out_tanh: cuda.Function, + gemm_fn: cuda.Function, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, kernel_dir: []const u8) !Kernels { + var module = if (kernel_dir.len == 0) try cuda.Module.load(d, cuda.kernels.drama_codec) else blk: { + const path = try std.fs.path.join(gpa, &.{ kernel_dir, fatbin_name }); + defer gpa.free(path); + const image = std.Io.Dir.cwd().readFileAllocOptions(io, path, gpa, .limited(1 << 28), .@"16", null) catch |e| { + std.log.err("drama codec kernels: cannot read {s}: {s}", .{ path, @errorName(e) }); + return e; + }; + defer gpa.free(image); + break :blk try cuda.Module.load(d, image); + }; + errdefer module.unload(); + return .{ + .module = module, + .rvq = try module.function("drama_codec_rvq_latent"), + .rms_norm = try module.function("drama_codec_rms_norm"), + .rope = try module.function("drama_codec_rope"), + .attention = try module.function("drama_codec_window_attention"), + .silu_mul = try module.function("drama_codec_silu_mul"), + .layer_norm = try module.function("drama_codec_layer_norm"), + .dwconv7 = try module.function("drama_codec_dwconv7"), + .snake_fn = try module.function("drama_codec_snake"), + .out_tanh = try module.function("drama_codec_conv_out_tanh"), + .gemm_fn = try module.function("drama_codec_conv_gemm"), + }; + } + + pub fn unload(k: *Kernels) void { + k.module.unload(); + k.* = undefined; + } + + fn run(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); + } + + /// codes [frames][10] u32 -> z [frames][1024]. + pub fn rvqLatent(k: *const Kernels, s: cuda.Stream, codes: u64, semantic_book: u64, residual_books: u64, out_w: u64, out_b: u64, z: u64, frames: usize) !void { + var a: cuda.Args = .{}; + a.add(codes); + a.add(semantic_book); + a.add(residual_books); + a.add(out_w); + a.add(out_b); + a.add(z); + try run(k.rvq, s, .{ .x = try blocks(frames, 1) }, 256, &a); + } + + pub fn rmsNorm(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, y: u64, rows: usize, width: usize, eps: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(y); + a.add(try small(width)); + a.add(eps); + try run(k.rms_norm, s, .{ .x = try blocks(rows, 1) }, 256, &a); + } + + /// In place on the q and k thirds of qkv [frames][3 * width]. + pub fn ropeQk(k: *const Kernels, s: cuda.Stream, qkv: u64, table: u64, frames: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(table); + a.add(try small(width)); + a.add(try small(3 * width)); + try run(k.rope, s, .{ .x = try blocks(frames, 1) }, 256, &a); + } + + /// Queries [first, end) at their absolute rows; qkv holds every row their windows reach. + pub fn windowAttention(k: *const Kernels, s: cuda.Stream, qkv: u64, out: u64, first: usize, end: usize, heads: usize, window: usize, scale: f32) !void { + if (window == 0 or window > 128) return error.Invalid; + var a: cuda.Args = .{}; + a.add(qkv); + a.add(out); + a.add(try small(first)); + a.add(try small(heads)); + a.add(try small(window)); + a.add(scale); + try run(k.attention, s, .{ .x = try blocks(end - first, 1), .y = @intCast(heads) }, 128, &a); + } + + pub fn siluMul(k: *const Kernels, s: cuda.Stream, gu: u64, out: u64, rows: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(gu); + a.add(out); + a.add(@as(i64, @intCast(rows))); + a.add(try small(width)); + try run(k.silu_mul, s, .{ .x = try blocks(rows * width, 256) }, 256, &a); + } + + pub fn layerNorm(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, b: u64, y: u64, rows: usize, width: usize, eps: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(b); + a.add(y); + a.add(try small(width)); + a.add(eps); + try run(k.layer_norm, s, .{ .x = try blocks(rows, 1) }, 256, &a); + } + + /// Rows [first, end) at their absolute rows; x holds the six rows before `first`. + pub fn dwconv(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, b: u64, y: u64, first: usize, end: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(b); + a.add(y); + a.add(@as(i64, @intCast(first))); + a.add(@as(i64, @intCast(end - first))); + a.add(try small(width)); + try run(k.dwconv7, s, .{ .x = try blocks((end - first) * width, 256) }, 256, &a); + } + + /// Snake over [rows][width]; x and y may be the same buffer. + pub fn snake(k: *const Kernels, s: cuda.Stream, x: u64, alpha: u64, inv_alpha: u64, y: u64, rows: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(alpha); + a.add(inv_alpha); + a.add(y); + a.add(@as(i64, @intCast(rows * width))); + a.add(try small(width)); + try run(k.snake_fn, s, .{ .x = try blocks(rows * width, 256) }, 256, &a); + } + + /// The final conv and tanh into FP32 PCM rows [first, end) at their absolute rows. + pub fn convOutTanh(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, b: u64, y: u64, first: usize, end: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(b); + a.add(y); + a.add(@as(i64, @intCast(first))); + a.add(@as(i64, @intCast(end - first))); + a.add(try small(width)); + try run(k.out_tanh, s, .{ .x = try blocks(end - first, 256) }, 256, &a); + } + + pub fn gemm(k: *const Kernels, s: cuda.Stream, g: Gemm) !void { + const ktot = g.taps * g.cin; + if (g.first >= g.m or g.n == 0 or g.taps == 0 or g.cin == 0) return error.Invalid; + if (g.cin % 8 != 0 or g.ldx % 8 != 0 or g.ldx < g.cin or g.ldy < g.n) return error.Invalid; + if (g.x % 16 != 0 or g.w % 16 != 0) return error.Misaligned; + if ((g.bias_mode != .none) != (g.bias != 0)) return error.Invalid; + if (g.residual != 0 and g.ldr < g.n) return error.Invalid; + const p: GemmParams = .{ + .x = g.x, + .w = g.w, + .bias = g.bias, + .scale = g.scale, + .residual = g.residual, + .y = g.y, + .m = @intCast(g.m), + .m_begin = @intCast(g.first), + .n = try small(g.n), + .cin = try small(g.cin), + .taps = try small(g.taps), + .dilation = try small(g.dilation), + .ldx = try small(g.ldx), + .ldy = try small(g.ldy), + .ldr = try small(g.ldr), + .period = try small(if (g.period == 0) g.n else g.period), + .bias_mode = @backingInt(g.bias_mode), + .act = @backingInt(g.act), + }; + _ = try small(ktot); + var a: cuda.Args = .{}; + a.add(p); + try run(k.gemm_fn, s, .{ .x = try blocks(g.m - g.first / 128 * 128, 128), .y = try blocks(g.n, 128) }, 256, &a); + } +}; diff --git a/zig/src/families/drama/codec_load.zig b/zig/src/families/drama/codec_load.zig new file mode 100644 index 00000000000..8904e96723e --- /dev/null +++ b/zig/src/families/drama/codec_load.zig @@ -0,0 +1,440 @@ +//! The pinned DAC codec's geometry and its device weight image, built once on the host from codec.pth. + +const std = @import("std"); +const pth = @import("codec_pth.zig"); + +const Allocator = std.mem.Allocator; + +// modded_dac_vq.yaml and modded_dac.py's geometry for the pinned codec. +pub const latent = 1024; +pub const codebook_dim = 8; +pub const semantic_size = 4096; +pub const residual_size = 1024; +pub const residual_books = 9; +pub const codebooks = 1 + residual_books; +pub const layers = 8; +pub const heads = 16; +pub const head_dim = 64; +pub const ffn = 3072; +pub const window = 128; +pub const rope_base = 10000.0; +pub const rms_eps: f32 = 1e-5; +pub const layer_norm_eps: f32 = 1e-6; +pub const convnext_hidden = 4 * latent; +pub const upsample_stages = 2; // downsample_factor [2, 2] +pub const decoder_dim = 1536; +pub const rates = [_]usize{ 8, 8, 4, 2 }; +pub const dilations = [_]usize{ 1, 3, 9 }; +pub const latent_rows_per_frame = 1 << upsample_stages; +const hop = blk: { + var h: usize = 1; + for (rates) |r| h *= r; + break :blk h; +}; +pub const samples_per_frame = latent_rows_per_frame * hop; // DAC.frame_length = hop_length * 4 = 2048 +pub const out_channels = decoder_dim >> rates.len; + +pub const Snake = struct { alpha: u64, inv: u64 }; + +pub const Layer = struct { + wqkv: u64, + wo: u64, + w13: u64, + w2: u64, + attention_norm: u64, + ffn_norm: u64, + attention_scale: u64, + ffn_scale: u64, +}; + +pub const Upsample = struct { + conv: u64, + conv_b: u64, + dw: u64, + dw_b: u64, + norm_w: u64, + norm_b: u64, + pw1: u64, + pw1_b: u64, + pw2: u64, + pw2_b: u64, + gamma: u64, +}; + +pub const Unit = struct { snake1: Snake, conv7: u64, conv7_b: u64, snake2: Snake, conv1: u64, conv1_b: u64 }; + +pub const Block = struct { snake: Snake, conv: u64, conv_b: u64, units: [dilations.len]Unit }; + +/// Byte offsets into the one device weight buffer. +pub const Weights = struct { + semantic_book: u64, + residual_books: u64, + out_w: u64, + out_b: u64, + layers: [layers]Layer, + norm: u64, + upsample: [upsample_stages]Upsample, + conv0: u64, + conv0_b: u64, + blocks: [rates.len]Block, + out_snake: Snake, + out_conv: u64, + out_conv_b: u64, + rope: u64, +}; + +/// The weight image built on the host before one upload; every tensor 256-byte aligned. +pub const Stage = struct { + gpa: Allocator, + bytes: std.ArrayList(u8) = .empty, + + fn reserve(st: *Stage, n: usize) !usize { + const at = std.mem.alignForward(usize, st.bytes.items.len, 256); + try st.bytes.appendNTimes(st.gpa, 0, at + n - st.bytes.items.len); + return at; + } + + /// FP32 values as FP16, round to nearest even (torch's .to(float16)). + fn halves(st: *Stage, values: []const f32) !u64 { + const at = try st.reserve(values.len * 2); + const dst = st.bytes.items[at..][0 .. values.len * 2]; + for (values, 0..) |v, i| std.mem.writeInt(u16, dst[i * 2 ..][0..2], halfBits(v), .little); + return at; + } + + fn floats(st: *Stage, values: []const f32) !u64 { + const at = try st.reserve(values.len * 4); + @memcpy(st.bytes.items[at..][0 .. values.len * 4], std.mem.sliceAsBytes(values)); + return at; + } +}; + +fn halfBits(v: f32) u16 { + return @bitCast(@as(f16, @floatCast(v))); +} + +/// float32 rounded to bfloat16 (round to nearest even) and back, as torch rounds it. +fn bf16Round(v: f32) f32 { + const b: u32 = @bitCast(v); + const r = b +% (0x7FFF + ((b >> 16) & 1)); + return @bitCast(r & 0xFFFF0000); +} + +/// torch._weight_norm over dim 0 with the CUDA kernel's 256-strided FP32 FMA tree, before rounding to FP16. +fn foldWeightNorm(v: []f32, g: []const f32) !void { + if (g.len == 0 or v.len % g.len != 0) return error.Invalid; + const row = v.len / g.len; + var width: usize = 1; + while (width < @min(row, 256)) : (width *= 2) {} + var partial: [256]f32 = undefined; + for (g, 0..) |gi, i| { + const r = v[i * row ..][0..row]; + for (0..width) |lane| { + var sum: f32 = 0; + var column = lane; + while (column < row) : (column += 256) sum = @mulAdd(f32, r[column], r[column], sum); + partial[lane] = sum; + } + // For short rows, the omitted upper lanes contain only zeros. + var stride = width / 2; + while (stride != 0) : (stride /= 2) { + for (0..stride) |lane| partial[lane] += partial[lane + stride]; + } + const norm: f32 = @sqrt(partial[0]); + if (!(norm > 0)) return error.DegenerateWeightNorm; + const rnorm: f32 = 1.0 / norm; + for (r) |*e| e.* = gi * e.* * rnorm; + } +} + +/// Conv1d weight [cout][cin][k] as the implicit GEMM's [cout][k * cin]. +fn convTaps(gpa: Allocator, w: []const f32, cout: usize, cin: usize, k: usize) ![]f32 { + if (w.len != cout * cin * k) return error.Invalid; + const out = try gpa.alloc(f32, w.len); + for (0..cout) |co| { + for (0..cin) |ci| { + for (0..k) |t| out[(co * k + t) * cin + ci] = w[(co * cin + ci) * k + t]; + } + } + return out; +} + +/// ConvTranspose1d [cin][cout][k] as the GEMM's [s * cout][taps * cin]; column j * cout + co is sample q * s + j. +fn transposedTaps(gpa: Allocator, w: []const f32, cin: usize, cout: usize, s: usize, k: usize) ![]f32 { + if (w.len != cin * cout * k or (k != s and k != 2 * s)) return error.Invalid; + const taps = k / s; + const out = try gpa.alloc(f32, w.len); + for (0..s) |j| { + for (0..cout) |co| { + for (0..taps) |tap| { + const kk = if (taps == 2 and tap == 0) j + s else j; + for (0..cin) |ci| out[((j * cout + co) * taps + tap) * cin + ci] = w[(ci * cout + co) * k + kk]; + } + } + } + return out; +} + +/// precompute_freqs_cis(seq_len, 64, 10000) for frames positions, cos and sin rounded to BF16, as [frames][32][2]. +fn ropeTable(gpa: Allocator, frames: usize) ![]f32 { + const pairs = head_dim / 2; + var freqs: [pairs]f32 = undefined; + for (&freqs, 0..) |*f, i| { + const x: f32 = @as(f32, @floatFromInt(2 * i)) / @as(f32, head_dim); + const p: f32 = @floatCast(std.math.pow(f64, rope_base, @as(f64, x))); + f.* = 1.0 / p; + } + const out = try gpa.alloc(f32, frames * pairs * 2); + for (0..frames) |t| { + for (freqs, 0..) |f, i| { + const angle: f32 = @as(f32, @floatFromInt(t)) * f; + const a: f64 = angle; + out[(t * pairs + i) * 2] = bf16Round(@floatCast(@cos(a))); + out[(t * pairs + i) * 2 + 1] = bf16Round(@floatCast(@sin(a))); + } + } + return out; +} + +pub const Loader = struct { + gpa: Allocator, + names: Allocator, + archive: *const pth.Archive, + stage: *Stage, + + fn name(l: *Loader, comptime fmt: []const u8, args: anytype) ![]const u8 { + return std.fmt.allocPrint(l.names, fmt, args); + } + + fn read(l: *Loader, tensor: []const u8, shape: []const u64) ![]f32 { + return l.archive.readF32(l.gpa, tensor, shape); + } + + /// A tensor as FP16 in its checkpoint layout. + fn half(l: *Loader, tensor: []const u8, shape: []const u64) !u64 { + const v = try l.read(tensor, shape); + defer l.gpa.free(v); + return l.stage.halves(v); + } + + /// A weight-normed tensor folded over dim 0 (caller frees); g is [shape[0], 1, 1]. + fn folded(l: *Loader, g_name: []const u8, v_name: []const u8, shape: []const u64) ![]f32 { + const v = try l.read(v_name, shape); + errdefer l.gpa.free(v); + const g = try l.read(g_name, &[_]u64{ shape[0], 1, 1 }); + defer l.gpa.free(g); + try foldWeightNorm(v, g); + return v; + } + + /// A decoder conv (parametrizations.weight_norm) at `prefix`.conv, folded, as GEMM taps in FP16. + fn decoderConv(l: *Loader, prefix: []const u8, cout: usize, cin: usize, k: usize) !u64 { + const v = try l.folded( + try l.name("{s}.conv.parametrizations.weight.original0", .{prefix}), + try l.name("{s}.conv.parametrizations.weight.original1", .{prefix}), + &[_]u64{ cout, cin, k }, + ); + defer l.gpa.free(v); + const t = try convTaps(l.gpa, v, cout, cin, k); + defer l.gpa.free(t); + return l.stage.halves(t); + } + + fn snake(l: *Loader, tensor: []const u8, channels: usize) !Snake { + const alpha = try l.read(tensor, &[_]u64{ 1, channels, 1 }); + defer l.gpa.free(alpha); + const inv = try l.gpa.alloc(f32, channels); + defer l.gpa.free(inv); + // (alpha + 1e-9).reciprocal() in FP32 + for (alpha, inv) |a, *r| r.* = 1.0 / (a + @as(f32, 1e-9)); + return .{ .alpha = try l.stage.floats(alpha), .inv = try l.stage.floats(inv) }; + } + + pub fn weights(l: *Loader, max_frames: usize) !Weights { + var w: Weights = undefined; + const gpa = l.gpa; + + // quantizer RVQ: codebooks, folded out_proj (legacy weight_norm: weight_g, weight_v) + w.semantic_book = try l.half("quantizer.semantic_quantizer.quantizers.0.codebook.weight", &[_]u64{ semantic_size, codebook_dim }); + { + const books = try gpa.alloc(f32, residual_books * residual_size * codebook_dim); + defer gpa.free(books); + for (0..residual_books) |i| { + const v = try l.read(try l.name("quantizer.quantizer.quantizers.{d}.codebook.weight", .{i}), &[_]u64{ residual_size, codebook_dim }); + defer gpa.free(v); + @memcpy(books[i * residual_size * codebook_dim ..][0..v.len], v); + } + w.residual_books = try l.stage.halves(books); + } + { + const ow = try gpa.alloc(f32, codebooks * latent * codebook_dim); + defer gpa.free(ow); + const ob = try gpa.alloc(f32, codebooks * latent); + defer gpa.free(ob); + for (0..codebooks) |i| { + const prefix = if (i == 0) "quantizer.semantic_quantizer.quantizers.0" else try l.name("quantizer.quantizer.quantizers.{d}", .{i - 1}); + const v = try l.folded(try l.name("{s}.out_proj.weight_g", .{prefix}), try l.name("{s}.out_proj.weight_v", .{prefix}), &[_]u64{ latent, codebook_dim, 1 }); + defer gpa.free(v); + @memcpy(ow[i * latent * codebook_dim ..][0..v.len], v); + const b = try l.read(try l.name("{s}.out_proj.bias", .{prefix}), &[_]u64{latent}); + defer gpa.free(b); + @memcpy(ob[i * latent ..][0..latent], b); + } + w.out_w = try l.stage.halves(ow); + w.out_b = try l.stage.halves(ob); + } + + // post_module transformer + for (&w.layers, 0..) |*layer, i| { + const p = try l.name("quantizer.post_module.layers.{d}", .{i}); + layer.wqkv = try l.half(try l.name("{s}.attention.wqkv.weight", .{p}), &[_]u64{ 3 * latent, latent }); + layer.wo = try l.half(try l.name("{s}.attention.wo.weight", .{p}), &[_]u64{ latent, latent }); + { + const w13 = try gpa.alloc(f32, 2 * ffn * latent); + defer gpa.free(w13); + const w1 = try l.read(try l.name("{s}.feed_forward.w1.weight", .{p}), &[_]u64{ ffn, latent }); + defer gpa.free(w1); + const w3 = try l.read(try l.name("{s}.feed_forward.w3.weight", .{p}), &[_]u64{ ffn, latent }); + defer gpa.free(w3); + @memcpy(w13[0 .. ffn * latent], w1); + @memcpy(w13[ffn * latent ..], w3); + layer.w13 = try l.stage.halves(w13); + } + layer.w2 = try l.half(try l.name("{s}.feed_forward.w2.weight", .{p}), &[_]u64{ latent, ffn }); + layer.attention_norm = try l.half(try l.name("{s}.attention_norm.weight", .{p}), &[_]u64{latent}); + layer.ffn_norm = try l.half(try l.name("{s}.ffn_norm.weight", .{p}), &[_]u64{latent}); + layer.attention_scale = try l.half(try l.name("{s}.attention_layer_scale.gamma", .{p}), &[_]u64{latent}); + layer.ffn_scale = try l.half(try l.name("{s}.ffn_layer_scale.gamma", .{p}), &[_]u64{latent}); + } + w.norm = try l.half("quantizer.post_module.norm.weight", &[_]u64{latent}); + + // upsample stages (plain convs: rvq.py's own CausalConvNet classes carry no weight norm) + for (&w.upsample, 0..) |*u, i| { + const p = try l.name("quantizer.upsample.{d}", .{i}); + { + const v = try l.read(try l.name("{s}.0.conv.weight", .{p}), &[_]u64{ latent, latent, 2 }); + defer gpa.free(v); + const t = try transposedTaps(gpa, v, latent, latent, 2, 2); + defer gpa.free(t); + u.conv = try l.stage.halves(t); + } + u.conv_b = try l.half(try l.name("{s}.0.conv.bias", .{p}), &[_]u64{latent}); + u.dw = try l.half(try l.name("{s}.1.dwconv.conv.weight", .{p}), &[_]u64{ latent, 1, 7 }); + u.dw_b = try l.half(try l.name("{s}.1.dwconv.conv.bias", .{p}), &[_]u64{latent}); + u.norm_w = try l.half(try l.name("{s}.1.norm.weight", .{p}), &[_]u64{latent}); + u.norm_b = try l.half(try l.name("{s}.1.norm.bias", .{p}), &[_]u64{latent}); + u.pw1 = try l.half(try l.name("{s}.1.pwconv1.weight", .{p}), &[_]u64{ convnext_hidden, latent }); + u.pw1_b = try l.half(try l.name("{s}.1.pwconv1.bias", .{p}), &[_]u64{convnext_hidden}); + u.pw2 = try l.half(try l.name("{s}.1.pwconv2.weight", .{p}), &[_]u64{ latent, convnext_hidden }); + u.pw2_b = try l.half(try l.name("{s}.1.pwconv2.bias", .{p}), &[_]u64{latent}); + u.gamma = try l.half(try l.name("{s}.1.gamma", .{p}), &[_]u64{latent}); + } + + // decoder + w.conv0 = try l.decoderConv("decoder.model.0", decoder_dim, latent, 7); + w.conv0_b = try l.half("decoder.model.0.conv.bias", &[_]u64{decoder_dim}); + var ch: usize = decoder_dim; + for (&w.blocks, rates, 0..) |*b, rate, i| { + const out_ch = ch / 2; + const p = try l.name("decoder.model.{d}.block", .{i + 1}); + b.snake = try l.snake(try l.name("{s}.0.alpha", .{p}), ch); + { + const v = try l.folded( + try l.name("{s}.1.conv.parametrizations.weight.original0", .{p}), + try l.name("{s}.1.conv.parametrizations.weight.original1", .{p}), + &[_]u64{ ch, out_ch, 2 * rate }, + ); + defer gpa.free(v); + const t = try transposedTaps(gpa, v, ch, out_ch, rate, 2 * rate); + defer gpa.free(t); + b.conv = try l.stage.halves(t); + } + b.conv_b = try l.half(try l.name("{s}.1.conv.bias", .{p}), &[_]u64{out_ch}); + for (&b.units, 0..) |*u, j| { + const q = try l.name("{s}.{d}.block", .{ p, j + 2 }); + u.snake1 = try l.snake(try l.name("{s}.0.alpha", .{q}), out_ch); + u.conv7 = try l.decoderConv(try l.name("{s}.1", .{q}), out_ch, out_ch, 7); + u.conv7_b = try l.half(try l.name("{s}.1.conv.bias", .{q}), &[_]u64{out_ch}); + u.snake2 = try l.snake(try l.name("{s}.2.alpha", .{q}), out_ch); + u.conv1 = try l.decoderConv(try l.name("{s}.3", .{q}), out_ch, out_ch, 1); + u.conv1_b = try l.half(try l.name("{s}.3.conv.bias", .{q}), &[_]u64{out_ch}); + } + ch = out_ch; + } + const tail = rates.len + 1; + w.out_snake = try l.snake(try l.name("decoder.model.{d}.alpha", .{tail}), out_channels); + { + const v = try l.folded( + try l.name("decoder.model.{d}.conv.parametrizations.weight.original0", .{tail + 1}), + try l.name("decoder.model.{d}.conv.parametrizations.weight.original1", .{tail + 1}), + &[_]u64{ 1, out_channels, 7 }, + ); + defer gpa.free(v); + // [1][96][7] -> [7][96], the rows the output kernel walks + var t: [7 * out_channels]f32 = undefined; + for (0..out_channels) |c| { + for (0..7) |tap| t[tap * out_channels + c] = v[c * 7 + tap]; + } + w.out_conv = try l.stage.halves(&t); + } + w.out_conv_b = try l.half(try l.name("decoder.model.{d}.conv.bias", .{tail + 1}), &[_]u64{1}); + + const rope = try ropeTable(gpa, max_frames); + defer gpa.free(rope); + w.rope = try l.stage.halves(rope); + return w; + } +}; + +test "transposed-conv taps reproduce ConvTranspose1d with the causal trim" { + // cin 2, cout 1, stride 2, kernel 4: direct definition vs the GEMM's two-tap form + const cin = 2; + const cout = 1; + const s = 2; + const k = 4; + const w = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; // [cin][cout][k] + const x = [_][cin]f32{ .{ 1, -1 }, .{ 2, 0.5 }, .{ -3, 4 } }; // [L][cin] + const taps = try transposedTaps(std.testing.allocator, &w, cin, cout, s, k); + defer std.testing.allocator.free(taps); + for (0..x.len) |q| { + for (0..s) |j| { + // reference: y[p] = sum over i, kk with p = i * s + kk, of x[i] * w[ci][0][kk] + const pos = q * s + j; + var want: f32 = 0; + for (0..x.len) |i| { + for (0..k) |kk| { + if (i * s + kk != pos) continue; + for (0..cin) |ci| want += x[i][ci] * w[ci * k + kk]; + } + } + var got: f32 = 0; + for (0..2) |tap| { + if (tap == 0 and q == 0) continue; + const row = if (tap == 0) q - 1 else q; + for (0..cin) |ci| got += x[row][ci] * taps[(j * cout * 2 + tap) * cin + ci]; + } + try std.testing.expectEqual(want, got); + } + } +} + +test "weight norm folds per output row and bf16 rounding ties to even" { + var v = [_]f32{ 3, 4, 0, 5 }; + try foldWeightNorm(&v, &.{ 10, 2 }); + try std.testing.expectEqualSlices(f32, &.{ 6, 8, 0, 2 }, &v); + // 1 + 2^-8 is halfway between bf16 neighbours 1 and 1 + 2^-7: ties to the even 1 + try std.testing.expectEqual(@as(f32, 1.0), bf16Round(1.0 + 1.0 / 256.0)); + try std.testing.expectEqual(@as(f32, 1.0 + 1.0 / 64.0), bf16Round(1.0 + 3.0 / 256.0)); +} + +test "weight norm preserves FP16 rounding across the CUDA reduction boundary" { + // Synthetic values: an FP64 sum changes this folded weight by one FP16 ULP. + var state: u32 = 689124668; + var v: [257]f32 = undefined; + for (&v) |*value| { + state = state *% 1664525 +% 1013904223; + value.* = @as(f32, @floatFromInt(state >> 8)) / 8388608.0 - 1.0; + } + try foldWeightNorm(&v, &.{1}); + try std.testing.expectEqual(@as(u16, 0xab13), halfBits(v[105])); +} diff --git a/zig/src/families/drama/codec_pth.zig b/zig/src/families/drama/codec_pth.zig new file mode 100644 index 00000000000..d470ddbcacf --- /dev/null +++ b/zig/src/families/drama/codec_pth.zig @@ -0,0 +1,550 @@ +//! codec.pth read without Python: the zip's stored members and a pickle VM limited to weights_only's allow-list. + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const DType = enum { f64, f32, f16, bf16, i64, i32, i16, i8, u8, bool }; + +pub fn elementBytes(t: DType) usize { + return switch (t) { + .f64, .i64 => 8, + .f32, .i32 => 4, + .f16, .bf16, .i16 => 2, + .i8, .u8, .bool => 1, + }; +} + +/// torch's legacy storage class names, as torch.save pickles them. +fn storageType(name: []const u8) ?DType { + const table = [_]struct { []const u8, DType }{ + .{ "DoubleStorage", .f64 }, .{ "FloatStorage", .f32 }, .{ "HalfStorage", .f16 }, + .{ "BFloat16Storage", .bf16 }, .{ "LongStorage", .i64 }, .{ "IntStorage", .i32 }, + .{ "ShortStorage", .i16 }, .{ "CharStorage", .i8 }, .{ "ByteStorage", .u8 }, + .{ "BoolStorage", .bool }, + }; + for (table) |e| if (std.mem.eql(u8, e[0], name)) return e[1]; + return null; +} + +/// One state-dict entry: a view into the storage member `data/`. +pub const Tensor = struct { + dtype: DType, + storage: []const u8, + storage_numel: u64, + offset: u64, // elements + shape: []const u64, + stride: []const u64, +}; + +const Member = struct { local: u64, size: u64, crc: u32 }; + +pub const Archive = struct { + arena: std.heap.ArenaAllocator, + io: std.Io, + file: std.Io.File, + members: std.StringHashMapUnmanaged(Member), + tensors: std.StringHashMapUnmanaged(Tensor), + /// The archive's top directory with its slash ("/"), as torch.save names it. + prefix: []const u8, + + pub fn open(gpa: Allocator, io: std.Io, path: []const u8) !Archive { + var arena = std.heap.ArenaAllocator.init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + errdefer file.close(io); + const members = try readDirectory(a, io, file); + var pickle_name: ?[]const u8 = null; + var it = members.iterator(); + while (it.next()) |e| { + if (!std.mem.endsWith(u8, e.key_ptr.*, "/data.pkl")) continue; + if (pickle_name != null) return error.BadArchive; + pickle_name = e.key_ptr.*; + } + const name = pickle_name orelse return error.BadArchive; + const prefix = name[0 .. name.len - "data.pkl".len]; + const order_name = try std.mem.concat(a, u8, &.{ prefix, "byteorder" }); + if (members.get(order_name)) |m| { + if (m.size > 16) return error.BadArchive; + const order = try a.alloc(u8, @intCast(m.size)); + try readMember(io, file, m, order); + if (!std.mem.eql(u8, order, "little")) return error.BigEndianArchive; + } + const pm = members.get(name).?; + if (pm.size > 64 << 20) return error.BadArchive; + const pickle = try a.alloc(u8, @intCast(pm.size)); + try readMember(io, file, pm, pickle); + const tensors = try unpickle(a, pickle); + return .{ .arena = arena, .io = io, .file = file, .members = members, .tensors = tensors, .prefix = prefix }; + } + + pub fn close(self: *Archive) void { + self.file.close(self.io); + self.arena.deinit(); + self.* = undefined; + } + + pub fn tensor(self: *const Archive, name: []const u8) !Tensor { + return self.tensors.get(name) orelse { + std.log.err("codec.pth has no tensor {s}", .{name}); + return error.MissingTensor; + }; + } + + /// name's float32 elements row-major (caller frees), its shape and its storage member's CRC-32 checked. + pub fn readF32(self: *const Archive, gpa: Allocator, name: []const u8, shape: []const u64) ![]f32 { + const t = try self.tensor(name); + if (t.dtype != .f32) { + std.log.err("codec.pth tensor {s} is {s}, not float32", .{ name, @tagName(t.dtype) }); + return error.UnexpectedDType; + } + if (!std.mem.eql(u64, t.shape, shape)) { + std.log.err("codec.pth tensor {s} has shape {any}, expected {any}", .{ name, t.shape, shape }); + return error.ShapeMismatch; + } + var numel: u64 = 1; + var i = t.shape.len; + while (i > 0) { + i -= 1; + if (t.shape[i] != 1 and t.stride[i] != numel) return error.NonContiguousTensor; + numel *= t.shape[i]; + } + if (t.offset > t.storage_numel or numel > t.storage_numel - t.offset) return error.BadArchive; + const key = try std.fmt.allocPrint(gpa, "{s}data/{s}", .{ self.prefix, t.storage }); + defer gpa.free(key); + const m = self.members.get(key) orelse return error.MissingStorage; + if (m.size != t.storage_numel * 4) return error.BadArchive; + const all = try gpa.alloc(f32, @intCast(t.storage_numel)); + errdefer gpa.free(all); + try readMember(self.io, self.file, m, std.mem.sliceAsBytes(all)); + if (t.offset == 0 and numel == all.len) return all; + const out = try gpa.dupe(f32, all[@intCast(t.offset)..][0..@intCast(numel)]); + gpa.free(all); + return out; + } +}; + +fn readU16(b: []const u8, at: usize) u16 { + return std.mem.readInt(u16, b[at..][0..2], .little); +} + +fn readU32(b: []const u8, at: usize) u32 { + return std.mem.readInt(u32, b[at..][0..4], .little); +} + +fn readU64(b: []const u8, at: usize) u64 { + return std.mem.readInt(u64, b[at..][0..8], .little); +} + +/// A stored member's bytes into `out` (exactly its size), CRC-checked. +fn readMember(io: std.Io, file: std.Io.File, m: Member, out: []u8) !void { + if (out.len != m.size) return error.BadArchive; + var head: [30]u8 = undefined; + if (try file.readPositionalAll(io, &head, m.local) != head.len) return error.ShortRead; + if (readU32(&head, 0) != 0x04034b50) return error.BadArchive; + const data: u64 = m.local + @as(u64, head.len) + @as(u64, readU16(&head, 26)) + @as(u64, readU16(&head, 28)); + if (try file.readPositionalAll(io, out, data) != out.len) return error.ShortRead; + if (std.hash.Crc32.hash(out) != m.crc) return error.ChecksumMismatch; +} + +/// The central directory: every member stored (method 0), zip64 records honoured. +fn readDirectory(a: Allocator, io: std.Io, file: std.Io.File) !std.StringHashMapUnmanaged(Member) { + const size = try file.length(io); + if (size < 22) return error.BadArchive; + const tail_len: usize = @intCast(@min(size, 22 + 0xFFFF)); + const tail = try a.alloc(u8, tail_len); + if (try file.readPositionalAll(io, tail, size - @as(u64, tail_len)) != tail_len) return error.ShortRead; + var at: usize = tail_len - 22; + while (readU32(tail, at) != 0x06054b50) { + if (at == 0) return error.BadArchive; + at -= 1; + } + var count: u64 = readU16(tail, at + 10); + var cd_size: u64 = readU32(tail, at + 12); + var cd_off: u64 = readU32(tail, at + 16); + if (count == 0xFFFF or cd_size == 0xFFFFFFFF or cd_off == 0xFFFFFFFF) { + if (at < 20 or readU32(tail, at - 20) != 0x07064b50) return error.BadArchive; + var rec: [56]u8 = undefined; + if (try file.readPositionalAll(io, &rec, readU64(tail, at - 20 + 8)) != rec.len) return error.ShortRead; + if (readU32(&rec, 0) != 0x06064b50) return error.BadArchive; + count = readU64(&rec, 32); + cd_size = readU64(&rec, 40); + cd_off = readU64(&rec, 48); + } + if (cd_size > 64 << 20 or cd_off > size or cd_size > size - cd_off) return error.BadArchive; + const cd = try a.alloc(u8, @intCast(cd_size)); + if (try file.readPositionalAll(io, cd, cd_off) != cd.len) return error.ShortRead; + var members: std.StringHashMapUnmanaged(Member) = .empty; + var p: usize = 0; + var n: u64 = 0; + while (n < count) : (n += 1) { + if (cd.len - p < 46 or readU32(cd, p) != 0x02014b50) return error.BadArchive; + const method = readU16(cd, p + 10); + const crc = readU32(cd, p + 16); + var csize: u64 = readU32(cd, p + 20); + var usize_: u64 = readU32(cd, p + 24); + const nlen: usize = readU16(cd, p + 28); + const xlen: usize = readU16(cd, p + 30); + const clen: usize = readU16(cd, p + 32); + var local: u64 = readU32(cd, p + 42); + if (cd.len - p - 46 < nlen + xlen + clen) return error.BadArchive; + const name = cd[p + 46 ..][0..nlen]; + var x = p + 46 + nlen; + const xend = x + xlen; + while (xend - x >= 4) { + const id = readU16(cd, x); + const len: usize = readU16(cd, x + 2); + if (xend - x - 4 < len) return error.BadArchive; + if (id == 0x0001) { + var f = x + 4; + const fend = f + len; + if (usize_ == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + usize_ = readU64(cd, f); + f += 8; + } + if (csize == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + csize = readU64(cd, f); + f += 8; + } + if (local == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + local = readU64(cd, f); + } + } + x += 4 + len; + } + if (method != 0 or csize != usize_) { + std.log.err("codec.pth member {s} is compressed; torch.save stores members", .{name}); + return error.CompressedMember; + } + if (local > size or usize_ > size - local) return error.BadArchive; + try members.put(a, name, .{ .local = local, .size = usize_, .crc = crc }); + p += 46 + nlen + xlen + clen; + } + return members; +} + +const GlobalRef = union(enum) { ordered_dict, rebuild_tensor_v2, storage_type: DType }; + +const Storage = struct { dtype: DType, key: []const u8, numel: u64 }; + +const Dict = struct { + keys: std.ArrayList(Value) = .empty, + values: std.ArrayList(Value) = .empty, + + fn put(d: *Dict, a: Allocator, k: Value, v: Value) !void { + try d.keys.append(a, k); + try d.values.append(a, v); + } +}; + +const Value = union(enum) { + none, + boolean: bool, + int: i64, + str: []const u8, + tuple: []const Value, + dict: *Dict, + global: GlobalRef, + storage: Storage, + tensor: *const Tensor, +}; + +const Reader = struct { + data: []const u8, + at: usize = 0, + + fn bytes(r: *Reader, n: usize) ![]const u8 { + if (r.data.len - r.at < n) return error.BadPickle; + defer r.at += n; + return r.data[r.at..][0..n]; + } + + fn byte(r: *Reader) !u8 { + return (try r.bytes(1))[0]; + } + + fn int(r: *Reader, comptime T: type) !T { + return std.mem.readInt(T, (try r.bytes(@sizeOf(T)))[0..@sizeOf(T)], .little); + } + + fn line(r: *Reader) ![]const u8 { + const end = std.mem.indexOfScalarPos(u8, r.data, r.at, '\n') orelse return error.BadPickle; + defer r.at = end + 1; + return r.data[r.at..end]; + } +}; + +fn resolveGlobal(module: []const u8, name: []const u8) !GlobalRef { + if (std.mem.eql(u8, module, "collections") and std.mem.eql(u8, name, "OrderedDict")) return .ordered_dict; + if (std.mem.eql(u8, module, "torch._utils") and std.mem.eql(u8, name, "_rebuild_tensor_v2")) return .rebuild_tensor_v2; + if (std.mem.eql(u8, module, "torch")) if (storageType(name)) |t| return .{ .storage_type = t }; + std.log.warn("codec.pth pickle names {s}.{s}, outside the tensor state-dict allow-list", .{ module, name }); + return error.ForbiddenGlobal; +} + +fn pop(stack: *std.ArrayList(Value)) !Value { + return stack.pop() orelse error.BadPickle; +} + +fn topDict(stack: *std.ArrayList(Value)) !*Dict { + if (stack.items.len == 0) return error.BadPickle; + return switch (stack.items[stack.items.len - 1]) { + .dict => |d| d, + else => error.BadPickle, + }; +} + +fn newDict(a: Allocator) !*Dict { + const d = try a.create(Dict); + d.* = .{}; + return d; +} + +fn nonNegative(v: Value) !u64 { + return switch (v) { + .int => |i| if (i < 0) error.BadPickle else @intCast(i), + else => error.BadPickle, + }; +} + +fn intTuple(a: Allocator, v: Value) ![]const u64 { + const items = switch (v) { + .tuple => |t| t, + else => return error.BadPickle, + }; + const out = try a.alloc(u64, items.len); + for (items, out) |item, *o| o.* = try nonNegative(item); + return out; +} + +/// torch.save's persistent id for a storage: ("storage", Storage, key, location, numel). +fn persistent(pid: Value) !Storage { + const t = switch (pid) { + .tuple => |t| t, + else => return error.BadPickle, + }; + if (t.len != 5) return error.BadPickle; + if (t[0] != .str or !std.mem.eql(u8, t[0].str, "storage")) return error.BadPickle; + const dtype = switch (t[1]) { + .global => |g| switch (g) { + .storage_type => |d| d, + else => return error.BadPickle, + }, + else => return error.BadPickle, + }; + if (t[2] != .str or t[3] != .str) return error.BadPickle; + return .{ .dtype = dtype, .key = t[2].str, .numel = try nonNegative(t[4]) }; +} + +fn reduce(a: Allocator, f: Value, args: Value) !Value { + const items = switch (args) { + .tuple => |t| t, + else => return error.BadPickle, + }; + const g = switch (f) { + .global => |g| g, + else => return error.BadPickle, + }; + switch (g) { + .ordered_dict => { + if (items.len != 0) return error.BadPickle; + return .{ .dict = try newDict(a) }; + }, + .rebuild_tensor_v2 => { + // (storage, storage_offset, size, stride, requires_grad, backward_hooks[, metadata]) + if (items.len < 6 or items.len > 7) return error.BadPickle; + const st = switch (items[0]) { + .storage => |s| s, + else => return error.BadPickle, + }; + const shape = try intTuple(a, items[2]); + const stride = try intTuple(a, items[3]); + if (shape.len != stride.len) return error.BadPickle; + if (items[4] != .boolean) return error.BadPickle; + switch (items[5]) { + .dict => |d| if (d.keys.items.len != 0) return error.BadPickle, + else => return error.BadPickle, + } + const t = try a.create(Tensor); + t.* = .{ .dtype = st.dtype, .storage = st.key, .storage_numel = st.numel, .offset = try nonNegative(items[1]), .shape = shape, .stride = stride }; + return .{ .tensor = t }; + }, + .storage_type => return error.BadPickle, + } +} + +/// The state dict's tensors by name. Unknown opcodes and globals are refused, never run. +fn unpickle(a: Allocator, data: []const u8) !std.StringHashMapUnmanaged(Tensor) { + var stack: std.ArrayList(Value) = .empty; + var marks: std.ArrayList(usize) = .empty; + var memo: std.AutoHashMapUnmanaged(u32, Value) = .empty; + var r: Reader = .{ .data = data }; + while (true) { + const op = try r.byte(); + switch (op) { + 0x80 => { // PROTO + const v = try r.byte(); + if (v < 2 or v > 5) return error.UnsupportedPickle; + }, + '}' => try stack.append(a, .{ .dict = try newDict(a) }), // EMPTY_DICT + ')' => try stack.append(a, .{ .tuple = &.{} }), // EMPTY_TUPLE + '(' => try marks.append(a, stack.items.len), // MARK + 't' => { // TUPLE + const at = marks.pop() orelse return error.BadPickle; + if (at > stack.items.len) return error.BadPickle; + const items = try a.dupe(Value, stack.items[at..]); + stack.shrinkRetainingCapacity(at); + try stack.append(a, .{ .tuple = items }); + }, + 0x85, 0x86, 0x87 => { // TUPLE1, TUPLE2, TUPLE3 + const n: usize = op - 0x84; + if (stack.items.len < n) return error.BadPickle; + const at = stack.items.len - n; + const items = try a.dupe(Value, stack.items[at..]); + stack.shrinkRetainingCapacity(at); + try stack.append(a, .{ .tuple = items }); + }, + 'X' => try stack.append(a, .{ .str = try r.bytes(try r.int(u32)) }), // BINUNICODE + 0x8c => try stack.append(a, .{ .str = try r.bytes(try r.byte()) }), // SHORT_BINUNICODE + 'c' => { // GLOBAL + const module = try r.line(); + const name = try r.line(); + try stack.append(a, .{ .global = try resolveGlobal(module, name) }); + }, + 'K' => try stack.append(a, .{ .int = try r.byte() }), // BININT1 + 'M' => try stack.append(a, .{ .int = try r.int(u16) }), // BININT2 + 'J' => try stack.append(a, .{ .int = try r.int(i32) }), // BININT + 0x8a => { // LONG1 + const n = try r.byte(); + if (n > 8) return error.UnsupportedPickle; + const b = try r.bytes(n); + var v: i64 = 0; + if (n > 0) { + var buf: [8]u8 = if (b[n - 1] & 0x80 != 0) @splat(0xFF) else @splat(0); + @memcpy(buf[0..n], b); + v = std.mem.readInt(i64, &buf, .little); + } + try stack.append(a, .{ .int = v }); + }, + 'N' => try stack.append(a, .none), + 0x88 => try stack.append(a, .{ .boolean = true }), // NEWTRUE + 0x89 => try stack.append(a, .{ .boolean = false }), // NEWFALSE + 'q', 'r' => { // BINPUT, LONG_BINPUT + const key: u32 = if (op == 'q') try r.byte() else try r.int(u32); + if (stack.items.len == 0) return error.BadPickle; + try memo.put(a, key, stack.items[stack.items.len - 1]); + }, + 'h', 'j' => { // BINGET, LONG_BINGET + const key: u32 = if (op == 'h') try r.byte() else try r.int(u32); + try stack.append(a, memo.get(key) orelse return error.BadPickle); + }, + 'Q' => try stack.append(a, .{ .storage = try persistent(try pop(&stack)) }), // BINPERSID + 'R' => { // REDUCE + const args = try pop(&stack); + const f = try pop(&stack); + try stack.append(a, try reduce(a, f, args)); + }, + 's' => { // SETITEM + const v = try pop(&stack); + const k = try pop(&stack); + try (try topDict(&stack)).put(a, k, v); + }, + 'u' => { // SETITEMS + const at = marks.pop() orelse return error.BadPickle; + if (at == 0 or at > stack.items.len) return error.BadPickle; + const d = switch (stack.items[at - 1]) { + .dict => |d| d, + else => return error.BadPickle, + }; + const items = stack.items[at..]; + if (items.len % 2 != 0) return error.BadPickle; + var i: usize = 0; + while (i < items.len) : (i += 2) try d.put(a, items[i], items[i + 1]); + stack.shrinkRetainingCapacity(at); + }, + 'b' => { // BUILD: the state dict's _metadata attribute, not needed to read tensors + switch (try pop(&stack)) { + .dict, .none => {}, + else => return error.BadPickle, + } + _ = try topDict(&stack); + }, + '.' => { // STOP + const root = switch (try pop(&stack)) { + .dict => |d| d, + else => return error.BadPickle, + }; + var out: std.StringHashMapUnmanaged(Tensor) = .empty; + for (root.keys.items, root.values.items) |k, v| { + if (k != .str or v != .tensor) return error.BadPickle; + const gop = try out.getOrPut(a, k.str); + if (gop.found_existing) return error.BadPickle; + gop.value_ptr.* = v.tensor.*; + } + return out; + }, + else => { + std.log.warn("codec.pth pickle opcode 0x{x:0>2} is outside the state-dict subset", .{op}); + return error.UnsupportedPickle; + }, + } + } +} + +test "the state-dict VM reads torch.save's tensor records and their views" { + // A protocol-2 state-dict pickle as torch.save writes it, built by a Python pickler without torch. + const fixture = [_]u8{ + 0x80, 0x02, 0x63, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x0a, 0x4f, + 0x72, 0x64, 0x65, 0x72, 0x65, 0x64, 0x44, 0x69, 0x63, 0x74, 0x0a, 0x71, 0x00, 0x29, 0x52, 0x71, + 0x01, 0x28, 0x58, 0x08, 0x00, 0x00, 0x00, 0x61, 0x2e, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x71, + 0x02, 0x63, 0x74, 0x6f, 0x72, 0x63, 0x68, 0x2e, 0x5f, 0x75, 0x74, 0x69, 0x6c, 0x73, 0x0a, 0x5f, + 0x72, 0x65, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x5f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x5f, 0x76, + 0x32, 0x0a, 0x71, 0x03, 0x28, 0x28, 0x58, 0x07, 0x00, 0x00, 0x00, 0x73, 0x74, 0x6f, 0x72, 0x61, + 0x67, 0x65, 0x71, 0x04, 0x63, 0x74, 0x6f, 0x72, 0x63, 0x68, 0x0a, 0x46, 0x6c, 0x6f, 0x61, 0x74, + 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x0a, 0x71, 0x05, 0x58, 0x01, 0x00, 0x00, 0x00, 0x30, + 0x71, 0x06, 0x58, 0x03, 0x00, 0x00, 0x00, 0x63, 0x70, 0x75, 0x71, 0x07, 0x4b, 0x06, 0x74, 0x71, + 0x08, 0x51, 0x4b, 0x00, 0x4b, 0x02, 0x4b, 0x03, 0x86, 0x71, 0x09, 0x4b, 0x03, 0x4b, 0x01, 0x86, + 0x71, 0x0a, 0x89, 0x68, 0x00, 0x29, 0x52, 0x71, 0x0b, 0x74, 0x71, 0x0c, 0x52, 0x71, 0x0d, 0x58, + 0x06, 0x00, 0x00, 0x00, 0x61, 0x2e, 0x62, 0x69, 0x61, 0x73, 0x71, 0x0e, 0x68, 0x03, 0x28, 0x28, + 0x68, 0x04, 0x68, 0x05, 0x68, 0x06, 0x68, 0x07, 0x4b, 0x06, 0x74, 0x71, 0x0f, 0x51, 0x4b, 0x04, + 0x4b, 0x02, 0x85, 0x71, 0x10, 0x4b, 0x01, 0x85, 0x71, 0x11, 0x89, 0x68, 0x00, 0x29, 0x52, 0x71, + 0x12, 0x74, 0x71, 0x13, 0x52, 0x71, 0x14, 0x58, 0x01, 0x00, 0x00, 0x00, 0x62, 0x71, 0x15, 0x68, + 0x03, 0x28, 0x28, 0x68, 0x04, 0x63, 0x74, 0x6f, 0x72, 0x63, 0x68, 0x0a, 0x42, 0x46, 0x6c, 0x6f, + 0x61, 0x74, 0x31, 0x36, 0x53, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x0a, 0x71, 0x16, 0x58, 0x01, + 0x00, 0x00, 0x00, 0x31, 0x71, 0x17, 0x68, 0x07, 0x4d, 0x2c, 0x01, 0x74, 0x71, 0x18, 0x51, 0x4b, + 0x00, 0x4d, 0x2c, 0x01, 0x85, 0x71, 0x19, 0x68, 0x11, 0x89, 0x68, 0x00, 0x29, 0x52, 0x71, 0x1a, + 0x74, 0x71, 0x1b, 0x52, 0x71, 0x1c, 0x75, 0x7d, 0x71, 0x1d, 0x58, 0x09, 0x00, 0x00, 0x00, 0x5f, + 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x71, 0x1e, 0x68, 0x00, 0x29, 0x52, 0x71, 0x1f, + 0x28, 0x58, 0x00, 0x00, 0x00, 0x00, 0x71, 0x20, 0x7d, 0x71, 0x21, 0x58, 0x07, 0x00, 0x00, 0x00, + 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x71, 0x22, 0x4b, 0x01, 0x73, 0x58, 0x01, 0x00, 0x00, + 0x00, 0x61, 0x71, 0x23, 0x7d, 0x71, 0x24, 0x68, 0x22, 0x4b, 0x02, 0x73, 0x75, 0x73, 0x62, 0x2e, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const tensors = try unpickle(arena.allocator(), &fixture); + try std.testing.expectEqual(@as(u32, 3), tensors.count()); + const w = tensors.get("a.weight").?; + try std.testing.expectEqual(DType.f32, w.dtype); + try std.testing.expectEqualStrings("0", w.storage); + try std.testing.expectEqual(@as(u64, 6), w.storage_numel); + try std.testing.expectEqualSlices(u64, &.{ 2, 3 }, w.shape); + try std.testing.expectEqualSlices(u64, &.{ 3, 1 }, w.stride); + const b = tensors.get("a.bias").?; + try std.testing.expectEqual(@as(u64, 4), b.offset); + try std.testing.expectEqualSlices(u64, &.{2}, b.shape); + const c = tensors.get("b").?; + try std.testing.expectEqual(DType.bf16, c.dtype); + try std.testing.expectEqual(@as(u64, 300), c.storage_numel); + try std.testing.expectEqualSlices(u64, &.{300}, c.shape); +} + +test "the state-dict VM refuses globals outside the allow-list" { + // PROTO 2; GLOBAL os.system; STOP + const evil = "\x80\x02cos\nsystem\n."; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expectError(error.ForbiddenGlobal, unpickle(arena.allocator(), evil)); +} diff --git a/zig/src/families/drama/root.zig b/zig/src/families/drama/root.zig new file mode 100644 index 00000000000..f8860d0ee9d --- /dev/null +++ b/zig/src/families/drama/root.zig @@ -0,0 +1,12 @@ +//! Drama 3's native CUDA backbone, temporal codebook tower and speech codec. +pub const backbone = @import("backbone.zig"); +pub const tower = @import("tower.zig"); +pub const codec = @import("codec.zig"); + +test { + _ = backbone; + _ = tower; + _ = codec; + _ = @import("codec_pth.zig"); + _ = @import("codec_load.zig"); +} diff --git a/zig/src/families/drama/tower.zig b/zig/src/families/drama/tower.zig new file mode 100644 index 00000000000..445b4cf2c98 --- /dev/null +++ b/zig/src/families/drama/tower.zig @@ -0,0 +1,540 @@ +//! Drama 3's temporal codebook tower: four shared and nine residual layers whose caches keep every earlier row. +const std = @import("std"); +const cuda = @import("cuda"); +const checkpoint = @import("core").checkpoint; +const Buffer = cuda.DeviceBuffer; +const Linear = cuda.cublaslt.Linear; +const Allocator = std.mem.Allocator; + +pub const Frame = [11]u32; +pub const Options = struct { context: usize = 8192, max_rows: usize = 128 }; +pub const Sampling = struct { temperature: f32 = 1, top_p: f32 = 0.9, top_k: u32 = 30 }; +const hidden = 2048; +const intermediate = 6144; +const query_width = 4096; +const kv_width = 512; +const qkv_width = 9216; +const layer_count = 13; +const workspace_bytes = 8 << 20; +const sample_shared_bytes = 65536; +/// drama_tower.cu's attention_split: the CTAs of drama_attention_decode's cluster for one query head. +const attention_split = 4; +/// Clusters are sm_90+: below it the image holds no drama_attention_decode, and the decode row runs drama_attention. +fn clusters(capability: u32) bool { + return capability >= 90; +} +const projections = [_][2]usize{ + .{ hidden, 2 * hidden }, .{ qkv_width, hidden }, .{ hidden, query_width }, + .{ 2 * intermediate, hidden }, .{ hidden, intermediate }, .{ 4096, hidden }, +}; + +/// Diagnostic capture points of Model.prefillTraced in execution order, BF16 [rows][stageWidth(stage)] each. +pub const Stage = enum { + shared_input, + joined, + mixed, + attention_input, + qkv, + query, + key, + value, + attended, + attention_output, + mlp_input, + mlp_residual, + gate_up, + activated, + mlp_output, + output, +}; + +pub fn stageWidth(stage: Stage) usize { + return switch (stage) { + .shared_input, .mixed, .attention_input, .attention_output, .mlp_input, .mlp_residual, .mlp_output, .output => hidden, + .joined => 2 * hidden, + .qkv => qkv_width, + .query, .attended => query_width, + .key, .value => kv_width, + .gate_up => 2 * intermediate, + .activated => intermediate, + }; +} + +/// Hashed by the trace driver so a capture names the exact tower it observed; unreferenced in production. +pub const trace_source = @embedFile("tower.zig"); + +const Config = struct { + model_type: []const u8, + semantic_start_token_id: u32, + semantic_end_token_id: u32, + eos_token_id: u32, + audio_decoder_config: struct { + decoder_type: []const u8, + dim: usize, + intermediate_size: usize, + n_head: usize, + n_local_heads: usize, + head_dim: usize, + shared_enrichment_layers: usize, + num_codebooks: usize, + vocab_size: usize, + vq_backbone_codebooks: usize, + rotary_percent: f32, + rotary_interleaved: bool, + rope_base: f32, + norm_eps: f32, + attention_output_gate: bool, + layernorm_zero_centered_gamma: bool, + }, +}; + +const Layer = struct { + embedding: Buffer, + enorm: Buffer, + hnorm: Buffer, + eh: Buffer, + input_norm: Buffer, + qkv: Buffer, + qnorm: Buffer, + knorm: Buffer, + out: Buffer, + post_norm: Buffer, + gate_up: Buffer, + down: Buffer, + final_norm: Buffer, +}; +const Kernels = struct { + embeddings: cuda.Function, + mix: cuda.Function, + norm: cuda.Function, + rope: cuda.Function, + attention: cuda.Function, + attention_decode: ?cuda.Function, + silu: cuda.Function, + sample: cuda.Function, + fn resolve(m: cuda.Module, capability: u32) !Kernels { + return .{ + .embeddings = try m.function("drama_frame_embeddings"), + .mix = try m.function("drama_mix"), + .norm = try m.function("drama_norm"), + .rope = try m.function("drama_rope_cache"), + .attention = try m.function("drama_attention"), + .attention_decode = if (clusters(capability)) try m.function("drama_attention_decode") else null, + .silu = try m.function("drama_silu_mul"), + .sample = try m.function("drama_sample"), + }; + } +}; + +const Impl = struct { + gpa: Allocator, + driver: *const cuda.Driver, + options: Options, + semantic_start: u32, + semantic_end: u32, + eos: u32, + eps: f32, + rope_base: f32, + buffers: std.ArrayList(Buffer) = .empty, + plans: std.ArrayList(Linear) = .empty, + module: ?cuda.Module = null, + library: cuda.cublaslt.Library = undefined, + library_open: bool = false, + kernels: Kernels = undefined, + layers: [layer_count]Layer = undefined, + heads: [9]Buffer = undefined, + embeddings: Buffer = undefined, + workspace: Buffer = undefined, + cache: Buffer = undefined, + input_frames: Buffer = undefined, + labels: Buffer = undefined, + extra: Buffer = undefined, + shared: Buffer = undefined, + joined: Buffer = undefined, + mixed: Buffer = undefined, + normalized: Buffer = undefined, + qkv: Buffer = undefined, + queries: Buffer = undefined, + attended: Buffer = undefined, + branch: Buffer = undefined, + residual: Buffer = undefined, + gate_up: Buffer = undefined, + activated: Buffer = undefined, + output_hidden: Buffer = undefined, + head_logits: Buffer = undefined, + result: Buffer = undefined, + position: usize = 0, + input_rows: usize = 0, + step: u64 = 0, + seed: u64 = 0, + + fn release(p: *Impl) void { + for (p.plans.items) |*plan| plan.deinit(); + p.plans.deinit(p.gpa); + if (p.library_open) p.library.close(); + for (p.buffers.items) |*buffer| buffer.free(); + p.buffers.deinit(p.gpa); + if (p.module) |*module| module.unload(); + const gpa = p.gpa; + gpa.destroy(p); + } + + fn allocate(p: *Impl, bytes: usize) !Buffer { + var owned = try Buffer.alloc(p.driver, bytes); + errdefer owned.free(); + try p.buffers.append(p.gpa, owned); + return view(owned, 0, bytes); + } + + fn weight(p: *Impl, ck: *checkpoint.Checkpoint, name: []const u8, shape: []const usize) !Buffer { + const t = try ck.expect(name, .bf16, shape); + const out = try p.allocate(t.bytes.len); + try out.upload(0, t.bytes); + return out; + } + + fn layerWeight(p: *Impl, ck: *checkpoint.Checkpoint, prefix: []const u8, suffix: []const u8, shape: []const usize) !Buffer { + var name: [256]u8 = undefined; + return p.weight(ck, try std.fmt.bufPrint(&name, "{s}.{s}.weight", .{ prefix, suffix }), shape); + } + + fn loadLayer(p: *Impl, ck: *checkpoint.Checkpoint, i: usize) !Layer { + var name: [128]u8 = undefined; + const prefix = if (i < 4) + try std.fmt.bufPrint(&name, "audio_decoder_mtp_shared.layers.{d}", .{i}) + else + try std.fmt.bufPrint(&name, "audio_decoder_mtp.layers.{d}", .{i - 4}); + const gate_up = try p.allocate(2 * intermediate * hidden * 2); + var key: [256]u8 = undefined; + for ([_][]const u8{ "w1", "w3" }, 0..) |part, half| { + const t = try ck.expect(try std.fmt.bufPrint(&key, "{s}.transformer_layer.feed_forward.{s}.weight", .{ prefix, part }), .bf16, &.{ intermediate, hidden }); + try gate_up.upload(half * intermediate * hidden * 2, t.bytes); + } + return .{ + .embedding = try p.layerWeight(ck, prefix, if (i < 4) "semantic_embedding" else "codebook_embedding", &.{ 4096, hidden }), + .enorm = try p.layerWeight(ck, prefix, "enorm", &.{hidden}), + .hnorm = try p.layerWeight(ck, prefix, "hnorm", &.{hidden}), + .eh = try p.layerWeight(ck, prefix, "eh_proj", &.{ hidden, 2 * hidden }), + .input_norm = try p.layerWeight(ck, prefix, "transformer_layer.attention_norm", &.{hidden}), + .qkv = try p.layerWeight(ck, prefix, "transformer_layer.attention.wqkv", &.{ qkv_width, hidden }), + .qnorm = try p.layerWeight(ck, prefix, "transformer_layer.attention.q_norm", &.{256}), + .knorm = try p.layerWeight(ck, prefix, "transformer_layer.attention.k_norm", &.{256}), + .out = try p.layerWeight(ck, prefix, "transformer_layer.attention.wo", &.{ hidden, query_width }), + .post_norm = try p.layerWeight(ck, prefix, "transformer_layer.ffn_norm", &.{hidden}), + .gate_up = gate_up, + .down = try p.layerWeight(ck, prefix, "transformer_layer.feed_forward.w2", &.{ hidden, intermediate }), + .final_norm = try p.layerWeight(ck, prefix, "final_layernorm", &.{hidden}), + }; + } + + fn project(p: *Impl, stream: cuda.Stream, rows: usize, kind: usize, x: Buffer, w: Buffer, out: Buffer) !void { + const plan = &p.plans.items[(rows - 1) * projections.len + kind]; + try plan.run(x.ptr, w.ptr, out.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + } + + fn norm(p: *Impl, stream: cuda.Stream, rows: usize, x: Buffer, residual: ?Buffer, w: Buffer, out: Buffer, residual_out: ?Buffer) !void { + var a: cuda.Args = .{}; + a.add(x.ptr); + a.add(if (residual) |r| r.ptr else @as(u64, 0)); + a.add(w.ptr); + a.add(out.ptr); + a.add(if (residual_out) |r| r.ptr else @as(u64, 0)); + a.add(@as(i32, hidden)); + a.add(p.eps); + try launch(p.kernels.norm, stream, rows, 256, 0, &a); + } + + /// One layer. `trace` is `{}` in production: every `stage` call below compiles to nothing. + fn layer(p: *Impl, stream: cuda.Stream, rows: usize, i: usize, input: Buffer, labels: Buffer, trace: anytype) !void { + const w = p.layers[i]; + var a: cuda.Args = .{}; + a.add(input.ptr); + a.add(w.embedding.ptr); + a.add(labels.ptr); + a.add(if (i == 0) p.shared.ptr else @as(u64, 0)); + a.add(w.enorm.ptr); + a.add(w.hnorm.ptr); + a.add(p.joined.ptr); + a.add(@as(i32, hidden)); + a.add(@as(i32, @intCast(if (i < 4) 0 else i - 4))); + a.add(@as(i32, @intCast(p.semantic_start))); + a.add(@as(i32, @intCast(p.semantic_end))); + a.add(p.eps); + try launch(p.kernels.mix, stream, rows, 256, 0, &a); + try p.stage(trace, stream, i, rows, .joined); + try p.project(stream, rows, 0, p.joined, w.eh, p.mixed); + try p.stage(trace, stream, i, rows, .mixed); + try p.norm(stream, rows, p.mixed, null, w.input_norm, p.normalized, null); + try p.stage(trace, stream, i, rows, .attention_input); + try p.project(stream, rows, 1, p.normalized, w.qkv, p.qkv); + try p.stage(trace, stream, i, rows, .qkv); + const cache_bytes = p.options.context * kv_width * 2; + const keys = view(p.cache, i * 2 * cache_bytes, cache_bytes); + const values = view(p.cache, (i * 2 + 1) * cache_bytes, cache_bytes); + a = .{}; + a.add(p.qkv.ptr); + a.add(w.qnorm.ptr); + a.add(w.knorm.ptr); + a.add(p.queries.ptr); + a.add(keys.ptr); + a.add(values.ptr); + a.add(@as(i32, @intCast(p.position))); + a.add(@as(i32, 16)); + a.add(@as(i32, 2)); + a.add(@as(i32, 256)); + a.add(@as(i32, 64)); + a.add(p.rope_base); + a.add(p.eps); + try launch(p.kernels.rope, stream, rows * 18, 256, 0, &a); + try p.stage(trace, stream, i, rows, .query); + try p.stage(trace, stream, i, rows, .key); + try p.stage(trace, stream, i, rows, .value); + a = .{}; + a.add(p.queries.ptr); + a.add(keys.ptr); + a.add(values.ptr); + a.add(p.qkv.ptr); + a.add(p.attended.ptr); + a.add(@as(i32, @intCast(p.position))); + a.add(@as(i32, 16)); + a.add(@as(i32, 2)); + a.add(@as(i32, 256)); + const decode = if (rows == 1) p.kernels.attention_decode else null; + if (decode) |f| try launch(f, stream, 16 * attention_split, 256, 0, &a) else try launch(p.kernels.attention, stream, rows * 16, 256, 0, &a); + try p.stage(trace, stream, i, rows, .attended); + try p.project(stream, rows, 2, p.attended, w.out, p.branch); + try p.stage(trace, stream, i, rows, .attention_output); + try p.norm(stream, rows, p.branch, p.mixed, w.post_norm, p.normalized, p.residual); + try p.stage(trace, stream, i, rows, .mlp_input); + try p.stage(trace, stream, i, rows, .mlp_residual); + try p.project(stream, rows, 3, p.normalized, w.gate_up, p.gate_up); + try p.stage(trace, stream, i, rows, .gate_up); + a = .{}; + a.add(p.gate_up.ptr); + a.add(p.activated.ptr); + a.add(@as(i32, intermediate)); + a.add(@as(i32, @intCast(rows))); + try launch(p.kernels.silu, stream, (rows * intermediate + 255) / 256, 256, 0, &a); + try p.stage(trace, stream, i, rows, .activated); + try p.project(stream, rows, 4, p.activated, w.down, p.branch); + try p.stage(trace, stream, i, rows, .mlp_output); + try p.norm(stream, rows, p.branch, p.residual, w.final_norm, p.output_hidden, null); + try p.stage(trace, stream, i, rows, .output); + } + + /// One capture point, compiled out for a void trace; the tracer must finish reading on stream before returning. + inline fn stage(p: *const Impl, trace: anytype, stream: cuda.Stream, i: usize, rows: usize, comptime which: Stage) !void { + if (@TypeOf(trace) != void) { + const width = comptime stageWidth(which); + const cache_bytes = p.options.context * kv_width * 2; + const data = switch (which) { + .shared_input => p.shared, + .joined => p.joined, + .mixed => p.mixed, + .attention_input, .mlp_input => p.normalized, + .qkv => p.qkv, + .query => p.queries, + .key => view(p.cache, i * 2 * cache_bytes + p.position * width * 2, cache_bytes - p.position * width * 2), + .value => view(p.cache, (i * 2 + 1) * cache_bytes + p.position * width * 2, cache_bytes - p.position * width * 2), + .attended => p.attended, + .attention_output, .mlp_output => p.branch, + .mlp_residual => p.residual, + .gate_up => p.gate_up, + .activated => p.activated, + .output => p.output_hidden, + }; + try trace.capture(stream, i, which, view(data, 0, rows * width * 2), p.position); + } + } + + fn sample(p: *Impl, stream: cuda.Stream, logits: Buffer, is_bf16: bool, output_index: usize, sampling: Sampling) !void { + var a: cuda.Args = .{}; + a.add(logits.ptr); + a.add(@as(i32, @intFromBool(is_bf16))); + a.add(@as(i32, if (output_index == 0) 4097 else 4096)); + a.add(sampling.temperature); + a.add(@as(i32, @intCast(sampling.top_k))); + a.add(sampling.top_p); + a.add(p.seed); + a.add(p.step); + a.add(@as(i32, @intCast(output_index))); + a.add(@as(i32, @intCast(p.semantic_start))); + a.add(@as(i32, @intCast(p.eos))); + a.add(p.result.ptr + 48); + a.add(p.result.ptr); + a.add(p.result.ptr + 44); + try launch(p.kernels.sample, stream, 1, 1024, sample_shared_bytes, &a); + } +}; + +fn view(buffer: Buffer, offset: usize, bytes: usize) Buffer { + std.debug.assert(offset <= buffer.len and bytes <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = bytes, .borrowed = true }; +} +fn launch(function: cuda.Function, stream: cuda.Stream, blocks: usize, threads: u32, shared: u32, args: *cuda.Args) !void { + try cuda.launch.launch(function, .{ .grid = .{ .x = @intCast(blocks), .y = 1, .z = 1 }, .block = .{ .x = threads, .y = 1, .z = 1 }, .shared = shared }, stream, args); +} + +pub const Model = struct { + impl: *Impl, + + pub fn init(gpa: Allocator, io: std.Io, ctx: *cuda.Context, dir: []const u8, kernel_dir: []const u8, options: Options) !Model { + if (options.context == 0 or options.context > 8192 or options.max_rows == 0 or options.max_rows > 128) return error.BadTowerCapacity; + const config_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(config_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 20)); + defer gpa.free(text); + const parsed = try std.json.parseFromSlice(Config, gpa, text, .{ .ignore_unknown_fields = true }); + defer parsed.deinit(); + const c = parsed.value.audio_decoder_config; + if (!std.mem.eql(u8, parsed.value.model_type, "fish_omni") or !std.mem.eql(u8, c.decoder_type, "codebook_mtp_shared") or + c.dim != hidden or c.intermediate_size != intermediate or c.n_head != 16 or c.n_local_heads != 2 or c.head_dim != 256 or + c.shared_enrichment_layers != 4 or c.num_codebooks != 10 or c.vocab_size != 4096 or c.vq_backbone_codebooks != 1 or + c.rotary_percent != 0.25 or !c.rotary_interleaved or !c.attention_output_gate or !c.layernorm_zero_centered_gamma or + c.rope_base != 10000000 or c.norm_eps != 1e-6 or parsed.value.semantic_end_token_id -| parsed.value.semantic_start_token_id != 4095 or + parsed.value.eos_token_id >= parsed.value.semantic_start_token_id) return error.UnsupportedTowerConfig; + const p = try gpa.create(Impl); + p.* = .{ .gpa = gpa, .driver = ctx.d, .options = options, .semantic_start = parsed.value.semantic_start_token_id, .semantic_end = parsed.value.semantic_end_token_id, .eos = parsed.value.eos_token_id, .eps = c.norm_eps, .rope_base = c.rope_base }; + errdefer p.release(); + p.module = if (kernel_dir.len == 0) try cuda.Module.load(ctx.d, cuda.kernels.drama_tower) else blk: { + const kernel_path = try std.fs.path.join(gpa, &.{ kernel_dir, "drama_tower.fatbin" }); + defer gpa.free(kernel_path); + const image = try std.Io.Dir.cwd().readFileAllocOptions(io, kernel_path, gpa, .limited(1 << 26), .@"16", null); + defer gpa.free(image); + break :blk try cuda.Module.load(ctx.d, image); + }; + p.kernels = try Kernels.resolve(p.module.?, try ctx.capability()); + try p.kernels.sample.allowDynamicShared(sample_shared_bytes); + p.library = try cuda.cublaslt.Library.open(); + p.library_open = true; + try p.plans.ensureTotalCapacityPrecise(gpa, options.max_rows * projections.len); + for (1..options.max_rows + 1) |rows| for (projections) |shape| { + var plan = try Linear.init(&p.library, rows, shape[0], shape[1], .bf16, workspace_bytes); + errdefer plan.deinit(); + try p.plans.append(gpa, plan); + }; + var ck = try checkpoint.Checkpoint.openModelPrefix(gpa, io, dir, "audio_decoder"); + defer ck.close(); + p.embeddings = try p.weight(&ck, "audio_decoder.codebook_embeddings.weight", &.{ 40960, hidden }); + for (0..layer_count) |i| p.layers[i] = try p.loadLayer(&ck, i); + for (&p.heads, 0..) |*head, i| { + var name: [128]u8 = undefined; + head.* = try p.weight(&ck, try std.fmt.bufPrint(&name, "audio_decoder_mtp.heads.{d}.weight", .{i}), &.{ 4096, hidden }); + } + if (ck.unused() != 0) return error.UnusedTowerWeights; + const rows = options.max_rows; + p.workspace = try p.allocate(workspace_bytes); + p.cache = try p.allocate(layer_count * 2 * options.context * kv_width * 2); + p.input_frames = try p.allocate(rows * @sizeOf(Frame)); + p.labels = try p.allocate(rows * @sizeOf(Frame)); + p.extra = try p.allocate(rows * hidden * 2); + p.shared = try p.allocate(rows * hidden * 2); + p.joined = try p.allocate(rows * 2 * hidden * 2); + p.mixed = try p.allocate(rows * hidden * 2); + p.normalized = try p.allocate(rows * hidden * 2); + p.qkv = try p.allocate(rows * qkv_width * 2); + p.queries = try p.allocate(rows * query_width * 2); + p.attended = try p.allocate(rows * query_width * 2); + p.branch = try p.allocate(rows * hidden * 2); + p.residual = try p.allocate(rows * hidden * 2); + p.gate_up = try p.allocate(rows * 2 * intermediate * 2); + p.activated = try p.allocate(rows * intermediate * 2); + p.output_hidden = try p.allocate(rows * hidden * 2); + p.head_logits = try p.allocate(4096 * 2); + p.result = try p.allocate(48 + 16 * 4); + return .{ .impl = p }; + } + + pub fn deinit(self: *Model) void { + self.impl.release(); + self.* = undefined; + } + + pub fn reset(self: *Model, stream: cuda.Stream, prompt_tail: []const u32, seed: u64) !void { + const p = self.impl; + try stream.synchronize(); + try p.result.fill8(0, null); + var history: [16]u32 = @splat(std.math.maxInt(u32)); + const n = @min(prompt_tail.len, history.len); + @memcpy(history[history.len - n ..], prompt_tail[prompt_tail.len - n ..]); + try p.result.upload(48, std.mem.sliceAsBytes(&history)); + p.position = 0; + p.input_rows = 0; + p.step = 0; + p.seed = seed; + // Every KV position read later is rewritten first, so the cache is not cleared. + } + + /// Stages input frames before the backbone reads the rows; the codebook-1 embedding is borrowed until the next one. + pub fn setInput(self: *Model, stream: cuda.Stream, frames: []const Frame) !?Buffer { + const p = self.impl; + if (frames.len == 0 or frames.len > p.options.max_rows) return error.BadTowerRows; + var has_audio = false; + for (frames) |frame| { + if (frame[0] >= p.semantic_start and frame[0] <= p.semantic_end) has_audio = true; + for (frame[1..]) |v| if (v >= 4096) return error.InvalidCodebookIndex; + } + p.input_rows = frames.len; + if (!has_audio) { + try view(p.shared, 0, frames.len * hidden * 2).fill8(0, stream.handle); + return null; + } + try p.input_frames.upload(0, std.mem.sliceAsBytes(frames)); + var a: cuda.Args = .{}; + a.add(p.input_frames.ptr); + a.add(p.embeddings.ptr); + a.add(p.extra.ptr); + a.add(p.shared.ptr); + a.add(@as(i32, hidden)); + a.add(@as(i32, @intCast(p.semantic_start))); + a.add(@as(i32, @intCast(p.semantic_end))); + try launch(p.kernels.embeddings, stream, frames.len, 256, 0, &a); + return view(p.extra, 0, frames.len * hidden * 2); + } + + /// Teacher-forces every prompt row but the last, whose tower pass uses generate()'s first sampled token. + pub fn prefill(self: *Model, stream: cuda.Stream, hidden_rows: Buffer, next_frames: []const Frame) !void { + return self.prefillTraced(stream, hidden_rows, next_frames, {}); + } + + /// prefill with stage captures: trace is {} (compiled out) or a tracer reading each stage on stream before return. + pub fn prefillTraced(self: *Model, stream: cuda.Stream, hidden_rows: Buffer, next_frames: []const Frame, trace: anytype) !void { + const p = self.impl; + const n = next_frames.len; + if (n == 0 or n > p.input_rows or n > p.options.max_rows or p.position + n > p.options.context or hidden_rows.len < n * hidden * 2) return error.BadTowerRows; + try p.labels.upload(0, std.mem.sliceAsBytes(next_frames)); + try p.stage(trace, stream, 0, n, .shared_input); + for (0..layer_count) |i| try p.layer(stream, n, i, if (i == 0) hidden_rows else p.output_hidden, p.labels, trace); + try stream.synchronize(); + p.position += n; + p.input_rows = 0; + } + + pub fn generate(self: *Model, stream: cuda.Stream, semantic_logits: Buffer, hidden_row: Buffer, sampling: Sampling) !Frame { + const p = self.impl; + if (p.input_rows != 1 or p.position >= p.options.context or hidden_row.len < hidden * 2 or semantic_logits.len < 4097 * 4) return error.BadTowerRows; + if (!std.math.isFinite(sampling.temperature) or sampling.temperature < 0 or !std.math.isFinite(sampling.top_p) or + sampling.top_p <= 0 or sampling.top_p > 1 or sampling.top_k == 0 or sampling.top_k > std.math.maxInt(i32)) return error.BadSpeechSampling; + try p.sample(stream, semantic_logits, false, 0, sampling); + for (0..layer_count) |i| { + try p.layer(stream, 1, i, if (i == 0) hidden_row else p.output_hidden, p.result, {}); + if (i >= 4) { + try p.project(stream, 1, 5, p.output_hidden, p.heads[i - 4], p.head_logits); + try p.sample(stream, p.head_logits, true, i - 2, sampling); + } + } + try stream.synchronize(); + var result: [12]u32 = undefined; + try p.result.download(0, std.mem.sliceAsBytes(&result)); + if (result[11] != 0) return error.NonFiniteSpeechLogits; + p.position += 1; + p.step += 1; + p.input_rows = 0; + return result[0..11].*; + } +}; + +test "sm_89, which the backbone admits, runs the decode row without a cluster" { + try std.testing.expect(!clusters(89)); + try std.testing.expect(clusters(90) and clusters(120) and clusters(121)); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 254a8799a9e..a1f668ab914 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -11,6 +11,7 @@ const budget = @import("cuda_memory.zig"); const lane_backend = @import("cuda_bound.zig"); const snaps = @import("cuda_snaps.zig"); const nemotron_slide = @import("nemotron_slide.zig"); +const drama_host = @import("drama_host.zig"); const cuda_disk = @import("cuda_disk.zig"); const vision_offer = @import("cuda_vision_offer.zig"); @@ -22,9 +23,10 @@ pub const records = true; pub const backends: []const []const u8 = &.{"cuda"}; pub const families: []const api.Family = blk: { - var out: [registry.len + 1]api.Family = undefined; + var out: [registry.len + 2]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats }; out[registry.len] = lfm2.family; + out[registry.len + 1] = .{ .model_type = "fish_omni", .formats = &.{"fp8-block128"} }; const final = out; break :blk &final; }; @@ -57,28 +59,6 @@ fn contextWindow(requested: ?i64, native: i64, default: i64) error{ Negative, No return r; } -/// The pool now, read on the thread whose context is current; `problem` names a bad variable. -fn pool(a: Allocator, io: std.Io, ctx: *const cuda.Context, problem: *[]const u8) !?budget.Pool { - const unified = (try ctx.attribute(.integrated)) != 0; - const card = try ctx.memInfo(); - const text = if (unified) budget.procText(a, io, "/proc/meminfo") else null; - const available = budget.counts(unified, .{ .total = card.total, .available = card.free }, text) catch { - problem.* = "cannot read or parse /proc/meminfo's MemTotal and MemAvailable; refusing CUDA unified-memory admission"; - return null; - }; - const free = available.available; - const total = available.total; - const reserve = budget.reserveBytes(getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), total, unified) catch { - problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_MEMORY_RESERVE_GIB={s}: a number of GiB from {d} to the memory's size", .{ getenv("TENSORFOLD_MEMORY_RESERVE_GIB").?, budget.floor(unified).least }); - return null; - }; - const limit = budget.limitBytes(getenv("TENSORFOLD_CUDA_MEMORY_LIMIT_GB")) catch { - problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_CUDA_MEMORY_LIMIT_GB={s}: a positive number of GiB whose byte count fits in a 64-bit size", .{getenv("TENSORFOLD_CUDA_MEMORY_LIMIT_GB").?}); - return null; - }; - return .{ .free = free, .total = total, .reserve = reserve, .limit = limit, .unified = unified }; -} - fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { const u = cuda.usage(reset_peak); return .{ .active = u.device, .cache = 0, .peak = u.peak, .pinned = u.host }; @@ -211,6 +191,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c problem.* = why; return null; } + if (std.mem.eql(u8, o.model_type, "fish_omni")) return openDrama(a, gpa, io, o, problem); inline for (registry) |F| { if (std.mem.eql(u8, o.model_type, F.model_type)) return openWith(F, a, gpa, io, o, problem); } @@ -225,6 +206,32 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c return null; } +fn openDrama(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (refusals.drama(o)) |why| { + problem.* = why; + return null; + } + const window = o.context orelse 8192; + if (window < 1025 or window > 8192) { + problem.* = "Drama 3 supports --context 1025 through 8192"; + return null; + } + const device = try setting(a, o.device, "TF_CUDA_DEVICE", 0, problem) orelse return null; + const segments = try setting(a, o.segments, "TF_CUDA_SEGMENTS", 1, problem) orelse return null; + if (segments != 1) { + problem.* = "Drama 3 uses one prompt segment at a time: use --segments 1"; + return null; + } + if (getenv("TENSORFOLD_CUDA_KERNELS")) |path| if (path.len > 0 and !std.mem.eql(u8, path, "native")) { + problem.* = "Drama 3 uses embedded native kernels, not captured kernel sets: unset TENSORFOLD_CUDA_KERNELS or set it to native"; + return null; + }; + return drama_host.open(gpa, io, o.dir, "", .{ .context = @intCast(window), .device = device }) catch |e| { + problem.* = try std.fmt.allocPrint(a, "the native Drama 3 CUDA engine could not load the checkpoint ({s})", .{@errorName(e)}); + return null; + }; +} + /// The admit's refusals: no stream fits, or --parallel asks for more than the budget holds. const no_stream = "the CUDA memory budget fits no stream: one at a {d}-token window takes {d:.2} GiB, " ++ "and {d:.2} GiB is left after the model's {d:.2} GiB and the {d:.1} GiB reserve{s}; " ++ @@ -299,7 +306,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O return null; }, }; - const before = try pool(a, io, &g.ctx, problem) orelse return null; + const before = try budget.readPool(a, io, &g.ctx, problem) orelse return null; // a family split over hosts holds only its rank's share (GLM-5.3-Flash's TP) const whole = budget.weightBytes(io, o.dir); const weights = if (@hasDecl(F, "weightShare")) F.weightShare(a, io, o.dir, whole) else whole; @@ -313,7 +320,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O problem: *[]const u8, fn read(p: *anyopaque) ?u64 { const self: *@This() = @ptrCast(@alignCast(p)); - const now = (pool(self.a, self.io, self.ctx, self.problem) catch return null) orelse return null; + const now = (budget.readPool(self.a, self.io, self.ctx, self.problem) catch return null) orelse return null; return now.room(cuda.usage(false).device - self.held); } }; @@ -371,7 +378,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O return null; }; const model = cuda.usage(false).device - held0; - const after = try pool(a, io, &g.ctx, problem) orelse return null; + const after = try budget.readPool(a, io, &g.ctx, problem) orelse return null; var room = after.room(model) -| loaded.learn_bytes; var low: []const u8 = ""; // names the rank whose room bounds the streams, when it is not this one if (@hasField(@TypeOf(loaded), "peer_room")) if (loaded.peer_room) |pr| if (pr.bytes < room) { @@ -489,10 +496,11 @@ test "the lane core sees a family's prefill_step through the lane backend, so a try std.testing.expect(h.backend().vtable.prefill_step != null); } -test "every registered family and d1's decision engine are listed for capabilities" { - try std.testing.expectEqual(@as(usize, registry.len + 1), families.len); +test "every registered family, d1's decision engine and Drama 3 are listed for capabilities" { + try std.testing.expectEqual(@as(usize, registry.len + 2), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].model_type); try std.testing.expectEqualStrings("lfm2_vl", families[registry.len].model_type); + try std.testing.expectEqualStrings("fish_omni", families[registry.len + 1].model_type); } test "context windows: the family default inside the model's, 0 for the model's, never past it" { diff --git a/zig/src/native/cuda_memory.zig b/zig/src/native/cuda_memory.zig index f5da4bf7612..cde70e1ba53 100644 --- a/zig/src/native/cuda_memory.zig +++ b/zig/src/native/cuda_memory.zig @@ -1,5 +1,6 @@ //! CUDA memory admission arithmetic, and the host pool read from /proc/meminfo and validated, without a device. const std = @import("std"); +const cuda = @import("cuda"); const gib: f64 = 1 << 30; /// The bytes of the checkpoint's safetensors files: what its weights need on the device, near enough to refuse early. @@ -122,6 +123,29 @@ pub fn counts(unified: bool, card: MemInfo, text: ?[]const u8) error{HostMemoryU return card; } +/// Shared native-engine admission; the context must be current. Invalid environment settings fail closed. +pub fn readPool(a: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, problem: *[]const u8) !?Pool { + const unified = (try ctx.attribute(.integrated)) != 0; + const card = try ctx.memInfo(); + const text = if (unified) procText(a, io, "/proc/meminfo") else null; + defer if (text) |bytes| a.free(bytes); + const available = counts(unified, .{ .total = card.total, .available = card.free }, text) catch { + problem.* = "cannot read or parse /proc/meminfo's MemTotal and MemAvailable; refusing CUDA unified-memory admission"; + return null; + }; + const reserve_text = if (std.c.getenv("TENSORFOLD_MEMORY_RESERVE_GIB")) |p| std.mem.span(p) else null; + const limit_text = if (std.c.getenv("TENSORFOLD_CUDA_MEMORY_LIMIT_GB")) |p| std.mem.span(p) else null; + const reserve = reserveBytes(reserve_text, available.total, unified) catch { + problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_MEMORY_RESERVE_GIB={s}: a number of GiB from {d} to the memory's size", .{ reserve_text orelse "", floor(unified).least }); + return null; + }; + const limit = limitBytes(limit_text) catch { + problem.* = try std.fmt.allocPrint(a, "TENSORFOLD_CUDA_MEMORY_LIMIT_GB={s}: a positive number of GiB whose byte count fits in a 64-bit size", .{limit_text orelse ""}); + return null; + }; + return .{ .free = available.available, .total = available.total, .reserve = reserve, .limit = limit, .unified = unified }; +} + test "the memory plan: reserve, cap, and admission that fails closed" { const g: u64 = 1 << 30; try std.testing.expectEqual(4 * g, try reserveBytes(null, 24 * g, true)); // unified: at least 4 GiB diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 7cdf93f18f5..3752b0b8443 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -19,6 +19,17 @@ pub fn lfm2(o: api.Open) ?[]const u8 { const lfm2_vision = "--vision: LFM2 reads the checkpoint's images through its own tower without the flag; " ++ "serve it without --vision"; +/// Drama 3 serves one synthesis on one device, without the text engines' extras or flags it does not read. +pub fn drama(o: api.Open) ?[]const u8 { + if (o.tp != 1 or o.rank != 0 or (o.lanes_fixed and o.lanes != 1)) return "Drama 3 serves one synthesis on one CUDA device: use --parallel 1 and no tensor parallelism"; + if (o.slide or o.drafter != null or o.mtp_drafts != null or o.mtp_confidence != null or + (o.prompt_cache_gib != null and o.prompt_cache_gib.? != 0) or + (o.keep != null and o.keep.? != 0) or o.policy.len != 0) + return "Drama 3 does not support learned weights, speculative drafts, retained prompt caches, or text-engine policies"; + if (o.vision != null or o.precision != null or o.record != null or o.learn_conversations) return "Drama 3 reads no images or NVFP4 checkpoints and keeps no rows or conversation states: serve it without --vision, --precision, --record and --learn-conversations"; + return null; +} + /// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron; null: `o` may open `F`. pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) return "--drafter loads a separate drafter, and this CUDA family drafts with its own MTP head: serve without --drafter"; @@ -68,3 +79,10 @@ test "--learn-conversations opens Nemotron only, the one CUDA family whose state try std.testing.expectStringStartsWith(family(Other, .{ .dir = "d", .model_type = "m", .learn_conversations = true }) orelse "", "--learn-conversations keeps"); try std.testing.expect(family(nemotron.native, .{ .dir = "d", .model_type = "nemotron_h", .learn_conversations = true }) == null); } + +test "Drama 3 refuses tensor parallelism, the text engines' extras and the flags it does not read" { + try std.testing.expect(drama(.{ .dir = "d", .model_type = "fish_omni" }) == null); + try std.testing.expectStringStartsWith(drama(.{ .dir = "d", .model_type = "fish_omni", .tp = 2 }) orelse "", "Drama 3 serves one synthesis"); + try std.testing.expectStringStartsWith(drama(.{ .dir = "d", .model_type = "fish_omni", .drafter = "/x" }) orelse "", "Drama 3 does not support"); + try std.testing.expectStringStartsWith(drama(.{ .dir = "d", .model_type = "fish_omni", .vision = .{} }) orelse "", "Drama 3 reads no images"); +} diff --git a/zig/src/native/drama_host.zig b/zig/src/native/drama_host.zig new file mode 100644 index 00000000000..59365b26a5f --- /dev/null +++ b/zig/src/native/drama_host.zig @@ -0,0 +1,473 @@ +//! Drama 3 speech for the native server: one synthesis at a time on a worker thread that owns the CUDA context. +const std = @import("std"); +const cuda = @import("cuda"); +const api = @import("engine_api"); +const drama = @import("drama"); +const budget = @import("cuda_memory.zig"); +const Allocator = std.mem.Allocator; + +const Frame = drama.tower.Frame; +const Codes = [10]u32; + +/// Backbone and tower rows a prompt pass takes at most. +const chunk_rows = 128; +/// Generation steps a request may take at most, the end-of-speech step included. +const max_frames = 1024; +/// Prompt tokens a request may carry at most, whatever the context. +const prompt_cap = 4096; +const min_context = max_frames + 1; +const max_context = 8192; +/// The tower's hidden width, which every backbone row it reads must have. +const tower_hidden = 2048; +/// Semantic logits a backbone row carries: EOS first, then the 4096 codes. +const logit_cols = drama.backbone.weights.head_cols; +const sample_rate = 44100; +const frame_length = 2048; +/// Frames a streamed request decodes together after its first, which is decoded alone for the earliest audio. +const stream_chunk_frames = 4; + +pub const Options = struct { + context: usize = 8192, + device: u32 = 0, +}; + +const Job = struct { + id: api.Id, + request: *const api.SpeechRequest, + sink: api.Sink, +}; + +const Host = struct { + gpa: Allocator, + io: std.Io, + context: usize, + driver: cuda.Driver = undefined, + ctx: cuda.Context = undefined, + stream: cuda.Stream = undefined, + backbone: drama.backbone.Model = undefined, + tower: drama.tower.Model = undefined, + codec: drama.codec.Model = undefined, + info_: api.Info = .{}, + startup: []u8 = &.{}, + previous_allocation_limit: ?u64 = null, + semantic_start: u32 = 0, + semantic_end: u32 = 0, + eos: u32 = 0, + thread: ?std.Thread = null, + + // Worker-thread only: the prompt pass's frames and the generated codes, sized once at open. + frames: [chunk_rows + 1]Frame = undefined, + codes: [max_frames]Codes = undefined, + + // Under `mutex`: the one admitted request and what status reports of it. + mutex: std.Io.Mutex = .init, + wake: std.Io.Condition = .init, + slot: ?Job = null, + running: bool = false, + cancelled: bool = false, + closing: bool = false, + live_prompt: u64 = 0, + live_frames: u64 = 0, + decode_began: ?i96 = null, + prefill_rate: f64 = 0, + prefill_at: i96 = 0, + + const window_ns: i96 = 2 * std.time.ns_per_s; + + const vtable: api.Engine.VTable = .{ + .info = infoFn, + .submit = submitFn, + .cancel = cancelFn, + .status = statusFn, + .memory = memoryFn, + .submit_speech = submitSpeechFn, + }; + + fn engine(h: *Host) api.Engine { + return .{ .ctx = h, .vtable = &vtable }; + } + + fn self(ctx: *anyopaque) *Host { + return @ptrCast(@alignCast(ctx)); + } + + fn lock(h: *Host) void { + h.mutex.lockUncancelable(h.io); + } + + fn unlock(h: *Host) void { + h.mutex.unlock(h.io); + } + + fn now(h: *Host) i96 { + return std.Io.Clock.awake.now(h.io).toNanoseconds(); + } + + fn infoFn(ctx: *anyopaque) api.Info { + return self(ctx).info_; + } + + /// Speech-only: the text completion routes are refused. + fn submitFn(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Unsupported; + } + + /// Admits `request` when it fits the advertised limits and no other synthesis is admitted. + fn submitSpeechFn(ctx: *anyopaque, id: api.Id, request: *const api.SpeechRequest, sink: api.Sink) api.SpeechSubmitError!void { + const h = self(ctx); + if (!h.valid(request)) return error.InvalidRequest; + h.lock(); + defer h.unlock(); + if (h.closing) return error.Closed; + if (h.slot != null) return error.Busy; + h.slot = .{ .id = id, .request = request, .sink = sink }; + h.cancelled = false; + h.wake.signal(h.io); + } + + /// Sizes, sampling and prompt tokens a plain built-in-voice synthesis may use (immutable host fields only). + fn valid(h: *const Host, r: *const api.SpeechRequest) bool { + const speech = h.info_.speech.?; + if (r.prompt.len == 0 or r.prompt.len > speech.max_prompt_tokens) return false; + if (r.max_frames == 0 or r.max_frames > speech.max_frames) return false; + if (r.pcm.len < @as(usize, r.max_frames) * speech.frame_length) return false; + // the tower's sampler accepts exactly these (tower.generate's BadSpeechSampling) + if (!std.math.isFinite(r.temperature) or r.temperature < 0) return false; + if (!std.math.isFinite(r.top_p) or r.top_p <= 0 or r.top_p > 1) return false; + if (r.top_k == 0 or r.top_k > std.math.maxInt(i32)) return false; + for (r.prompt) |t| { + if (t >= drama.backbone.config.vocab) return false; + if (t >= h.semantic_start and t <= h.semantic_end) return false; // plain prompts carry no audio rows + } + return true; + } + + /// Ends the admitted request at its next prompt chunk, frame or codec boundary; unknown ids are ignored. + fn cancelFn(ctx: *anyopaque, id: api.Id) void { + const h = self(ctx); + h.lock(); + defer h.unlock(); + const job = h.slot orelse return; + if (job.id != id) return; + h.cancelled = true; + h.wake.signal(h.io); + } + + /// Host counters only: HTTP threads never touch the CUDA context. + fn statusFn(ctx: *anyopaque, out: *api.Status, stream_tokens: []u32) void { + const h = self(ctx); + h.lock(); + defer h.unlock(); + const t = h.now(); + var rate: f64 = 0; + if (h.running) if (h.decode_began) |began| if (t > began) { + rate = @as(f64, @floatFromInt(h.live_frames)) / (@as(f64, @floatFromInt(t - began)) / 1e9); + }; + var streams: usize = 0; + if (h.running and stream_tokens.len > 0) { + stream_tokens[0] = @intCast(h.live_prompt + h.live_frames); + streams = 1; + } + out.* = .{ + .running = @intFromBool(h.running), + .waiting = @intFromBool(h.slot != null and !h.running), + .decode_tokens_per_second = rate, + .prefill_tokens_per_second = if (t - h.prefill_at <= window_ns) h.prefill_rate else 0, + .preemptions = 0, + .streams = streams, + .generation_tokens = if (h.running) h.live_frames else 0, + }; + } + + /// The process's CUDA allocation counters (atomics, not a driver query). + fn memoryFn(_: *anyopaque, reset_peak: bool) ?api.Memory { + const u = cuda.usage(reset_peak); + return .{ .active = u.device, .cache = 0, .peak = u.peak, .pinned = u.host }; + } + + /// The worker: takes the admitted request, synthesizes it, finishes it; on close, cancels what is admitted. + fn run(h: *Host) void { + // CUDA binds per thread; synthesize binds again and reports a failure there + h.ctx.makeCurrent() catch |e| std.log.err("drama: cuCtxSetCurrent on the worker thread: {s}", .{@errorName(e)}); + while (true) { + h.lock(); + while (h.slot == null and !h.closing) h.wake.waitUncancelable(h.io, &h.mutex); + const job = h.slot orelse { + h.unlock(); + return; + }; + h.running = true; + h.live_prompt = job.request.prompt.len; + h.live_frames = 0; + h.decode_began = null; + h.unlock(); + h.serve(job); + } + } + + /// True when the admitted request was cancelled or the engine is closing (read under the lock). + fn stopped(h: *Host) bool { + h.lock(); + defer h.unlock(); + return h.cancelled or h.closing; + } + + fn check(h: *Host) error{Cancelled}!void { + if (h.stopped()) return error.Cancelled; + } + + /// One synthesis to its single terminal event; nothing touches the request after `finished`. + fn serve(h: *Host, job: Job) void { + const r = job.request; + var stats: api.Stats = .{}; + const began = h.now(); + const done = h.synthesize(job, &stats, began) catch |e| { + h.stream.synchronize() catch {}; // no device work outlives the request it served + if (e == error.Cancelled) return h.finish(job, .cancelled, stats, ""); + std.log.warn("drama: synthesis {d} failed: {s}", .{ job.id, @errorName(e) }); + return h.finish(job, .failed, stats, words(e)); + }; + r.result.samples = done.samples; // published only after the full decode and the final cancellation check + h.finish(job, if (done.truncated) .length else .stop, stats, ""); + } + + /// Frees the slot (a new request may be admitted while this one's event is out), then sends `finished`. + fn finish(h: *Host, job: Job, reason: api.Reason, stats: api.Stats, message: []const u8) void { + h.lock(); + h.slot = null; + h.running = false; + h.cancelled = false; + h.live_frames = 0; + h.decode_began = null; + h.unlock(); + const event: api.Event = .{ .finished = .{ .reason = reason, .stats = stats, .message = message } }; + job.sink.event(job.sink.ctx, job.id, &event); + } + + /// Prompt, generation and codec decode into the request's PCM; at max_frames the audio so far is kept, truncated. + fn synthesize(h: *Host, job: Job, stats: *api.Stats, began: i96) !Done { + const r = job.request; + try h.check(); + try h.ctx.makeCurrent(); // CUDA binds per thread: the worker's calls need the context current + const b = &h.backbone; + const t = &h.tower; + const s = h.stream; + try b.reset(s); + try t.reset(s, r.prompt, r.seed); + + // Prompt pass: chunks staged in the tower, run through the backbone, teacher-forced but the prompt's last row. + const prompt = r.prompt; + var last: drama.backbone.Rows = undefined; + var start: usize = 0; + while (start < prompt.len) { + try h.check(); + const end = @min(start + chunk_rows, prompt.len); + const n = end - start; + const look = @min(end + 1, prompt.len); // this chunk's frames and the next row's, for its last label + for (prompt[start..look], h.frames[0 .. look - start]) |token, *frame| frame.* = plainFrame(token); + const extra = try t.setInput(s, h.frames[0..n]); + last = try b.run(s, .prefill, prompt[start..end], extra); + if (last.rows != n) return error.DramaRowsMismatch; + const taught = look - start - 1; // n inside the prompt; n - 1 in its final chunk + if (taught > 0) try t.prefill(s, last.hidden, h.frames[1 .. 1 + taught]); + // the final row's tower pass is generate's: it stages that row alone when prefill consumed the chunk + if (end == prompt.len and taught > 0) _ = try t.setInput(s, h.frames[n - 1 .. n]); + start = end; + } + const prefilled = h.now(); + stats.prefill_seconds = @as(f64, @floatFromInt(prefilled - began)) / 1e9; + h.notePrefill(prompt.len, began, prefilled); + + // Generation: each step samples a frame; a non-EOS frame is the next backbone row, max_frames steps at most. + const sampling: drama.tower.Sampling = .{ .temperature = r.temperature, .top_p = r.top_p, .top_k = r.top_k }; + var hidden = try lastRow(last.hidden, last.rows, b.hidden * 2); + var logits = try lastRow(last.semantic_logits, 1, logit_cols * 4); + var count: usize = 0; + var truncated = false; + var published: usize = 0; // frames a streamed request's caller owns + if (r.stream) h.codec.begin(); + while (true) { + try h.check(); + const frame = try t.generate(s, logits, hidden, sampling); + stats.rounds += 1; + if (frame[0] == h.eos) break; + if (frame[0] < h.semantic_start or frame[0] > h.semantic_end) return error.BadSpeechFrame; + h.codes[count] = frame[1..11].*; + count += 1; + h.noteFrames(count); + if (count == r.max_frames) { + truncated = true; + break; + } + if (r.stream and (published == 0 or count - published == stream_chunk_frames)) published = try h.publish(job, count); + h.frames[0] = frame; + const extra = try t.setInput(s, h.frames[0..1]); + const rows = try b.run(s, .decode, h.frames[0][0..1], extra); + if (rows.rows != 1) return error.DramaRowsMismatch; + hidden = try lastRow(rows.hidden, 1, b.hidden * 2); + logits = try lastRow(rows.semantic_logits, 1, logit_cols * 4); + } + if (count == 0) return error.EmptySpeech; + + try h.check(); + if (r.stream) { + if (count > published) _ = try h.publish(job, count); + return .{ .samples = count * frame_length, .truncated = truncated }; + } + const want = count * frame_length; + const samples = try h.codec.decode(s, h.codes[0..count], r.pcm); + if (samples != want) return error.CodecSampleCount; + for (r.pcm[0..samples]) |x| if (!std.math.isFinite(x)) return error.NonFiniteAudio; + try h.check(); + return .{ .samples = samples, .truncated = truncated }; + } + + /// What a finished synthesis produced: its samples, and whether it stopped at max_frames before its end of speech. + const Done = struct { samples: usize, truncated: bool }; + + /// Decodes the frames not yet decoded, checks them, then hands pcm[0..frames * 2048] over with an `audio` event. + fn publish(h: *Host, job: Job, frames: usize) !usize { + try h.check(); + const r = job.request; + const from = h.codec.decoded * frame_length; + const samples = try h.codec.advance(h.stream, h.codes[0..frames], r.pcm); + if (samples != frames * frame_length) return error.CodecSampleCount; + for (r.pcm[from..samples]) |x| if (!std.math.isFinite(x)) return error.NonFiniteAudio; + try h.check(); + const event: api.Event = .{ .audio = samples }; + job.sink.event(job.sink.ctx, job.id, &event); + return frames; + } + + fn notePrefill(h: *Host, tokens: usize, began: i96, done: i96) void { + h.lock(); + defer h.unlock(); + if (done > began) h.prefill_rate = @as(f64, @floatFromInt(tokens)) / (@as(f64, @floatFromInt(done - began)) / 1e9); + h.prefill_at = done; + h.decode_began = done; + } + + fn noteFrames(h: *Host, frames: usize) void { + h.lock(); + defer h.unlock(); + h.live_frames = frames; + } +}; + +/// A plain prompt row's frame: the text token, no codebook values. +fn plainFrame(token: u32) Frame { + var frame: Frame = @splat(0); + frame[0] = token; + return frame; +} + +/// A borrowed view of the last row; the backbone's semantic logits contain exactly one row. +fn lastRow(buffer: cuda.DeviceBuffer, rows: usize, row_bytes: usize) !cuda.DeviceBuffer { + if (rows == 0 or buffer.len != rows * row_bytes) return error.DramaRowsMismatch; + const at = (rows - 1) * row_bytes; + return .{ .d = buffer.d, .ptr = buffer.ptr + at, .len = row_bytes, .borrowed = true }; +} + +/// The failure message a finished event carries (static text: it outlives the sink call). +fn words(err: anyerror) []const u8 { + return switch (err) { + error.EmptySpeech => "the model ended speech before its first audio frame", + error.NonFiniteSpeechLogits => "the model produced non-finite speech logits", + error.NonFiniteAudio => "the codec produced non-finite audio", + error.BadSpeechFrame => "the tower sampled a token outside the semantic band", + error.CodecSampleCount => "the codec returned a sample count other than frames x frame_length", + error.DramaRowsMismatch => "the backbone returned rows other than those it was given", + error.DramaContextOverflow => "the prompt and frames do not fit the engine's context", + error.OutOfDeviceMemory => "the GPU ran out of memory during synthesis", + else => @errorName(err), + }; +} + +/// Drama 3 at `checkpoint_dir` with kernels from `kernel_dir`, served on its own worker thread; `close` joins it. +pub fn open(gpa: Allocator, io: std.Io, checkpoint_dir: []const u8, kernel_dir: []const u8, options: Options) !api.Opened { + if (options.context < min_context or options.context > max_context) return error.BadDramaContext; + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.* = .{ .gpa = gpa, .io = io, .context = options.context }; + + h.driver = try cuda.Driver.open(); + errdefer h.driver.close(); + const count = try h.driver.deviceCount(); + if (count <= 0 or options.device >= @as(u32, @intCast(count))) return error.NoSuchCudaDevice; + h.ctx = try cuda.Context.init(&h.driver, @intCast(options.device)); + errdefer h.ctx.deinit(); + h.stream = try cuda.Stream.init(&h.driver, true); + errdefer h.stream.deinit(); + var admission_arena: std.heap.ArenaAllocator = .init(gpa); + defer admission_arena.deinit(); + var admission_problem: []const u8 = ""; + const plan = try budget.readPool(admission_arena.allocator(), io, &h.ctx, &admission_problem) orelse { + std.log.err("Drama memory admission: {s}", .{admission_problem}); + return error.DramaMemoryAdmission; + }; + const used = cuda.usage(false); + const held = used.device + used.host; + h.previous_allocation_limit = try cuda.setAllocationLimit(held + plan.room(held)); + errdefer _ = cuda.setAllocationLimit(h.previous_allocation_limit) catch unreachable; + + const held0 = cuda.usage(false).device; + h.backbone = try drama.backbone.Model.init(gpa, io, &h.ctx, checkpoint_dir, kernel_dir, .{ .context = options.context, .max_rows = chunk_rows }); + errdefer h.backbone.deinit(); + h.tower = try drama.tower.Model.init(gpa, io, &h.ctx, checkpoint_dir, kernel_dir, .{ .context = options.context, .max_rows = chunk_rows }); + errdefer h.tower.deinit(); + h.codec = try drama.codec.Model.init(gpa, io, &h.ctx, checkpoint_dir, kernel_dir, .{ .max_frames = max_frames }); + errdefer h.codec.deinit(); + const model_bytes = cuda.usage(false).device -| held0; + + if (h.backbone.hidden != tower_hidden) return error.DramaHiddenMismatch; + if (h.codec.sample_rate != sample_rate or h.codec.frame_length != frame_length or h.codec.num_codebooks != 10) return error.UnsupportedDramaCodec; + h.semantic_start = h.backbone.semantic_start; + h.semantic_end = h.backbone.semantic_end; + h.eos = h.backbone.eos; + + var name_buf: [256]u8 = undefined; + const name = h.ctx.name(&name_buf) catch "GPU"; + const capability = try h.ctx.capability(); + const max_prompt: u32 = @intCast(@min(prompt_cap, options.context - max_frames)); + h.startup = try std.fmt.allocPrint(gpa, "Drama 3 on CUDA sm_{d} device {d} ({s}): models {d:.2} GiB; context {d} tokens, prompts up to {d} tokens in passes of {d} rows, up to {d} frames of {d} samples at {d} Hz; one synthesis at a time", .{ + capability, options.device, name, @as(f64, @floatFromInt(model_bytes)) / (1 << 30), options.context, max_prompt, chunk_rows, max_frames, frame_length, sample_rate, + }); + errdefer gpa.free(h.startup); + h.info_ = .{ + .name = "drama-3", + .text_generation = false, + .speech = .{ .sample_rate = sample_rate, .frame_length = frame_length, .max_frames = max_frames, .max_prompt_tokens = max_prompt }, + .lanes = 1, + .context_window = @intCast(options.context), + .thinking_budget = false, + .plain_only = true, + .startup = h.startup, + }; + h.thread = try std.Thread.spawn(.{ .stack_size = 16 << 20 }, Host.run, .{h}); + return .{ .engine = h.engine(), .close = close, .ctx = h }; +} + +/// Stops admitting, cancels the admitted request (its finished event still arrives), joins the worker, frees all. +fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.lock(); + h.closing = true; + h.wake.broadcast(h.io); + h.unlock(); + if (h.thread) |t| t.join(); + h.thread = null; + h.ctx.makeCurrent() catch {}; // the closing thread frees device memory + h.stream.synchronize() catch {}; + h.codec.deinit(); + h.tower.deinit(); + h.backbone.deinit(); + h.stream.deinit(); + _ = cuda.setAllocationLimit(h.previous_allocation_limit) catch |e| blk: { + std.log.err("Drama memory budget restore: {s}", .{@errorName(e)}); + break :blk null; + }; + h.ctx.deinit(); + h.driver.close(); + h.gpa.free(h.startup); + h.gpa.destroy(h); +} diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 35b131e2cd3..f6a4e50f285 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -196,6 +196,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an error.Busy => cx.fail(.capacity, "the engine is busy; retry shortly", .{}), error.Closed => cx.fail(.other, "the scheduler is closed", .{}), error.InvalidSpans => cx.fail(.request, "the prompt span layout is invalid", .{}), + error.Unsupported => cx.fail(.request, "this model does not support text generation", .{}), error.Stale => cx.fail(.server, "{s}", .{api.stale_message}), }; release(srv, preparing); // a background request waits only while a foreground one prepares diff --git a/zig/src/server/drama_prompt.zig b/zig/src/server/drama_prompt.zig new file mode 100644 index 00000000000..3e466c86d2a --- /dev/null +++ b/zig/src/server/drama_prompt.zig @@ -0,0 +1,170 @@ +//! Drama 3's default-voice prompt as the reference builds it; each literal is tokenized alone to keep seam ids. +const std = @import("std"); +const model_text = @import("model_text.zig"); +const pyrepr = @import("pyrepr.zig"); +const Allocator = std.mem.Allocator; + +/// ``REQUEST_ERROR_PREFIX``: every refusal the model's request lowering writes starts with it. +pub const error_prefix = "Drama 3 request:"; + +pub const tts_instruction = "convert the provided text to speech"; +pub const message_end = "<|im_end|>\n"; +pub const generation_start = "<|im_start|>assistant\n<|voice|>"; + +/// Only the builder writes these; other special-token text in the caller's input is content. +pub const structural_tokens = [_][]const u8{ "<|im_start|>", "<|im_end|>", "<|voice|>", "<|text|>", "<|interleave|>", "<|semantic:" }; + +/// The tokenizer spells <|speaker:0|> to <|speaker:15|>. +pub const max_speaker_id = 15; + +/// The model's sampling defaults (``speech_request.py``), not the generic chat defaults. +pub const temperature: f32 = 1.0; +pub const top_p: f32 = 0.9; +pub const top_k: u32 = 30; + +/// The segments one prompt is encoded from, in order. +pub const segment_count = 7; + +/// The Unicode White_Space property (``UNICODE_WHITE_SPACE``); U+001C..U+001F are not in it. +pub fn isWhiteSpace(cp: u21) bool { + return switch (cp) { + 0x09...0x0d, 0x20, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, + else => false, + }; +} + +/// ``text.lstrip(UNICODE_WHITE_SPACE)``; ``text`` is valid UTF-8. +pub fn trimStart(text: []const u8) []const u8 { + var it = std.unicode.Utf8View.initUnchecked(text).iterator(); + while (true) { + const at = it.i; + const cp = it.nextCodepoint() orelse return text[text.len..]; + if (!isWhiteSpace(cp)) return text[at..]; + } +} + +const Tag = struct { digits: []const u8, end: usize }; + +/// ``SPEAKER_TAG_PATTERN.match(text, start)``: ``<|speaker:`` one or more ASCII digits ``|>``. +fn tagAt(text: []const u8, start: usize) ?Tag { + const open = "<|speaker:"; + if (!std.mem.startsWith(u8, text[start..], open)) return null; + const first = start + open.len; + var i = first; + while (i < text.len and std.ascii.isDigit(text[i])) i += 1; + if (i == first or !std.mem.startsWith(u8, text[i..], "|>")) return null; + return .{ .digits = text[first..i], .end = i + 2 }; +} + +/// ``SPEAKER_IDS``: the decimal spellings 0..15, no leading zero. +fn speakerId(digits: []const u8) ?u8 { + if (digits.len == 0 or digits.len > 2 or (digits.len == 2 and digits[0] == '0')) return null; + const n = std.fmt.parseInt(u8, digits, 10) catch return null; + return if (n <= max_speaker_id) n else null; +} + +/// Why input cannot be spoken, in the reference's words and order, or null. +pub fn problem(a: Allocator, input: []const u8) Allocator.Error!?[]const u8 { + // speech_request.py: well-formed tags naming a speaker other than 0 (malformed ones are the builder's) + var others: u16 = 0; + var at: usize = 0; + while (std.mem.indexOfPos(u8, input, at, "<|speaker:")) |start| { + if (tagAt(input, start)) |tag| { + if (speakerId(tag.digits)) |n| if (n != 0) { + others |= @as(u16, 1) << @intCast(n); + }; + at = tag.end; + } else at = start + 1; + } + if (others != 0) { + var list: std.ArrayList(u8) = .empty; + try list.appendSlice(a, error_prefix ++ " only speaker 0 is supported; got speaker tags ["); + var first = true; + for (1..max_speaker_id + 1) |n| if (others & (@as(u16, 1) << @intCast(n)) != 0) { + if (!first) try list.appendSlice(a, ", "); + try list.print(a, "{d}", .{n}); + first = false; + }; + try list.append(a, ']'); + return list.items; + } + // prompt.py's validate_caller_text(text, "input") + if (trimStart(input).len == 0) return error_prefix ++ " input: text must not be empty"; + for (structural_tokens) |token| if (std.mem.indexOf(u8, input, token) != null) + return try std.fmt.allocPrint(a, error_prefix ++ " input: {s} is written by the prompt builder and must not appear in caller text", .{token}); + at = 0; + while (std.mem.indexOfPos(u8, input, at, "<|speaker")) |start| { + const tag = tagAt(input, start); + if (tag == null or speakerId(tag.?.digits) == null) + return try std.fmt.allocPrint(a, error_prefix ++ " input: speaker tags must be written <|speaker:N|> with N in 0..{d} and no leading zero; got {s}", .{ max_speaker_id, try pyrepr.repr(a, .{ .string = input }) }); + at = start + "<|speaker".len; + } + return null; +} + +/// ``with_speaker_tag(text, 0)``: speaker 0 speaks unless a tag leads the text after white space. +pub fn tagged(a: Allocator, input: []const u8) Allocator.Error![]const u8 { + if (tagAt(trimStart(input), 0) != null) return input; + return std.mem.concat(a, u8, &.{ "<|speaker:0|> ", input }); +} + +/// The prompt's segments for a checked ``input`` (``problem`` returned null), each tokenized on its own. +pub fn segments(a: Allocator, input: []const u8) Allocator.Error![segment_count][]const u8 { + return .{ "<|im_start|>system\n", tts_instruction, message_end, "<|im_start|>user\n", try tagged(a, input), message_end, generation_start }; +} + +/// The prompt's ids: each segment encoded with the server's tokenizer as ``tokenizer.encode(segment).ids`` encodes it. +pub fn encode(a: Allocator, text: model_text.Text, input: []const u8) model_text.Error![]u32 { + var ids: std.ArrayList(u32) = .empty; + for (try segments(a, input)) |segment| try ids.appendSlice(a, try text.encode(a, segment, true)); + return ids.items; +} + +test "white space is the Unicode property, not Python's str.strip set" { + try std.testing.expect(isWhiteSpace(0x3000) and isWhiteSpace(0x85) and isWhiteSpace(0x0d) and isWhiteSpace(0x200a)); + for ([_]u21{ 0x1c, 0x1f, 0x200b, 0x180e, 0xfeff }) |cp| try std.testing.expect(!isWhiteSpace(cp)); + try std.testing.expectEqualStrings("x \u{3000}", trimStart("\u{3000}\n x \u{3000}")); + try std.testing.expectEqualStrings("\x1cx", trimStart(" \x1cx")); +} + +test "speaker 0 tags untagged text; a leading tag after white space is kept" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_][2][]const u8{ + .{ "hello", "<|speaker:0|> hello" }, + .{ "<|speaker:0|> hi", "<|speaker:0|> hi" }, + .{ "\n<|speaker:0|> hi", "\n<|speaker:0|> hi" }, + .{ "\u{3000}<|speaker:0|> hi", "\u{3000}<|speaker:0|> hi" }, + .{ "a <|speaker:0|> b", "<|speaker:0|> a <|speaker:0|> b" }, + .{ "\x1c<|speaker:0|> hi", "<|speaker:0|> \x1c<|speaker:0|> hi" }, + .{ "\x1f", "<|speaker:0|> \x1f" }, + }; + for (cases) |c| { + try std.testing.expect(try problem(a, c[0]) == null); + try std.testing.expectEqualStrings(c[1], try tagged(a, c[0])); + } +} + +test "input the reference refuses" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const malformed = [_][]const u8{ "<|speaker:99|> x", "<|speaker:16|> x", "a <|speaker:99|> b", "<|speaker:01|> x", "<|speaker:00|> x", "<|speaker:|> x", "<|speaker0|> x", "hi <|speaker", "<|speaker:abc|> x", "<|speaker:0> x", " <|speaker:abc|> hi" }; + for (malformed) |text| { + const message = (try problem(a, text)) orelse return error.TestUnexpectedResult; + try std.testing.expect(std.mem.startsWith(u8, message, "Drama 3 request: input: speaker tags must be written <|speaker:N|> with N in 0..15 and no leading zero; got ")); + } + try std.testing.expectEqualStrings("Drama 3 request: only speaker 0 is supported; got speaker tags [1, 15]", (try problem(a, "<|speaker:15|> a <|speaker:1|> b <|speaker:1|> c <|speaker:0|> d")).?); + // other speakers are refused before malformed tags, as speech_request.py checks them first + try std.testing.expectEqualStrings("Drama 3 request: only speaker 0 is supported; got speaker tags [2]", (try problem(a, "<|speaker:2|> x <|speaker:01|>")).?); + for ([_][]const u8{ "", " ", "\u{3000}\u{2028}\t" }) |blank| + try std.testing.expectEqualStrings("Drama 3 request: input: text must not be empty", (try problem(a, blank)).?); + for (structural_tokens) |token| { + const message = (try problem(a, try std.mem.concat(a, u8, &.{ "say ", token, " it" }))).?; + try std.testing.expect(std.mem.indexOf(u8, message, " is written by the prompt builder and must not appear in caller text") != null); + } + for ([_][]const u8{ "<|semantic:", "<|semantic:12|>" }) |text| try std.testing.expect(try problem(a, text) != null); + for ([_][]const u8{ "hi <|audio_separator|> there", "<|fim_prefix|> hi", "<|speaker:0|> current part<|endofturn|>next part" }) |content| + try std.testing.expect(try problem(a, content) == null); +} diff --git a/zig/src/server/mailbox.zig b/zig/src/server/mailbox.zig index 8a3e4e509ef..ec953de01bb 100644 --- a/zig/src/server/mailbox.zig +++ b/zig/src/server/mailbox.zig @@ -14,6 +14,7 @@ pub const Mailbox = struct { prompt_rows: ?[]api.LogprobRow = null, // one a prompt token after the first, for requests with prompt_logprobs cached: ?u32 = null, prefilled_ns: ?i96 = null, + audio: usize = 0, // samples a streamed speech request has made final finished: bool = false, reason: api.Reason = .stop, stats: api.Stats = .{}, @@ -37,6 +38,7 @@ pub const Mailbox = struct { m.tokens.appendSlice(m.gpa, t) catch {}; m.chunks.append(m.gpa, m.tokens.items.len) catch {}; }, + .audio => |n| m.audio = n, .finished => |f| { m.finished = true; m.reason = f.reason; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 381c864ad01..a114e3bc5ec 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -36,6 +36,9 @@ test { _ = @import("hub.zig"); _ = @import("chunk_plan.zig"); _ = @import("status_routes.zig"); + _ = @import("speech.zig"); + _ = @import("speech_stream_test.zig"); + _ = @import("drama_prompt.zig"); _ = @import("health_test.zig"); _ = @import("memory_routes.zig"); _ = @import("process_memory.zig"); diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index a529e1920bf..67d2ce4c0c9 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -13,6 +13,7 @@ const systemone = @import("systemone.zig"); const status = @import("status_routes.zig"); const memory = @import("memory_routes.zig"); const slide = @import("slide.zig"); +const speech = @import("speech.zig"); const recall = @import("recall_routes.zig"); const imprint = @import("imprint_routes.zig"); const slide_forget = @import("slide_forget.zig"); @@ -75,6 +76,7 @@ fn discardBody(conn: *Conn, a: Allocator) void { fn post(srv: *Server, conn: *Conn, a: Allocator) void { const route = auth.routePath(conn.path); + if (std.mem.eql(u8, route, "/v1/audio/speech")) return speech.post(srv, conn, a) catch {}; if (std.mem.eql(u8, route, "/v1/slide/learn")) return slide.learn(srv, conn, a); if (std.mem.eql(u8, route, "/v1/imprint/resume")) return imprint.post(srv, conn, a, .where); if (std.mem.eql(u8, route, "/v1/imprint/load")) return imprint.post(srv, conn, a, .load); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 5406581774c..3801a60cc56 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -119,6 +119,10 @@ pub const Server = struct { const srv = try gpa.create(Server); srv.* = .{ .gpa = gpa, .io = io, .engine = engine, .info = engine.info(), .text = text, .config = config, .keys = keys, .metrics = .{ .gpa = gpa }, .store = .{ .gpa = gpa }, .arena = .init(gpa), .slide = .init(gpa, io, config.slide_graph), .teacher = .init(gpa) }; errdefer srv.deinit(); // a later step's failure stops the keepalive before the caller closes the engine + if (!srv.info.text_generation) { + if (config.cortheon) return error.CortheonRequiresTextGeneration; + return srv; + } if (config.cortheon) srv.cortheon = try cortheon.State.init(gpa, io, "TensorFold-Cortheon (+https://github.com/ashhart/TensorFold)", config.cortheon_search_key); if (config.keep_warm_s > 0) if (engine.keepaliveTarget()) |target| { srv.keepalive = api.keepalive.Keepalive.start(gpa, io, target, @as(i64, config.keep_warm_s) * std.time.ns_per_s) catch |e| blk: { diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig new file mode 100644 index 00000000000..362f79598d0 --- /dev/null +++ b/zig/src/server/speech.zig @@ -0,0 +1,416 @@ +//! POST /v1/audio/speech: WAV or raw PCM whole, or raw PCM chunks with stream; only complete synthesis is audio. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const errors = @import("errors.zig"); +const http_body = @import("http_body.zig"); +const routes = @import("routes.zig"); +const openai = @import("openai.zig"); +const pyrepr = @import("pyrepr.zig"); +const reply_text = @import("reply_text.zig"); +const drama_prompt = @import("drama_prompt.zig"); +const ids = @import("ids.zig"); +const log = @import("log.zig"); +const clock = @import("clock.zig"); +const Mailbox = @import("mailbox.zig").Mailbox; +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Value = json.Value; +const Cx = errors.Cx; +const Allocator = std.mem.Allocator; + +/// ``MAX_SPEECH_INPUT_CHARS``: the most characters (code points) one input may hold. +pub const max_input_chars = 4096; + +/// The request fields served: the OpenAI ones (``speaker`` is ``voice``'s alias); ``stream*`` are checked apart. +const served_fields = [_][]const u8{ "model", "input", "voice", "speaker", "response_format" }; + +/// The rest of the speech protocol's fields: synthesis modifiers and references this route does not honor. +const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instructions", "ref_audio", "ref_text", "references", "x_vector_only_mode", "stream_codec_output", "suppress_bootstrap_silence", "token_count", "duration_tokens", "initial_codec_chunk_frames", "max_new_tokens", "temperature", "top_p", "top_k", "repetition_penalty", "seed", "stage_params" }; + +pub const Format = enum { + wav, + pcm, + + fn contentType(f: Format) []const u8 { + return switch (f) { + .wav => "audio/wav", + .pcm => "audio/pcm", + }; + } +}; + +const Plan = struct { prompt: []const u32, seed: u64, format: Format, stream: bool }; + +pub fn post(srv: *Server, c: *Conn, a: Allocator) !void { + const sp = srv.info.speech orelse { + _ = try http_body.read(c, a, http_body.limit); // dropped, so it cannot reach the next request on this connection + return routes.unknown(c, a); + }; + var cx: Cx = .{ .a = a }; + const id = try ids.make(a, "speech-", 32); + const received = clock.nowNs(srv.io); + const raw = http_body.readJson(c, &cx) catch |e| return refuse(c, &cx, id, e); + const plan = prepare(srv, &cx, sp, raw) catch |e| return refuse(c, &cx, id, e); + // only chunked framing tells a client that a stream which ends early is incomplete + if (plan.stream and !std.mem.eql(u8, c.version, "HTTP/1.1")) return fail(c, &cx, id, .request, "stream=true requires HTTP/1.1"); + synthesize(srv, c, &cx, id, sp, plan, received); +} + +fn listed(names: []const []const u8, key: []const u8) bool { + for (names) |name| if (std.mem.eql(u8, name, key)) return true; + return false; +} + +/// Refuses what this route would drop: unknown fields, set modifiers, non-strings, a bad ``stream``/``stream_format``. +fn checkFields(cx: *Cx, body: Value) errors.Refused!void { + for (body.object.keys(), body.object.values()) |key, value| { + if (listed(&served_fields, key)) { + if (value != .string) return cx.fail(.request, "{s} must be a string", .{key}); + } else if (std.mem.eql(u8, key, "stream")) { + if (value != .bool and value != .null) return cx.refuse("stream must be a boolean"); + } else if (std.mem.eql(u8, key, "stream_format")) { + if (value == .null or (value == .string and std.mem.eql(u8, value.string, "audio"))) continue; + if (value == .string and std.mem.eql(u8, value.string, "sse")) return cx.refuse("stream_format sse is not supported by this model"); + return cx.refuse("stream_format must be one of: audio, sse"); + } else if (listed(&modifier_fields, key)) { + if (value != .null) return cx.fail(.request, "{s} is not supported by this model", .{key}); + } else return cx.fail(.request, "unknown speech request field: {s}", .{key}); + } +} + +/// ``response_format.strip().lower()``, which must name WAV or raw PCM. +fn responseFormat(cx: *Cx, value: []const u8) errors.Refused!Format { + const name = reply_text.pyStrip(value); + if (std.ascii.eqlIgnoreCase(name, "wav")) return .wav; + if (std.ascii.eqlIgnoreCase(name, "pcm")) return .pcm; + return cx.refuse("response_format must be one of: pcm, wav"); +} + +/// Every check that can refuse the request, then its prompt ids, before anything reaches the engine. +fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused!Plan { + if (raw != .object) return cx.refuse("speech request body must be a JSON object"); + try checkFields(cx, raw); + const model = raw.strField("model") orelse return cx.fail(.request, "model is required: send {s}", .{srv.config.served_name}); + if (!listed(srv.config.model_ids, model)) + return cx.fail(.request, "model {s} is not served here: send {s}", .{ try pyrepr.repr(cx.a, .{ .string = model }), srv.config.served_name }); + const input = raw.strField("input") orelse return cx.refuse("input must be a non-empty string"); + if (!std.unicode.utf8ValidateSlice(input)) return cx.refuse("input must be valid UTF-8 text"); + if (reply_text.pyStrip(input).len == 0) return cx.refuse("input must be a non-empty string"); + if ((std.unicode.utf8CountCodepoints(input) catch unreachable) > max_input_chars) + return cx.fail(.request, "input must be at most {d} characters", .{max_input_chars}); + const format = try responseFormat(cx, raw.strField("response_format") orelse "wav"); + const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false; + if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'"); + const voice = raw.strField("voice") orelse raw.strField("speaker") orelse "default"; + if (voice.len > 0 and !std.ascii.eqlIgnoreCase(voice, "default")) + return cx.fail(.request, drama_prompt.error_prefix ++ " unknown voice {s}; only the default voice is supported", .{try pyrepr.repr(cx.a, .{ .string = voice })}); + if (try drama_prompt.problem(cx.a, input)) |message| return cx.refuse(message); + const prompt = drama_prompt.encode(cx.a, srv.text, input) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Template => cx.other("the tokenizer cannot encode this prompt"), + }; + if (prompt.len > sp.max_prompt_tokens) + return cx.fail(.request, drama_prompt.error_prefix ++ " a prompt of {d} rows exceeds the maximum allowed length of {d} rows", .{ prompt.len, sp.max_prompt_tokens }); + return .{ .prompt = prompt, .seed = api.seedFor(prompt, srv.config.seed_salt), .format = format, .stream = stream }; +} + +/// One synthesis: submit, then send the whole audio after the finished event, or stream it as the engine publishes it. +fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96) void { + const pcm_len = std.math.mul(usize, sp.max_frames, sp.frame_length) catch 0; + if (pcm_len == 0 or sp.sample_rate == 0 or sp.sample_rate > std.math.maxInt(u32) / 2) + return fail(c, cx, id, .server, "the engine advertises no usable speech output"); + const pcm = srv.gpa.alloc(f32, pcm_len) catch return fail(c, cx, id, .server, "out of memory"); + defer srv.gpa.free(pcm); + var result: api.SpeechResult = .{}; + const request: api.SpeechRequest = .{ + .prompt = plan.prompt, + .pcm = pcm, + .result = &result, + .seed = plan.seed, + .max_frames = sp.max_frames, + .temperature = drama_prompt.temperature, + .top_p = drama_prompt.top_p, + .top_k = drama_prompt.top_k, + .stream = plan.stream, + }; + var box: Mailbox = .{ .io = srv.io, .gpa = srv.gpa }; + defer box.deinit(); + const engine_id = srv.next_id.fetchAdd(1, .monotonic); + if (srv.keepalive) |k| k.begin(); + defer if (srv.keepalive) |k| k.end(); + srv.engine.submitSpeech(engine_id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return switch (e) { + error.Busy => fail(c, cx, id, .capacity, "the engine is busy; retry shortly"), + error.Closed => fail(c, cx, id, .other, "the scheduler is closed"), + error.InvalidRequest => fail(c, cx, id, .request, "the engine refused this speech request's prompt, frame limit or sampling"), + error.Unsupported => fail(c, cx, id, .request, "this model does not support speech synthesis"), + }; + // The engine holds request, prompt, pcm and result until finished; no path below returns before that. + if (plan.stream) return streamReply(srv, c, cx, id, sp, plan, received, &box, engine_id, pcm, &result); + if (settle(srv, c, &box, engine_id, null) == null) return left(srv, c, id, plan.prompt.len, received); + const samples = result.samples; + if (why(&box, samples, pcm.len)) |message| return fail(c, cx, id, .server, message); + const data = quantizeInPlace(pcm[0..samples]) catch return fail(c, cx, id, .server, "the synthesized audio has non-finite samples"); + if (data.len > std.math.maxInt(u32) - 36) return fail(c, cx, id, .server, "the synthesized audio is too long for one reply"); + sendAudio(c, plan.format, sp.sample_rate, data, box.reason) catch { + c.close = true; // a head already started or a client gone: nothing more can be sent on this connection + return; + }; + log.line("speech {s} prompt={d} samples={d} format={s} finish={s} seconds={d:.2}", .{ id, plan.prompt.len, samples, @tagName(plan.format), @tagName(box.reason), clock.seconds(clock.nowNs(srv.io) - received) }); +} + +/// The client left before the reply ended; the synthesis was cancelled and waited out. +fn left(srv: *Server, c: *Conn, id: []const u8, prompt_len: usize, received: i96) void { + c.close = true; + srv.metrics.disconnected(srv.io); + var buf: [1024]u8 = undefined; + log.line("{s}", .{log.ended(&buf, id, null, prompt_len, 0, clock.seconds(clock.nowNs(srv.io) - received))}); +} + +/// Why a finished synthesis has no complete audio, or null; clipped audio (length) is sent with X-Finish-Reason. +fn why(box: *const Mailbox, samples: usize, capacity: usize) ?[]const u8 { + return switch (box.reason) { + .stop, .length => if (samples == 0 or samples > capacity) "the engine finished without complete audio" else null, + .cancelled => "speech synthesis was cancelled", + .failed => if (box.message.len > 0) box.message else "speech synthesis failed", + }; +} + +/// An error reply when synthesis ends before any audio; else the chunks, and the terminator only after a complete one. +fn streamReply(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInfo, plan: Plan, received: i96, box: *Mailbox, engine_id: api.Id, pcm: []f32, result: *const api.SpeechResult) void { + const sent = streamAudio(srv, c, sp, box, engine_id, pcm) orelse return left(srv, c, id, plan.prompt.len, received); + const mismatch: ?[]const u8 = if (result.samples != sent.samples) "the finished synthesis does not match the audio it published" else null; + const problem = why(box, result.samples, pcm.len) orelse mismatch; + if (sent.samples == 0) return fail(c, cx, id, .server, problem orelse "the engine finished without publishing audio"); + if (problem) |message| { + c.close = true; // no terminating chunk: the client's HTTP/1.1 parser reports an incomplete body + log.line("speech {s} stream ended incomplete after samples={d}: {s}", .{ id, sent.samples, message }); + return; + } + c.writeAll(if (box.reason == .length) length_chunk else last_chunk) catch { + c.close = true; + return; + }; + log.line("speech {s} prompt={d} samples={d} format=pcm stream=true finish={s} first_audio_ready_seconds={d:.3} first_frame_written_seconds={d:.3} seconds={d:.2}", .{ + id, plan.prompt.len, sent.samples, @tagName(box.reason), clock.seconds(sent.first_ready - received), clock.seconds(sent.first_written - received), clock.seconds(clock.nowNs(srv.io) - received), + }); +} + +/// What a stream sent, when this thread first saw published audio, and when frame 0's own bytes reached the socket. +const Sent = struct { samples: usize = 0, first_ready: i96 = 0, first_written: i96 = 0 }; + +/// Sends everything published since the last send as one chunk, converted in place; null: the client left. +fn streamAudio(srv: *Server, c: *Conn, sp: api.SpeechInfo, box: *Mailbox, engine_id: api.Id, pcm: []f32) ?Sent { + var sent: Sent = .{}; + var size: [20]u8 = undefined; + while (true) { + const now = settle(srv, c, box, engine_id, sent.samples) orelse return null; + if (now == sent.samples) return sent; // finished, and everything published is sent + const first = sent.samples == 0; + if (first) { + sent.first_ready = clock.nowNs(srv.io); + startStream(c, sp.sample_rate) catch return abandon(srv, box, engine_id); + } + // the audio event made pcm[..now] final: this thread converts it in place + const bytes = quantizeInPlace(pcm[sent.samples..now]) catch return abandon(srv, box, engine_id); + // frame 0's bytes go apart, so their hand-off time does not depend on the chunk's size + const split: usize = if (first) @min(2 * sp.frame_length, bytes.len) else 0; + c.writeAll(std.fmt.bufPrint(&size, "{x}\r\n", .{bytes.len}) catch unreachable) catch return abandon(srv, box, engine_id); + c.writeAll(bytes[0..split]) catch return abandon(srv, box, engine_id); + if (first) sent.first_written = clock.nowNs(srv.io); + c.writeAll(bytes[split..]) catch return abandon(srv, box, engine_id); + c.writeAll("\r\n") catch return abandon(srv, box, engine_id); + sent.samples = now; + } +} + +/// Cancels a synthesis whose client is gone, then waits for its finished event; null, for the callers' `return`. +fn abandon(srv: *Server, box: *Mailbox, engine_id: api.Id) ?Sent { + srv.engine.cancel(engine_id); + box.mutex.lockUncancelable(box.io); + defer box.mutex.unlock(box.io); + while (!box.finished) box.cond.waitUncancelable(box.io, &box.mutex); + return null; +} + +/// Waits for `finished` or (with `sent`) samples past it, cancelling if the client leaves; samples so far, or null. +fn settle(srv: *Server, c: *Conn, box: *Mailbox, engine_id: api.Id, sent: ?usize) ?usize { + while (true) { + box.mutex.lockUncancelable(box.io); + const idle = if (sent) |n| box.audio == n else true; + if (!box.finished and idle) box.cond.waitTimeout(box.io, &box.mutex, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake } }) catch {}; + const finished = box.finished; + const published = box.audio; + box.mutex.unlock(box.io); + if (finished or (if (sent) |n| published > n else false)) return published; + if (c.peerGone()) { + _ = abandon(srv, box, engine_id); + return null; + } + } +} + +/// 200 with raw PCM16LE in HTTP/1.1 chunks, under the reference's sample-format headers. +fn startStream(c: *Conn, sample_rate: u32) error{Closed}!void { + c.startResponse(200, null) catch return error.Closed; + c.addHeader("Content-Type", Format.pcm.contentType()) catch return error.Closed; + c.addHeader("Transfer-Encoding", "chunked") catch return error.Closed; + var rate: [16]u8 = undefined; + c.addHeader("X-Sample-Rate", std.fmt.bufPrint(&rate, "{d}", .{sample_rate}) catch unreachable) catch return error.Closed; + c.addHeader("X-Channels", "1") catch return error.Closed; + c.addHeader("X-Bit-Depth", "16") catch return error.Closed; + c.addHeader("Trailer", "X-Finish-Reason") catch return error.Closed; + if (c.close) c.addHeader("Connection", "close") catch return error.Closed; + // each chunk leaves at once rather than waiting on the client's acknowledgement of the last (no effect off TCP) + std.posix.setsockopt(c.fd, std.posix.IPPROTO.TCP, std.posix.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1))) catch {}; + // a blocking write into a full socket returns after the stall limit, so writeAll's poll can end a stalled stream + const stall: std.posix.timeval = .{ .sec = @divTrunc(c.timeouts.write_ms, 1000), .usec = @rem(c.timeouts.write_ms, 1000) * 1000 }; + std.posix.setsockopt(c.fd, std.posix.SOL.SOCKET, std.posix.SO.SNDTIMEO, std.mem.asBytes(&stall)) catch {}; + return c.finish(""); +} + +/// Ends a complete stream; audio clipped at the frame limit ends with the X-Finish-Reason trailer instead. +const last_chunk = "0\r\n\r\n"; +const length_chunk = "0\r\nX-Finish-Reason: length\r\n\r\n"; + +fn refuse(c: *Conn, cx: *Cx, id: []const u8, e: errors.Refused) void { + if (e == error.OutOfMemory) { + cx.kind = .server; + cx.message = "out of memory"; + } + send(c, cx, id); +} + +fn fail(c: *Conn, cx: *Cx, id: []const u8, kind: errors.Kind, message: []const u8) void { + cx.kind = kind; + cx.message = message; + send(c, cx, id); +} + +/// OpenAI's error object, logged first: the access line shows only the status. +fn send(c: *Conn, cx: *Cx, id: []const u8) void { + var buf: [1400]u8 = undefined; + log.line("{s}", .{log.refused(&buf, id, cx.message)}); + const body = openai.errorBody(cx.a, cx, null) catch return; + routes.sendValue(c, cx.a, cx.status(), openai.wrapError(cx.a, body) catch return); +} + +/// The head, then the WAV header and the samples where they lie: the audio is never copied to prepend a header. +fn sendAudio(c: *Conn, format: Format, sample_rate: u32, data: []const u8, reason: api.Reason) error{ Closed, OutOfMemory }!void { + const header: ?[wav_header_len]u8 = if (format == .wav) wavHeader(sample_rate, @intCast(data.len)) else null; + const header_len: usize = if (header != null) wav_header_len else 0; + try c.startResponse(200, null); + try c.addHeader("Content-Type", format.contentType()); + var len: [24]u8 = undefined; + try c.addHeader("Content-Length", std.fmt.bufPrint(&len, "{d}", .{header_len + data.len}) catch unreachable); + try c.addHeader("X-Finish-Reason", @tagName(reason)); + if (c.close) try c.addHeader("Connection", "close"); + defer c.out.clearRetainingCapacity(); + if (!std.mem.eql(u8, c.version, "HTTP/0.9")) try c.out.appendSlice(c.gpa, "\r\n"); + if (header) |h| try c.out.appendSlice(c.gpa, &h); + try c.writeAll(c.out.items); + try c.writeAll(data); +} + +pub const wav_header_len = 44; + +/// A canonical 44-byte RIFF/WAVE header for mono 16-bit PCM of ``data_bytes`` bytes. +pub fn wavHeader(sample_rate: u32, data_bytes: u32) [wav_header_len]u8 { + var h: [wav_header_len]u8 = undefined; + @memcpy(h[0..4], "RIFF"); + std.mem.writeInt(u32, h[4..8], 36 + data_bytes, .little); + @memcpy(h[8..12], "WAVE"); + @memcpy(h[12..16], "fmt "); + std.mem.writeInt(u32, h[16..20], 16, .little); // fmt chunk size + std.mem.writeInt(u16, h[20..22], 1, .little); // PCM + std.mem.writeInt(u16, h[22..24], 1, .little); // mono + std.mem.writeInt(u32, h[24..28], sample_rate, .little); + std.mem.writeInt(u32, h[28..32], sample_rate * 2, .little); // byte rate + std.mem.writeInt(u16, h[32..34], 2, .little); // block align + std.mem.writeInt(u16, h[34..36], 16, .little); // bits a sample + @memcpy(h[36..40], "data"); + std.mem.writeInt(u32, h[40..44], data_bytes, .little); + return h; +} + +/// The reference's (clip(x, -1, 1) * 32767).astype(int16) as PCM16LE in place; each sample is read before written. +pub fn quantizeInPlace(pcm: []f32) error{NonFinite}![]u8 { + const bytes = std.mem.sliceAsBytes(pcm); + for (0..pcm.len) |i| { + const x = pcm[i]; + if (!std.math.isFinite(x)) return error.NonFinite; + const q: i16 = @intFromFloat(std.math.clamp(x, -1.0, 1.0) * 32767.0); + std.mem.writeInt(i16, bytes[2 * i ..][0..2], q, .little); + } + return bytes[0 .. 2 * pcm.len]; +} + +test "quantization clips, truncates toward zero and stays in place" { + var pcm = [_]f32{ 0, 1, -1, 1.5, -7, 0.5, -0.5, 0.25, 1e-6, -1e-6 }; + const want = [_]i16{ 0, 32767, -32767, 32767, -32767, 16383, -16383, 8191, 0, 0 }; + const bytes = try quantizeInPlace(&pcm); + try std.testing.expectEqual(@as(usize, 2 * want.len), bytes.len); + try std.testing.expectEqual(@intFromPtr(&pcm), @intFromPtr(bytes.ptr)); + for (want, 0..) |w, i| try std.testing.expectEqual(w, std.mem.readInt(i16, bytes[2 * i ..][0..2], .little)); +} + +test "non-finite audio is refused" { + for ([_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }) |bad| { + var pcm = [_]f32{ 0.1, bad, 0.2 }; + try std.testing.expectError(error.NonFinite, quantizeInPlace(&pcm)); + } +} + +test "the WAV header describes mono 16-bit PCM at the advertised rate" { + const h = wavHeader(44100, 4096); + try std.testing.expectEqualStrings("RIFF", h[0..4]); + try std.testing.expectEqual(@as(u32, 36 + 4096), std.mem.readInt(u32, h[4..8], .little)); + try std.testing.expectEqualStrings("WAVEfmt ", h[8..16]); + try std.testing.expectEqual(@as(u32, 16), std.mem.readInt(u32, h[16..20], .little)); + try std.testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, h[20..22], .little)); + try std.testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, h[22..24], .little)); + try std.testing.expectEqual(@as(u32, 44100), std.mem.readInt(u32, h[24..28], .little)); + try std.testing.expectEqual(@as(u32, 88200), std.mem.readInt(u32, h[28..32], .little)); + try std.testing.expectEqual(@as(u16, 2), std.mem.readInt(u16, h[32..34], .little)); + try std.testing.expectEqual(@as(u16, 16), std.mem.readInt(u16, h[34..36], .little)); + try std.testing.expectEqualStrings("data", h[36..40]); + try std.testing.expectEqual(@as(u32, 4096), std.mem.readInt(u32, h[40..44], .little)); +} + +test "fields: unknown ones are refused even when null, modifiers when set" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_][2][]const u8{ + .{ "{\"model\": \"m\", \"input\": \"hi\", \"voice\": \"default\", \"response_format\": \"wav\", \"speed\": null, \"references\": null}", "" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_audio\": null}", "unknown speech request field: stream_audio" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"speed\": 1.0}", "speed is not supported by this model" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": false, \"stream_format\": \"audio\"}", "" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": null, \"stream_format\": null}", "" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream\": \"yes\"}", "stream must be a boolean" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_format\": \"sse\"}", "stream_format sse is not supported by this model" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"stream_format\": \"mp3\"}", "stream_format must be one of: audio, sse" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"temperature\": 0.7}", "temperature is not supported by this model" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"ref_audio\": \"x.wav\"}", "ref_audio is not supported by this model" }, + .{ "{\"model\": \"m\", \"input\": 3}", "input must be a string" }, + .{ "{\"model\": null, \"input\": \"hi\"}", "model must be a string" }, + .{ "{\"model\": \"m\", \"input\": \"hi\", \"voice\": null}", "voice must be a string" }, + }; + for (cases) |case| { + var cx: Cx = .{ .a = a }; + const body = (try json.parse(a, case[0])).ok; + if (case[1].len == 0) { + try checkFields(&cx, body); + } else { + try std.testing.expectError(error.Refused, checkFields(&cx, body)); + try std.testing.expectEqualStrings(case[1], cx.message); + } + } +} + +test "response_format is WAV or PCM, stripped and case-folded as Python does" { + var cx: Cx = .{ .a = std.testing.allocator }; + try std.testing.expectEqual(Format.wav, try responseFormat(&cx, " WAV\n")); + try std.testing.expectEqual(Format.pcm, try responseFormat(&cx, "\u{3000}Pcm\x1c")); + for ([_][]const u8{ "mp3", "", "wave", "pcm16" }) |bad| try std.testing.expectError(error.Refused, responseFormat(&cx, bad)); +} diff --git a/zig/src/server/speech_stream_test.zig b/zig/src/server/speech_stream_test.zig new file mode 100644 index 00000000000..9a3ca4d8fe8 --- /dev/null +++ b/zig/src/server/speech_stream_test.zig @@ -0,0 +1,377 @@ +//! The streamed speech reply on the wire, against a scripted engine over a socketpair with the route on its own thread. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("root.zig"); +const json = server.json; +const model_text = @import("model_text.zig"); +const routes = @import("routes.zig"); +const Conn = @import("http_conn.zig").Conn; + +const frame = 2048; +const gpa = std.testing.allocator; + +/// Publishes 0.5-filled steps then finishes: inside submit (`inline_`), else on a thread that may `hold` for `release`. +const Script = struct { + steps: []const usize, + reason: api.Reason = .stop, + message: []const u8 = "", + hold: usize = 0, + inline_: bool = false, + max_frames: u32 = 4, + release: std.atomic.Value(bool) = .init(false), + cancelled: std.atomic.Value(bool) = .init(false), + thread: ?std.Thread = null, + + fn engine(e: *Script) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .submit_speech = speech } }; + } + fn info(ctx: *anyopaque) api.Info { + const e: *Script = @ptrCast(@alignCast(ctx)); + return .{ .text_generation = false, .speech = .{ .sample_rate = 44100, .frame_length = frame, .max_frames = e.max_frames, .max_prompt_tokens = 4096 } }; + } + fn speech(ctx: *anyopaque, id: api.Id, request: *const api.SpeechRequest, sink: api.Sink) api.SpeechSubmitError!void { + const e: *Script = @ptrCast(@alignCast(ctx)); + if (e.inline_) return run(e, id, request, sink); + e.thread = std.Thread.spawn(.{}, run, .{ e, id, request, sink }) catch return error.Busy; + } + fn run(e: *Script, id: api.Id, request: *const api.SpeechRequest, sink: api.Sink) void { + var done: usize = 0; + for (e.steps, 0..) |n, i| { + if (e.hold > 0 and i == e.hold) { + while (!e.release.load(.acquire)) std.Thread.yield() catch {}; + if (e.cancelled.load(.acquire)) return sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .cancelled } }); + } + @memset(request.pcm[done..n], 0.5); + if (request.stream) sink.event(sink.ctx, id, &.{ .audio = n }); + done = n; + } + if (e.reason == .stop or e.reason == .length) request.result.samples = done; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = e.reason, .message = e.message } }); + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const e: *Script = @ptrCast(@alignCast(ctx)); + e.cancelled.store(true, .release); + e.release.store(true, .release); + } + fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Unsupported; + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// Every byte is its own token: the route's prompt encoding needs no vocabulary. +const Bytes = struct { + fn text(t: *Bytes) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } }; + } + fn encode(_: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + fn decode(_: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { + const out = try a.alloc(u8, ids.len); + for (ids, out) |id, *byte| byte.* = @intCast(id); + return out; + } + fn tokenId(_: *anyopaque, _: []const u8) ?u32 { + return null; + } + fn tokenString(_: *anyopaque, a: std.mem.Allocator, id: u32) std.mem.Allocator.Error![]u8 { + return std.fmt.allocPrint(a, "{d}", .{id}); + } + fn vocabSize(_: *anyopaque) u32 { + return 256; + } + fn eosIds(_: *anyopaque) []const u32 { + return &.{}; + } + fn render(_: *anyopaque, _: std.mem.Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error![]u8 { + return error.Template; + } + fn templateSource(_: *anyopaque) []const u8 { + return ""; + } +}; + +/// One request served on its own thread; the test reads the reply from the client end as it arrives. +const Served = struct { + srv: *server.Server, + text: Bytes = .{}, + client: std.c.fd_t, + route_fd: std.c.fd_t, + route: std.Thread, + write_ms: i32, + got: std.ArrayList(u8) = .empty, + read_at: usize = 0, + eof: bool = false, + client_open: bool = true, + + fn start(s: *Served, script: *Script, version: []const u8, body: []const u8, write_ms: i32) !void { + var pair: [2]std.c.fd_t = undefined; + if (std.c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM, 0, &pair) != 0) return error.SocketPair; + s.* = .{ .srv = undefined, .client = pair[0], .route_fd = pair[1], .route = undefined, .write_ms = write_ms }; + s.srv = try server.Server.init(gpa, std.testing.io, script.engine(), s.text.text(), .{ .served_name = "m", .model_ids = &.{"m"} }, null); + var head: [160]u8 = undefined; + try writeAll(s.client, try std.fmt.bufPrint(&head, "POST /v1/audio/speech {s}\r\nHost: t\r\nContent-Length: {d}\r\n\r\n", .{ version, body.len })); + try writeAll(s.client, body); + s.route = try std.Thread.spawn(.{}, serve, .{s}); + } + + fn serve(s: *Served) void { + var conn = Conn.init(gpa, s.route_fd, "test") catch return; + defer conn.deinit(); + conn.timeouts = .{ .idle_ms = 2000, .read_ms = 2000, .write_ms = s.write_ms }; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const outcome = conn.readRequest(arena.allocator(), false) catch return; + if (outcome == .ready) routes.dispatch(s.srv, &conn, arena.allocator()); + if (conn.close) _ = std.c.shutdown(s.route_fd, 1); // what the server loop does to a closing connection: EOF + } + + /// Waits for the route, then for the engine's own thread. + fn join(s: *Served, script: *Script) void { + s.route.join(); + if (script.thread) |t| t.join(); + script.thread = null; + } + + fn deinit(s: *Served) void { + if (s.client_open) _ = std.c.close(s.client); + _ = std.c.close(s.route_fd); + s.got.deinit(gpa); + s.srv.deinit(); + } + + /// Reads more of the reply; false at EOF or after `wait_ms` of silence. + fn more(s: *Served, wait_ms: i32) !bool { + if (s.eof) return false; + var fds = [_]std.posix.pollfd{.{ .fd = s.client, .events = std.posix.POLL.IN, .revents = 0 }}; + if (try std.posix.poll(&fds, wait_ms) == 0) return false; + var tmp: [65536]u8 = undefined; + const n = std.posix.read(s.client, &tmp) catch 0; + if (n == 0) { + s.eof = true; + return false; + } + try s.got.appendSlice(gpa, tmp[0..n]); + return true; + } + + fn readHead(s: *Served) ![]const u8 { + while (std.mem.indexOf(u8, s.got.items, "\r\n\r\n") == null) if (!try s.more(2000)) return error.NoHead; + const end = std.mem.indexOf(u8, s.got.items, "\r\n\r\n").? + 4; + s.read_at = end; + return s.got.items[0..end]; + } + + /// The next chunk's bytes, or null after the terminating chunk; NoChunk when the reply ends first. + fn readChunk(s: *Served) !?[]const u8 { + while (true) { + const rest = s.got.items[s.read_at..]; + if (std.mem.indexOf(u8, rest, "\r\n")) |line| { + const size = try std.fmt.parseInt(usize, rest[0..line], 16); + if (rest.len >= line + 2 + size + 2) { + if (!std.mem.eql(u8, rest[line + 2 + size ..][0..2], "\r\n")) return error.BadChunk; + s.read_at += line + 2 + size + 2; + return if (size == 0) null else rest[line + 2 ..][0..size]; + } + } + if (!try s.more(2000)) return error.NoChunk; + } + } + + /// Every chunk's bytes until the reply ends; `terminated`: the zero chunk came. + fn payload(s: *Served, terminated: *bool) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + while (s.readChunk()) |chunk| { + const bytes = chunk orelse { + terminated.* = true; + return out.toOwnedSlice(gpa); + }; + try out.appendSlice(gpa, bytes); + } else |e| if (e != error.NoChunk) return e; + terminated.* = false; + return out.toOwnedSlice(gpa); + } + + /// The rest of a reply the route has finished writing. + fn readRest(s: *Served) ![]const u8 { + while (try s.more(200)) {} + return s.got.items[s.read_at..]; + } +}; + +fn writeAll(fd: std.c.fd_t, data: []const u8) !void { + var sent: usize = 0; + while (sent < data.len) { + const n = std.c.write(fd, data[sent..].ptr, data.len - sent); + if (n <= 0) return error.Closed; + sent += @intCast(n); + } +} + +const stream_body = "{\"model\":\"m\",\"input\":\"hi\",\"response_format\":\"pcm\",\"stream\":true}"; +/// `n` frames of 0.5, which quantizes to 16383 (0x3fff), as PCM16LE. +fn pcm(comptime n: usize) [2 * frame * n]u8 { + var bytes: [2 * frame * n]u8 = undefined; + for (0..frame * n) |i| bytes[2 * i ..][0..2].* = .{ 0xff, 0x3f }; + return bytes; +} + +fn expectHeader(head: []const u8, line: []const u8) !void { + try std.testing.expect(std.mem.indexOf(u8, head, line) != null); +} + +test "a complete stream carries every frame in order, converted, then the terminating chunk" { + var script: Script = .{ .steps = &.{ frame, 3 * frame } }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + const head = try s.readHead(); + try expectHeader(head, "HTTP/1.1 200"); + try expectHeader(head, "Content-Type: audio/pcm\r\n"); + try expectHeader(head, "Transfer-Encoding: chunked\r\n"); + try expectHeader(head, "X-Sample-Rate: 44100\r\nX-Channels: 1\r\nX-Bit-Depth: 16\r\n"); + try std.testing.expect(std.mem.indexOf(u8, head, "Content-Length") == null); + var terminated = false; + const audio = try s.payload(&terminated); // where the route caught each publication is scheduling, not the bytes + defer gpa.free(audio); + s.join(&script); + try std.testing.expectEqualStrings(&pcm(3), audio); + try std.testing.expect(terminated); +} + +test "audio published before the route reads it goes out as one chunk" { + var script: Script = .{ .steps = &.{ frame, 3 * frame }, .inline_ = true }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + _ = try s.readHead(); + s.join(&script); + const rest = try s.readRest(); + try std.testing.expect(std.mem.startsWith(u8, rest, "3000\r\n") and std.mem.endsWith(u8, rest, "\r\n0\r\n\r\n")); + try std.testing.expectEqualStrings(&pcm(3), rest["3000\r\n".len .. rest.len - "\r\n0\r\n\r\n".len]); +} + +test "audio is on the wire before the synthesis ends; frame 0 alone when sent before more is published" { + var script: Script = .{ .steps = &.{ frame, 3 * frame }, .hold = 1 }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + _ = try s.readHead(); + try std.testing.expectEqualStrings(&pcm(1), (try s.readChunk()).?); // the engine still holds frames 1 and 2 + script.release.store(true, .release); + try std.testing.expectEqualStrings(&pcm(2), (try s.readChunk()).?); + try std.testing.expect(try s.readChunk() == null); + s.join(&script); +} + +test "a failure after audio ends the stream without its terminating chunk" { + var script: Script = .{ .steps = &.{frame}, .reason = .failed, .message = "the codec produced non-finite audio" }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + _ = try s.readHead(); + var terminated = true; + const audio = try s.payload(&terminated); + defer gpa.free(audio); + s.join(&script); + try std.testing.expectEqualStrings(&pcm(1), audio); + try std.testing.expect(!terminated and s.eof); +} + +test "audio clipped at the frame limit ends the stream with the length trailer" { + var script: Script = .{ .steps = &.{ frame, 2 * frame }, .reason = .length, .inline_ = true }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + try expectHeader(try s.readHead(), "Trailer: X-Finish-Reason\r\n"); + s.join(&script); + const rest = try s.readRest(); + const end = "\r\n0\r\nX-Finish-Reason: length\r\n\r\n"; + try std.testing.expect(std.mem.startsWith(u8, rest, "2000\r\n") and std.mem.endsWith(u8, rest, end)); + try std.testing.expectEqualStrings(&pcm(2), rest["2000\r\n".len .. rest.len - end.len]); +} + +test "a whole reply returns audio clipped at the frame limit and names its finish reason" { + for ([_]api.Reason{ .stop, .length }) |reason| { + var script: Script = .{ .steps = &.{frame}, .reason = reason }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", "{\"model\":\"m\",\"input\":\"hi\",\"response_format\":\"pcm\"}", 2000); + defer s.deinit(); + const head = try s.readHead(); + try expectHeader(head, "HTTP/1.1 200"); + try expectHeader(head, if (reason == .length) "X-Finish-Reason: length\r\n" else "X-Finish-Reason: stop\r\n"); + s.join(&script); + try std.testing.expectEqualStrings(&pcm(1), try s.readRest()); + } +} + +test "a failure before any audio is an error reply" { + var script: Script = .{ .steps = &.{}, .reason = .failed, .message = "the model ended speech before its first audio frame" }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + try expectHeader(try s.readHead(), "HTTP/1.1 500"); + s.join(&script); + try std.testing.expect(std.mem.indexOf(u8, try s.readRest(), "the model ended speech before its first audio frame") != null); +} + +test "a client that leaves after the first chunk cancels the synthesis, which is waited out" { + var script: Script = .{ .steps = &.{ frame, 3 * frame }, .hold = 1 }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 2000); + defer s.deinit(); + _ = try s.readHead(); + _ = (try s.readChunk()).?; + _ = std.c.close(s.client); // the route's peerGone poll cancels; the engine then finishes cancelled + s.client_open = false; + s.join(&script); // returns only after the finished event: the request storage outlived the synthesis + try std.testing.expect(script.cancelled.load(.acquire)); +} + +test "a client that stops reading is cut off at the write stall limit and the synthesis cancelled" { + var steps: [255]usize = undefined; + for (&steps, 1..) |*n, i| n.* = i * frame; + var script: Script = .{ .steps = &steps, .max_frames = 256, .hold = 1 }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", stream_body, 200); + defer s.deinit(); + script.release.store(true, .release); // 1 MiB of PCM16 published while nobody reads overflows the socket buffers + s.join(&script); + try std.testing.expect(script.cancelled.load(.acquire)); + _ = try s.readHead(); + var terminated = true; + gpa.free(try s.payload(&terminated)); + try std.testing.expect(!terminated); +} + +test "stream needs pcm and HTTP/1.1; stream false is the whole reply" { + const cases = [_]struct { version: []const u8, body: []const u8, want: []const u8 }{ + .{ .version = "HTTP/1.1", .body = "{\"model\":\"m\",\"input\":\"hi\",\"stream\":true}", .want = "stream=true requires response_format='pcm'" }, + .{ .version = "HTTP/1.0", .body = stream_body, .want = "stream=true requires HTTP/1.1" }, + }; + for (cases) |case| { + var script: Script = .{ .steps = &.{frame} }; + var s: Served = undefined; + try s.start(&script, case.version, case.body, 2000); + defer s.deinit(); + try expectHeader(try s.readHead(), " 400 "); + s.join(&script); + try std.testing.expect(std.mem.indexOf(u8, try s.readRest(), case.want) != null); + } + var script: Script = .{ .steps = &.{frame} }; + var s: Served = undefined; + try s.start(&script, "HTTP/1.1", "{\"model\":\"m\",\"input\":\"hi\",\"response_format\":\"pcm\",\"stream\":false}", 2000); + defer s.deinit(); + try expectHeader(try s.readHead(), "Content-Length: 4096\r\n"); + s.join(&script); + try std.testing.expectEqualStrings(&pcm(1), try s.readRest()); +} diff --git a/zig/tests/cuda/drama_backbone_oracle.zig b/zig/tests/cuda/drama_backbone_oracle.zig new file mode 100644 index 00000000000..3784843135e --- /dev/null +++ b/zig/tests/cuda/drama_backbone_oracle.zig @@ -0,0 +1,92 @@ +//! Runs the production backbone across chunk sizes and reset on 2..512 u32 text tokens; the caller owns the GPU. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const width = 2048; +const candidate_count = 4097; + +fn runChunks(model: *drama.backbone.Model, stream: cuda.Stream, tokens: []const u32, chunk: usize, hidden: []u16, logits: []f32) !void { + try model.reset(stream); + var at: usize = 0; + while (at < tokens.len) { + const end = @min(at + chunk, tokens.len); + const output = try model.run(stream, .prefill, tokens[at..end], null); + try output.hidden.download(0, std.mem.sliceAsBytes(hidden[at * width .. end * width])); + if (end == tokens.len) try output.semantic_logits.download(0, std.mem.sliceAsBytes(logits)); + at = end; + } + for (hidden) |bits| { + const value: f32 = @bitCast(@as(u32, bits) << 16); + if (!std.math.isFinite(value)) return error.NonFiniteBackboneHidden; + } + for (logits) |value| if (!std.math.isFinite(value)) return error.NonFiniteBackboneLogits; +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-backbone-oracle CHECKPOINT TOKENS_U32LE OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [512 * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const file = try std.Io.Dir.cwd().openFile(init.io, args[2], .{}); + defer file.close(init.io); + const count = try file.readPositionalAll(init.io, &bytes, 0); + if (count < 8 or count > 512 * 4 or count % 4 != 0) return error.ExpectedTwoTo512Tokens; + const tokens = std.mem.bytesAsSlice(u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + var out = try std.Io.Dir.cwd().openDir(init.io, args[3], .{}); + defer out.close(init.io); + const baseline = try init.gpa.alloc(u16, tokens.len * width); + defer init.gpa.free(baseline); + const actual = try init.gpa.alloc(u16, tokens.len * width); + defer init.gpa.free(actual); + var baseline_logits: [candidate_count]f32 = undefined; + var logits: [candidate_count]f32 = undefined; + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try drama.backbone.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .context = 512, .max_rows = 128 }); + defer model.deinit(); + for (tokens) |token| if (token >= model.semantic_start and token <= model.semantic_end) return error.TextFixtureMustNotContainSemanticTokens; + var all_equal = true; + var name_buffer: [128]u8 = undefined; + for ([_]usize{ 1, 7, 128 }) |chunk| { + const started = std.Io.Clock.awake.now(init.io).toNanoseconds(); + try runChunks(&model, stream, tokens, chunk, actual, &logits); + const elapsed = std.Io.Clock.awake.now(init.io).toNanoseconds() - started; + var name = try std.fmt.bufPrint(&name_buffer, "native-chunk-{d}-hidden.bf16", .{chunk}); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(actual) }); + name = try std.fmt.bufPrint(&name_buffer, "native-chunk-{d}-semantic.f32", .{chunk}); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(&logits) }); + if (chunk == 1) { + @memcpy(baseline, actual); + baseline_logits = logits; + } + var hidden_differences: usize = 0; + for (baseline, actual) |a, b| if (a != b) { + hidden_differences += 1; + }; + const head_equal = std.mem.eql(u8, std.mem.sliceAsBytes(&baseline_logits), std.mem.sliceAsBytes(&logits)); + all_equal = all_equal and hidden_differences == 0 and head_equal; + std.debug.print("rows={d} chunk={d} elapsed_s={d:.6} hidden_bit_differences={d} semantic_logits_bit_equal={}\n", .{ + tokens.len, chunk, @as(f64, @floatFromInt(elapsed)) / 1e9, hidden_differences, head_equal, + }); + } + // Repeat the exact last execution after reset; chunk consistency and reset are separate invariants. + @memcpy(baseline, actual); + baseline_logits = logits; + try runChunks(&model, stream, tokens, 128, actual, &logits); + const reset_equal = std.mem.eql(u16, baseline, actual) and std.mem.eql(u8, std.mem.sliceAsBytes(&baseline_logits), std.mem.sliceAsBytes(&logits)); + var metadata: [512]u8 = undefined; + const text = try std.fmt.bufPrint(&metadata, "{{\"rows\":{d},\"hidden_width\":{d},\"eos\":{d},\"semantic_start\":{d},\"semantic_end\":{d},\"chunk_bit_exact\":{},\"reset_bit_exact\":{}}}\n", .{ tokens.len, width, model.eos, model.semantic_start, model.semantic_end, all_equal, reset_equal }); + try out.writeFile(init.io, .{ .sub_path = "native-metadata.json", .data = text }); + const used = cuda.usage(false); + std.debug.print("reset_bit_exact={} cuda_bytes={d} pinned_bytes={d}\n", .{ reset_equal, used.device, used.host }); + return if (all_equal and reset_equal) 0 else 1; +} diff --git a/zig/tests/cuda/drama_backbone_replay.zig b/zig/tests/cuda/drama_backbone_replay.zig new file mode 100644 index 00000000000..c330435d89e --- /dev/null +++ b/zig/tests/cuda/drama_backbone_replay.zig @@ -0,0 +1,449 @@ +//! Diagnostic: replays backbone attention and MoE operators on frozen native and reference stage inputs. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const Sha256 = std.crypto.hash.sha2.Sha256; +const Model = drama.backbone.Model; +const Stage = drama.backbone.Stage; +const Operator = drama.backbone.ReplayOperator; +const linear = drama.backbone.config.linear; +const replay_fixtures = @import("drama_backbone_replay_fixtures.zig"); +const Source = replay_fixtures.Source; +const loadSource = replay_fixtures.loadSource; +const loadTokens = replay_fixtures.loadTokens; + +pub const width = 2048; +const candidate_count = 4097; +pub const max_rows = 128; +pub const context = 512; +pub const rows = 182; +pub const tensor_bytes = rows * width * 2; +/// The forward's own layer array. +pub const layer_count = @typeInfo(@FieldType(@FieldType(Model, "w"), "layers")).array.len; +pub const contract_tokens_sha256 = "fe39111abb37fc10cb2e5c846313464c38fad13d92d44f082ef465d5b3baba86"; +const contract_name = "drama-backbone-replay-contract/1"; +pub const replay_layers = [_]usize{ 0, 3, 13, 39 }; +/// The native capture's chunks: Model.run over 182 rows at max_rows 128. +pub const chunks = [_]usize{ 128, 54 }; +const operators = std.meta.tags(Operator); +pub const Origin = enum(usize) { native, reference }; +const origins = std.meta.tags(Origin); +/// Stages read from each source directory per replayed layer: the operators' inputs and original outputs. +pub const used_stages = [_]Stage{ .attention_input, .attention_output, .mlp_input, .mlp_output }; + +comptime { + std.debug.assert(drama.backbone.config.hidden == width); + std.debug.assert(drama.backbone.weights.head_cols == candidate_count); + var total: usize = 0; + for (chunks) |c| { + std.debug.assert(c > 0 and c <= max_rows); + total += c; + } + std.debug.assert(total == rows and rows <= context); + for (replay_layers) |layer| std.debug.assert(layer < layer_count); +} + +fn inputStage(op: Operator) Stage { + return switch (op) { + .attention => .attention_input, + .moe => .mlp_input, + }; +} + +fn outputStage(op: Operator) Stage { + return switch (op) { + .attention => .attention_output, + .moe => .mlp_output, + }; +} + +/// The production method `Model.replayOperator` runs for this layer and operator. +fn methodName(layer: usize, op: Operator) []const u8 { + return switch (op) { + .attention => if (linear(layer)) "deltaNet" else "fullAttention", + .moe => "moe", + }; +} + +pub fn usedIndex(stage: Stage) usize { + for (used_stages, 0..) |s, i| { + if (s == stage) return i; + } + unreachable; +} + +pub fn stageFileName(buffer: []u8, layer: usize, stage: Stage) ![]u8 { + return std.fmt.bufPrint(buffer, "layer-{d:0>2}-{s}.bf16", .{ layer, @tagName(stage) }); +} + +/// Recorded failures that leave the outputs written but the evidence invalid. +pub const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + pub fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + const message = try std.fmt.allocPrint(e.gpa, f, args); + defer e.gpa.free(message); + std.debug.print("error: {s}\n", .{message}); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n " else ",\n "); + try jsonString(&e.json, e.gpa, message); + e.count += 1; + } +}; + +pub fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn nonfiniteF32(values: []const f32) usize { + var count: usize = 0; + for (values) |v| { + if (!std.math.isFinite(v)) count += 1; + } + return count; +} + +fn bf16(bits: u16) f64 { + return @as(f32, @bitCast(@as(u32, bits) << 16)); +} + +/// `got` against an original capture `want`, both BF16 [rows, width]. +const Comparison = struct { + bit_differences: usize = 0, + max_abs: f64 = 0, + /// ||got - want|| / ||want||. + relative_l2: f64 = 0, + min_row_cosine: f64 = 1, + min_row: usize = 0, + + fn of(got_bytes: []align(16) const u8, want_bytes: []align(16) const u8) Comparison { + const got = std.mem.bytesAsSlice(u16, got_bytes); + const want = std.mem.bytesAsSlice(u16, want_bytes); + var c: Comparison = .{}; + var diff_sq: f64 = 0; + var want_sq: f64 = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var gg: f64 = 0; + var ww: f64 = 0; + for (got[r * width ..][0..width], want[r * width ..][0..width]) |gb, wb| { + if (gb != wb) c.bit_differences += 1; + const g = bf16(gb); + const w = bf16(wb); + const d = g - w; + c.max_abs = @max(c.max_abs, @abs(d)); + diff_sq += d * d; + dot += g * w; + gg += g * g; + ww += w * w; + } + want_sq += ww; + const cosine: f64 = if (gg == 0 and ww == 0) 1 else if (gg == 0 or ww == 0) 0 else dot / (@sqrt(gg) * @sqrt(ww)); + if (r == 0 or cosine < c.min_row_cosine) { + c.min_row_cosine = cosine; + c.min_row = r; + } + } + c.relative_l2 = if (want_sq == 0) (if (diff_sq == 0) 0 else std.math.inf(f64)) else @sqrt(diff_sq / want_sq); + return c; + } + + fn json(c: Comparison, list: *std.ArrayList(u8), gpa: Allocator, want_sha: []const u8) !void { + try list.print(gpa, "{{\"original_sha256\": \"{s}\", \"bit_differences\": {d}, \"bit_exact\": {}, \"max_abs\": ", .{ want_sha, c.bit_differences, c.bit_differences == 0 }); + try jsonNumber(list, gpa, c.max_abs); + try list.appendSlice(gpa, ", \"relative_l2\": "); + try jsonNumber(list, gpa, c.relative_l2); + try list.appendSlice(gpa, ", \"min_row_cosine\": "); + try jsonNumber(list, gpa, c.min_row_cosine); + try list.print(gpa, ", \"min_row\": {d}}}", .{c.min_row}); + } +}; + +/// A finite number, else null (JSON has no NaN or infinity). +fn jsonNumber(list: *std.ArrayList(u8), gpa: Allocator, v: f64) !void { + if (std.math.isFinite(v)) try list.print(gpa, "{e}", .{v}) else try list.appendSlice(gpa, "null"); +} + +pub fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +fn nowNs(io: std.Io) i128 { + return std.Io.Clock.awake.now(io).toNanoseconds(); +} + +fn seconds(ns: i128) f64 { + return @as(f64, @floatFromInt(ns)) / 1e9; +} + +/// What the GPU phase measured besides the per-capture JSON. +const Gpu = struct { + after_init: cuda.Usage, + end: cuda.Usage, + replay_pinned_bytes: usize, + captures: usize, + replay_ns: i128, + run_after_replay_refused: bool, + replay_after_replay_refused: bool, + final_hidden_sha: [64]u8, + semantic_logits_sha: [64]u8, + production_bit_exact: bool, +}; + +fn replayAll(gpa: Allocator, io: std.Io, checkpoint: []const u8, sources: *const [origins.len]Source, tokens: []const u32, out: std.Io.Dir, errors: *Errors, captures: *std.ArrayList(u8), self_control: *std.ArrayList(u8)) !Gpu { + const native = &sources[@backingInt(Origin.native)]; + const reference = &sources[@backingInt(Origin.reference)]; + const hidden = try gpa.alloc(u16, rows * width); + defer gpa.free(hidden); + var logits: [candidate_count]f32 = undefined; + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try Model.init(gpa, io, &ctx, checkpoint, "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + if (model.hidden != width) return error.UnexpectedBackboneWidth; + const after_init = cuda.usage(false); + var input = try cuda.HostBuffer.alloc(&driver, tensor_bytes); + defer input.free(); + var output = try cuda.HostBuffer.alloc(&driver, tensor_bytes); + defer output.free(); + const in_bytes: []align(16) u8 = input.bytes[0..tensor_bytes]; + const out_bytes: []align(16) u8 = output.bytes[0..tensor_bytes]; + for (origins) |origin| try out.createDir(io, @tagName(origin), .default_dir); + + // 2-3. replay every origin, layer and operator from a fresh reset; compare against both original captures + var replay_ns: i128 = 0; + var count: usize = 0; + var name_buffer: [64]u8 = undefined; + var path_buffer: [96]u8 = undefined; + for (origins) |origin| { + const src = &sources[@backingInt(origin)]; + for (replay_layers, 0..) |layer, li| { + for (operators) |op| { + const in_stage = inputStage(op); + const out_stage = outputStage(op); + @memcpy(in_bytes, src.tensor(li, in_stage)); + @memset(out_bytes, 0xff); // BF16 NaN: a row the replay never wrote would show as nonfinite + try model.reset(stream); + const start = nowNs(io); + try model.replayOperator(stream, layer, op, &chunks, in_bytes, out_bytes); + const ns = nowNs(io) - start; + replay_ns += ns; + count += 1; + + const name = try stageFileName(&name_buffer, layer, out_stage); + const path = try std.fmt.bufPrint(&path_buffer, "{s}/{s}", .{ @tagName(origin), name }); + try out.writeFile(io, .{ .sub_path = path, .data = out_bytes, .flags = .{ .exclusive = true } }); + const sha = sha256Hex(out_bytes); + const nonfinite = nonfiniteBf16(std.mem.bytesAsSlice(u16, out_bytes)); + if (nonfinite != 0) try errors.add("{s}: {d} nonfinite values", .{ path, nonfinite }); + const vs_native = Comparison.of(out_bytes, native.tensor(li, out_stage)); + const vs_reference = Comparison.of(out_bytes, reference.tensor(li, out_stage)); + + try captures.print(gpa, "{s}\n {{\"origin\": \"{s}\", \"layer\": {d}, \"stage\": \"{s}\", \"method\": \"{s}\", \"input_stage\": \"{s}\", \"input_sha256\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"chunks\": [{d}, {d}], \"nonfinite\": {d}, \"replay_s\": {d:.6}, \"vs_native_original\": ", .{ + if (captures.items.len == 0) "" else ",", @tagName(origin), layer, @tagName(out_stage), methodName(layer, op), @tagName(in_stage), src.sha(li, in_stage), path, sha[0..], rows, width, chunks[0], chunks[1], nonfinite, seconds(ns), + }); + try vs_native.json(captures, gpa, native.sha(li, out_stage)); + try captures.appendSlice(gpa, ", \"vs_reference_original\": "); + try vs_reference.json(captures, gpa, reference.sha(li, out_stage)); + try captures.appendSlice(gpa, "}"); + + if (origin == .native) { + if (vs_native.bit_differences != 0) try errors.add("native self-control {s}: {d} bit differences vs the original native capture", .{ path, vs_native.bit_differences }); + try self_control.print(gpa, "{s}\n {{\"layer\": {d}, \"stage\": \"{s}\", \"method\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"original_sha256\": \"{s}\", \"bit_differences\": {d}, \"bit_exact\": {}}}", .{ + if (self_control.items.len == 0) "" else ",", layer, @tagName(out_stage), methodName(layer, op), path, sha[0..], native.sha(li, out_stage), vs_native.bit_differences, vs_native.bit_differences == 0, + }); + } + std.debug.print("{s}: {s} sha256={s} vs_native_bits={d} vs_reference_bits={d} replay_s={d:.6}\n", .{ path, methodName(layer, op), sha[0..], vs_native.bit_differences, vs_reference.bit_differences, seconds(ns) }); + } + } + } + if (count != origins.len * replay_layers.len * operators.len) try errors.add("{d} replays, expected {d}", .{ count, origins.len * replay_layers.len * operators.len }); + + // 4. poison guard, then the production run over the contract prompt + const run_refused = if (model.run(stream, .prefill, tokens[0..1], null)) |_| false else |err| err == error.DramaStateNeedsReset; + if (!run_refused) try errors.add("Model.run after a replay was not refused with DramaStateNeedsReset", .{}); + const replay_refused = if (model.replayOperator(stream, replay_layers[0], .moe, &chunks, in_bytes, out_bytes)) |_| false else |err| err == error.DramaStateNeedsReset; + if (!replay_refused) try errors.add("replayOperator after a replay was not refused with DramaStateNeedsReset", .{}); + try model.reset(stream); + var at: usize = 0; + for (chunks) |n| { + const result = try model.run(stream, .prefill, tokens[at..][0..n], null); + if (result.rows != n) return error.UnexpectedBackboneRows; + try result.hidden.download(0, std.mem.sliceAsBytes(hidden[at * width ..][0 .. n * width])); + at += n; + if (at == rows) try result.semantic_logits.download(0, std.mem.sliceAsBytes(&logits)); + } + const end = cuda.usage(false); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const logits_sha = sha256Hex(std.mem.sliceAsBytes(&logits)); + const hidden_nonfinite = nonfiniteBf16(hidden); + const logits_nonfinite = nonfiniteF32(&logits); + if (hidden_nonfinite != 0 or logits_nonfinite != 0) try errors.add("production control: {d} hidden and {d} logit nonfinite values", .{ hidden_nonfinite, logits_nonfinite }); + const hidden_equal = std.mem.eql(u8, &hidden_sha, native.final_hidden_sha.?); + const logits_equal = std.mem.eql(u8, &logits_sha, native.semantic_logits_sha.?); + if (!hidden_equal) try errors.add("production control: final hidden sha256 {s} differs from the native trace {s}", .{ hidden_sha[0..], native.final_hidden_sha.? }); + if (!logits_equal) try errors.add("production control: semantic logits sha256 {s} differ from the native trace {s}", .{ logits_sha[0..], native.semantic_logits_sha.? }); + return .{ + .after_init = after_init, + .end = end, + .replay_pinned_bytes = input.bytes.len + output.bytes.len, + .captures = count, + .replay_ns = replay_ns, + .run_after_replay_refused = run_refused, + .replay_after_replay_refused = replay_refused, + .final_hidden_sha = hidden_sha, + .semantic_logits_sha = logits_sha, + .production_bit_exact = hidden_equal and logits_equal, + }; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 5) { + std.debug.print("usage: tf-drama-backbone-replay CHECKPOINT NATIVE_STAGE_DIR REFERENCE_STAGE_DIR OUTPUT_DIR\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + // 1. fixtures + var sources: [origins.len]Source = undefined; + for (origins) |origin| sources[@backingInt(origin)] = try loadSource(arena, io, origin, args[2 + @backingInt(origin)], &errors); + const native = &sources[@backingInt(Origin.native)]; + const tokens = try loadTokens(arena, io, native, &errors); + var fixture_host_bytes: usize = 0; + for (sources) |src| { + for (src.tensors) |layer_tensors| { + for (layer_tensors) |t| fixture_host_bytes += if (t) |bytes| bytes.len else 0; + } + } + + var captures: std.ArrayList(u8) = .empty; + defer captures.deinit(gpa); + var self_control: std.ArrayList(u8) = .empty; + defer self_control.deinit(gpa); + const gpu: ?Gpu = if (errors.count == 0) + try replayAll(gpa, io, args[1], &sources, tokens.?, out, &errors, &captures, &self_control) + else blk: { + std.debug.print("fixture validation failed: no model load, no replay\n", .{}); + break :blk null; + }; + + // 5. manifest + const exe_path = "/proc/self/exe"; + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, exe_path)) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const backbone_source_sha = sha256Hex(drama.backbone.trace_source); + const replay_source_sha = sha256Hex(@embedFile("drama_backbone_replay.zig")); + const evidence_valid = errors.count == 0; + + var m: std.ArrayList(u8) = .empty; + defer m.deinit(gpa); + try m.print(gpa, "{{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-backbone-replay\",\n \"contract\": \"{s}\",\n \"checkpoint\": ", .{contract_name}); + try jsonString(&m, gpa, args[1]); + try m.appendSlice(gpa, ",\n \"origins\": ["); + for (sources, 0..) |src, i| { + try m.print(gpa, "{s}\n {{\"origin\": \"{s}\", \"stage_dir\": ", .{ if (i == 0) "" else ",", @tagName(src.origin) }); + try jsonString(&m, gpa, src.path); + if (src.manifest_sha) |sha| try m.print(gpa, ", \"manifest_sha256\": \"{s}\"", .{sha[0..]}) else try m.appendSlice(gpa, ", \"manifest_sha256\": null"); + try m.print(gpa, ", \"manifest_evidence_valid\": {}}}", .{src.manifest_evidence_valid}); + } + try m.appendSlice(gpa, "\n ],\n \"tokens_file\": "); + if (native.tokens_file) |path| try jsonString(&m, gpa, path) else try m.appendSlice(gpa, "null"); + try m.print(gpa, ",\n \"tokens_sha256\": {s}{s}{s},\n \"rows\": {d},\n \"width\": {d},\n \"dtype\": \"bf16le\",\n \"layer_count\": {d},\n \"layers\": [", .{ + if (tokens != null) "\"" else "", if (tokens != null) contract_tokens_sha256 else "null", if (tokens != null) "\"" else "", rows, width, layer_count, + }); + for (replay_layers, 0..) |layer, i| try m.print(gpa, "{s}{d}", .{ if (i == 0) "" else ", ", layer }); + try m.print(gpa, "],\n \"chunks\": [{d}, {d}],\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}}," ++ + "\n \"replay\": \"per origin, layer and operator: Model.reset, then Model.replayOperator, which uploads each chunk of the frozen input into Scratch.normed and runs the production method at request position row0; MoE replays the frozen mlp_input\"," ++ + "\n \"inputs\": [", .{ chunks[0], chunks[1], context, max_rows }); + var first = true; + var name_buffer: [64]u8 = undefined; + for (sources) |src| { + for (replay_layers, 0..) |layer, li| { + for (used_stages, 0..) |stage, si| { + if (src.tensors[li][si] == null) continue; + const name = try stageFileName(&name_buffer, layer, stage); + try m.print(gpa, "{s}\n {{\"origin\": \"{s}\", \"layer\": {d}, \"stage\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}]}}", .{ + if (first) "" else ",", @tagName(src.origin), layer, @tagName(stage), name, src.shas[li][si][0..], rows, width, + }); + first = false; + } + } + } + try m.print(gpa, "\n ],\n \"captures\": [{s}\n ],\n \"native_self_control\": [{s}\n ],", .{ captures.items, self_control.items }); + if (gpu) |g| { + try m.print(gpa, "\n \"production_control\": {{\"kind\": \"after all replays: Model.run and replayOperator without reset must be refused; then reset and production Model.run over the tokens_file in chunks 128 + 54\", \"run_after_replay_refused\": {}, \"replay_after_replay_refused\": {}, \"final_hidden_sha256\": \"{s}\", \"expected_final_hidden_sha256\": \"{s}\", \"semantic_logits_sha256\": \"{s}\", \"expected_semantic_logits_sha256\": \"{s}\", \"bit_exact\": {}}}," ++ + "\n \"timing_s\": {{\"replay_total\": {d:.6}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}, \"replay_pinned_bytes\": {d}, \"fixture_host_bytes\": {d}}},", .{ + g.run_after_replay_refused, g.replay_after_replay_refused, g.final_hidden_sha[0..], native.final_hidden_sha.?, g.semantic_logits_sha[0..], native.semantic_logits_sha.?, g.production_bit_exact, + seconds(g.replay_ns), g.after_init.device, g.end.device, g.end.peak, g.end.host, g.replay_pinned_bytes, fixture_host_bytes, + }); + } else { + try m.print(gpa, "\n \"production_control\": null,\n \"timing_s\": null,\n \"allocations\": {{\"cuda_device_bytes_after_init\": null, \"fixture_host_bytes\": {d}}},", .{fixture_host_bytes}); + } + try m.print(gpa, "\n \"binary_sha256\": {s},\n \"backbone_source_sha256\": \"{s}\",\n \"replay_source_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ binary_json.items, backbone_source_sha[0..], replay_source_sha[0..], evidence_valid, errors.json.items }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = m.items, .flags = .{ .exclusive = true } }); + + std.debug.print("replays={d} evidence_valid={} errors={d}\n", .{ if (gpu) |g| g.captures else 0, evidence_valid, errors.count }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_backbone_replay_fixtures.zig b/zig/tests/cuda/drama_backbone_replay_fixtures.zig new file mode 100644 index 00000000000..fd838335303 --- /dev/null +++ b/zig/tests/cuda/drama_backbone_replay_fixtures.zig @@ -0,0 +1,219 @@ +//! tf-drama-backbone-replay's fixtures: both stage manifests, their captures and the contract prompt, checked on CPU. +const std = @import("std"); +const drama = @import("drama"); +const Allocator = std.mem.Allocator; +const Stage = drama.backbone.Stage; +const backbone_replay = @import("drama_backbone_replay.zig"); +const width = backbone_replay.width; +const max_rows = backbone_replay.max_rows; +const context = backbone_replay.context; +const rows = backbone_replay.rows; +const tensor_bytes = backbone_replay.tensor_bytes; +const layer_count = backbone_replay.layer_count; +const contract_tokens_sha256 = backbone_replay.contract_tokens_sha256; +const replay_layers = backbone_replay.replay_layers; +const chunks = backbone_replay.chunks; +const Origin = backbone_replay.Origin; +const used_stages = backbone_replay.used_stages; +const usedIndex = backbone_replay.usedIndex; +const stageFileName = backbone_replay.stageFileName; +const Errors = backbone_replay.Errors; +const nonfiniteBf16 = backbone_replay.nonfiniteBf16; +const sha256Hex = backbone_replay.sha256Hex; + +/// One stage directory's validated fixtures. A null tensor failed validation (and recorded why). +pub const Source = struct { + origin: Origin, + path: []const u8, + manifest_sha: ?[64]u8 = null, + manifest_evidence_valid: bool = false, + tensors: [replay_layers.len][used_stages.len]?[]align(16) const u8 = @splat(@splat(null)), + shas: [replay_layers.len][used_stages.len][64]u8 = undefined, + /// Native only: the prompt and the production run's final outputs the trace recorded. + tokens_file: ?[]const u8 = null, + final_hidden_sha: ?[]const u8 = null, + semantic_logits_sha: ?[]const u8 = null, + + pub fn tensor(s: *const Source, li: usize, stage: Stage) []align(16) const u8 { + return s.tensors[li][usedIndex(stage)].?; + } + + pub fn sha(s: *const Source, li: usize, stage: Stage) []const u8 { + return &s.shas[li][usedIndex(stage)]; + } +}; + +fn jsonUint(v: ?std.json.Value, expected: u64) bool { + const value = v orelse return false; + return value == .integer and value.integer >= 0 and @as(u64, @intCast(value.integer)) == expected; +} + +fn jsonText(v: ?std.json.Value) ?[]const u8 { + const value = v orelse return null; + return if (value == .string) value.string else null; +} + +fn isSha256Hex(s: []const u8) bool { + if (s.len != 64) return false; + for (s) |c| switch (c) { + '0'...'9', 'a'...'f' => {}, + else => return false, + }; + return true; +} + +fn expectUint(errors: *Errors, origin: Origin, o: std.json.ObjectMap, key: []const u8, expected: u64) !void { + if (!jsonUint(o.get(key), expected)) try errors.add("{s} manifest: {s} is not {d}", .{ @tagName(origin), key, expected }); +} + +fn expectText(errors: *Errors, origin: Origin, o: std.json.ObjectMap, key: []const u8, expected: []const u8) !void { + const got = jsonText(o.get(key)) orelse ""; + if (!std.mem.eql(u8, got, expected)) try errors.add("{s} manifest: {s} is not {s}", .{ @tagName(origin), key, expected }); +} + +/// A nested object's string field, or null after recording the failure. +fn nestedText(errors: *Errors, origin: Origin, o: std.json.ObjectMap, outer: []const u8, inner: []const u8) !?[]const u8 { + if (o.get(outer)) |v| { + if (v == .object) { + if (jsonText(v.object.get(inner))) |s| return s; + } + } + try errors.add("{s} manifest: {s}.{s} missing or not a string", .{ @tagName(origin), outer, inner }); + return null; +} + +fn jsonChunks(v: std.json.Value) bool { + if (v != .array or v.array.items.len != chunks.len) return false; + for (v.array.items, chunks) |item, c| { + if (!jsonUint(item, c)) return false; + } + return true; +} + +pub fn loadSource(arena: Allocator, io: std.Io, origin: Origin, path: []const u8, errors: *Errors) !Source { + var src: Source = .{ .origin = origin, .path = path }; + const dir = std.Io.Dir.cwd().openDir(io, path, .{}) catch |err| { + try errors.add("{s}: stage directory {s} unreadable: {s}", .{ @tagName(origin), path, @errorName(err) }); + return src; + }; + defer dir.close(io); + const text = dir.readFileAlloc(io, "manifest.json", arena, .limited(1 << 24)) catch |err| { + try errors.add("{s}: manifest.json unreadable: {s}", .{ @tagName(origin), @errorName(err) }); + return src; + }; + src.manifest_sha = sha256Hex(text); + const doc = std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}) catch |err| { + try errors.add("{s}: manifest.json is not JSON: {s}", .{ @tagName(origin), @errorName(err) }); + return src; + }; + if (doc != .object) { + try errors.add("{s}: manifest.json is not an object", .{@tagName(origin)}); + return src; + } + const root = doc.object; + try expectUint(errors, origin, root, "schema_version", 1); + try expectUint(errors, origin, root, "rows", rows); + try expectUint(errors, origin, root, "width", width); + try expectUint(errors, origin, root, "layer_count", layer_count); + try expectText(errors, origin, root, "dtype", "bf16le"); + try expectText(errors, origin, root, "tokens_sha256", contract_tokens_sha256); + src.manifest_evidence_valid = if (root.get("evidence_valid")) |v| v == .bool and v.bool else false; + if (!src.manifest_evidence_valid) try errors.add("{s} manifest: evidence_valid is not true", .{@tagName(origin)}); + if (origin == .native) { + const options_ok = if (root.get("model_options")) |v| v == .object and jsonUint(v.object.get("context"), context) and jsonUint(v.object.get("max_rows"), max_rows) else false; + if (!options_ok) try errors.add("native manifest: model_options is not context {d} max_rows {d}", .{ context, max_rows }); + const chunks_ok = if (root.get("chunks")) |v| jsonChunks(v) else false; + if (!chunks_ok) try errors.add("native manifest: chunks is not [128, 54]", .{}); + src.tokens_file = jsonText(root.get("tokens_file")); + if (src.tokens_file == null) try errors.add("native manifest: tokens_file missing", .{}); + src.final_hidden_sha = try nestedText(errors, origin, root, "final_hidden", "sha256"); + src.semantic_logits_sha = try nestedText(errors, origin, root, "semantic_logits", "sha256"); + } + const captures = root.get("captures") orelse std.json.Value{ .null = {} }; + if (captures != .array) { + try errors.add("{s} manifest: captures is not an array", .{@tagName(origin)}); + return src; + } + for (replay_layers, 0..) |layer, li| { + for (used_stages, 0..) |stage, si| { + src.tensors[li][si] = try loadCapture(arena, io, dir, origin, captures.array.items, layer, stage, errors, &src.shas[li][si]); + } + } + return src; +} + +/// One stage file checked against its unique manifest entry; null after recording any failure. +fn loadCapture(arena: Allocator, io: std.Io, dir: std.Io.Dir, origin: Origin, captures: []const std.json.Value, layer: usize, stage: Stage, errors: *Errors, sha_out: *[64]u8) !?[]align(16) const u8 { + const tag = @tagName(origin); + var name_buffer: [64]u8 = undefined; + const name = try stageFileName(&name_buffer, layer, stage); + var entry: ?std.json.ObjectMap = null; + var matches: usize = 0; + for (captures) |c| { + if (c != .object) continue; + const stage_name = jsonText(c.object.get("stage")) orelse continue; + if (jsonUint(c.object.get("layer"), layer) and std.mem.eql(u8, stage_name, @tagName(stage))) { + entry = c.object; + matches += 1; + } + } + if (matches != 1) { + try errors.add("{s} {s}: {d} manifest captures, expected exactly 1", .{ tag, name, matches }); + return null; + } + const e = entry.?; + const file = jsonText(e.get("file")) orelse ""; + if (!std.mem.eql(u8, file, name)) { + try errors.add("{s} {s}: manifest file is {s}", .{ tag, name, file }); + return null; + } + const want = jsonText(e.get("sha256")) orelse ""; + if (!isSha256Hex(want)) { + try errors.add("{s} {s}: manifest sha256 is not 64 lowercase hex digits", .{ tag, name }); + return null; + } + const shape_ok = if (e.get("shape")) |v| v == .array and v.array.items.len == 2 and jsonUint(v.array.items[0], rows) and jsonUint(v.array.items[1], width) else false; + if (!shape_ok) { + try errors.add("{s} {s}: manifest shape is not [{d}, {d}]", .{ tag, name, rows, width }); + return null; + } + const bytes = dir.readFileAllocOptions(io, name, arena, .limited(tensor_bytes + 1), .@"16", null) catch |err| { + try errors.add("{s} {s}: unreadable or larger than {d} bytes: {s}", .{ tag, name, tensor_bytes, @errorName(err) }); + return null; + }; + if (bytes.len != tensor_bytes) { + try errors.add("{s} {s}: {d} bytes, expected {d}", .{ tag, name, bytes.len, tensor_bytes }); + return null; + } + const got = sha256Hex(bytes); + if (!std.mem.eql(u8, &got, want)) { + try errors.add("{s} {s}: sha256 {s} does not match manifest {s}", .{ tag, name, got[0..], want }); + return null; + } + const nonfinite = nonfiniteBf16(std.mem.bytesAsSlice(u16, bytes)); + if (nonfinite != 0) { + try errors.add("{s} {s}: {d} nonfinite values", .{ tag, name, nonfinite }); + return null; + } + sha_out.* = got; + return bytes; +} + +/// The contract prompt, from the native manifest's tokens_file; null after recording any failure. +pub fn loadTokens(arena: Allocator, io: std.Io, native: *const Source, errors: *Errors) !?[]const u32 { + const path = native.tokens_file orelse return null; + const bytes = std.Io.Dir.cwd().readFileAllocOptions(io, path, arena, .limited(context * 4 + 1), .@"16", null) catch |err| { + try errors.add("tokens file {s} unreadable: {s}", .{ path, @errorName(err) }); + return null; + }; + if (bytes.len != rows * 4) { + try errors.add("tokens file {s}: {d} bytes, expected {d}", .{ path, bytes.len, rows * 4 }); + return null; + } + const got = sha256Hex(bytes); + if (!std.mem.eql(u8, &got, contract_tokens_sha256)) { + try errors.add("tokens file {s}: sha256 {s} is not the contract prompt", .{ path, got[0..] }); + return null; + } + return std.mem.bytesAsSlice(u32, bytes); +} diff --git a/zig/tests/cuda/drama_backbone_trace.zig b/zig/tests/cuda/drama_backbone_trace.zig new file mode 100644 index 00000000000..d13738420a4 --- /dev/null +++ b/zig/tests/cuda/drama_backbone_trace.zig @@ -0,0 +1,329 @@ +//! Diagnostic: captures six stages of every backbone layer from the production forward, checked against run. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const Model = drama.backbone.Model; +const Stage = drama.backbone.Stage; + +const width = 2048; +const candidate_count = 4097; +const max_rows = 128; +const context = 512; +const stages = std.meta.tags(Stage); +const stage_count = stages.len; +/// The forward's own layer array: every layer it iterates is captured. +const layer_count = @typeInfo(@FieldType(@FieldType(Model, "w"), "layers")).array.len; +const contract_tokens_sha256 = "fe39111abb37fc10cb2e5c846313464c38fad13d92d44f082ef465d5b3baba86"; + +comptime { + std.debug.assert(drama.backbone.config.hidden == width); + std.debug.assert(drama.backbone.weights.head_cols == candidate_count); +} + +/// What each stage file holds, in `Model.forward`'s terms. +const stage_sources = + \\{"attention_input": "Scratch.normed after addNorm(x, residual, ln1): input RMSNorm output", + \\ "attention_residual": "Scratch.residual after addNorm(x, residual, ln1): updated residual (layer 0: the embedding)", + \\ "attention_output": "Scratch.x after deltaNet or fullAttention: out projection, before the second add-norm", + \\ "mlp_input": "Scratch.normed after addNorm(x, residual, ln2): post-attention RMSNorm output", + \\ "mlp_residual": "Scratch.residual after addNorm(x, residual, ln2): updated residual", + \\ "mlp_output": "Scratch.x after moe: routed experts combined with the sigmoid-gated shared expert"} +; + +/// Recorded failures that leave the files written but the evidence invalid. Messages hold no quote or backslash. +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +/// The runTraced tracer: each (layer, stage) file is written at its rows' offset and hashed as it goes. +const Tracer = struct { + io: std.Io, + dir: std.Io.Dir, + rows: usize, + /// Pinned, max_rows * width * 2 bytes: the target of the stream-ordered copy. + staging: []align(16) u8, + /// Rows captured so far per (layer, stage); a capture must start exactly there. + next_row: [slots]usize = @splat(0), + hashes: [slots]std.crypto.hash.sha2.Sha256 = @splat(std.crypto.hash.sha2.Sha256.init(.{})), + nonfinite: [slots]usize = @splat(0), + captures: usize = 0, + written: usize = 0, + + const slots = layer_count * stage_count; + + fn slotOf(layer: usize, stage: Stage) usize { + return layer * stage_count + @backingInt(stage); + } + + fn fileName(buffer: []u8, layer: usize, stage: Stage) ![]u8 { + return std.fmt.bufPrint(buffer, "layer-{d:0>2}-{s}.bf16", .{ layer, @tagName(stage) }); + } + + pub fn capture(t: *Tracer, stream: cuda.Stream, layer: usize, stage: Stage, src: cuda.DeviceBuffer, row0: usize) !void { + if (layer >= layer_count) return error.TraceLayerOutOfRange; + if (src.len == 0 or src.len % (width * 2) != 0 or src.len > t.staging.len) return error.TraceCaptureShape; + const n = src.len / (width * 2); + if (row0 > t.rows or n > t.rows - row0) return error.TraceRowsOutOfRange; + const at = slotOf(layer, stage); + if (row0 != t.next_row[at]) return error.TraceDuplicateOrMissingRows; + // Queued behind the stage's kernel and ahead of the next one, then drained before the forward continues. + const bytes = t.staging[0..src.len]; + try src.downloadAsync(0, bytes, stream.handle); + try stream.synchronize(); + var name_buffer: [64]u8 = undefined; + const name = try fileName(&name_buffer, layer, stage); + const file = if (row0 == 0) + try t.dir.createFile(t.io, name, .{ .exclusive = true }) + else + try t.dir.openFile(t.io, name, .{ .mode = .write_only }); + defer file.close(t.io); + try file.writePositionalAll(t.io, bytes, row0 * width * 2); + t.hashes[at].update(bytes); + t.nonfinite[at] += nonfiniteBf16(std.mem.bytesAsSlice(u16, bytes)); + t.next_row[at] = row0 + n; + t.captures += 1; + t.written += bytes.len; + } +}; + +/// Reset, then the whole prompt in max_rows chunks: `Model.run` for a void trace, else `Model.runTraced`. +fn runPrompt(model: *Model, stream: cuda.Stream, tokens: []const u32, trace: anytype, hidden: []u16, logits: *[candidate_count]f32) !void { + try model.reset(stream); + var at: usize = 0; + while (at < tokens.len) { + const end = @min(at + max_rows, tokens.len); + const output = if (@TypeOf(trace) == void) + try model.run(stream, .prefill, tokens[at..end], null) + else + try model.runTraced(stream, .prefill, tokens[at..end], null, trace); + if (output.rows != end - at) return error.UnexpectedBackboneRows; + try output.hidden.download(0, std.mem.sliceAsBytes(hidden[at * width .. end * width])); + if (end == tokens.len) try output.semantic_logits.download(0, std.mem.sliceAsBytes(logits)); + at = end; + } +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn nonfiniteF32(values: []const f32) usize { + var count: usize = 0; + for (values) |v| { + if (!std.math.isFinite(v)) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// Writes one new file and returns its SHA-256. +fn emit(dir: std.Io.Dir, io: std.Io, name: []const u8, data: []const u8) ![64]u8 { + try dir.writeFile(io, .{ .sub_path = name, .data = data, .flags = .{ .exclusive = true } }); + return sha256Hex(data); +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-backbone-trace CHECKPOINT TOKENS_U32LE OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + + var bytes: [context * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(io, args[2], .{}); + defer input.close(io); + const count = try input.readPositionalAll(io, &bytes, 0); + if (count < 8 or count > context * 4 or count % 4 != 0) return error.ExpectedTwoTo512Tokens; + const tokens = std.mem.bytesAsSlice(u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + const tokens_sha = sha256Hex(bytes[0..count]); + const rows = tokens.len; + const chunks = (rows + max_rows - 1) / max_rows; + const out = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer out.close(io); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + if (!std.mem.eql(u8, &tokens_sha, contract_tokens_sha256)) try errors.add("tokens_sha256 {s} is not the contract prompt {s}", .{ tokens_sha[0..], contract_tokens_sha256 }); + + const traced_hidden = try gpa.alloc(u16, rows * width); + defer gpa.free(traced_hidden); + const plain_hidden = try gpa.alloc(u16, rows * width); + defer gpa.free(plain_hidden); + const trace_host_bytes = (traced_hidden.len + plain_hidden.len) * 2 + @sizeOf(Tracer); + var traced_logits: [candidate_count]f32 = undefined; + var plain_logits: [candidate_count]f32 = undefined; + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + if (model.hidden != width) return error.UnexpectedBackboneWidth; + for (tokens) |token| if (token >= model.semantic_start and token <= model.semantic_end) return error.TextFixtureMustNotContainSemanticTokens; + const model_usage = cuda.usage(false); + var staging = try cuda.HostBuffer.alloc(&driver, max_rows * width * 2); + defer staging.free(); + + // 1. traced + var tracer: Tracer = .{ .io = io, .dir = out, .rows = rows, .staging = staging.bytes }; + const traced_start = std.Io.Clock.awake.now(io).toNanoseconds(); + try runPrompt(&model, stream, tokens, &tracer, traced_hidden, &traced_logits); + const traced_ns = std.Io.Clock.awake.now(io).toNanoseconds() - traced_start; + + // 2. control: production run, no tracer + const plain_start = std.Io.Clock.awake.now(io).toNanoseconds(); + try runPrompt(&model, stream, tokens, {}, plain_hidden, &plain_logits); + const plain_ns = std.Io.Clock.awake.now(io).toNanoseconds() - plain_start; + const used = cuda.usage(false); + + var hidden_differences: usize = 0; + for (traced_hidden, plain_hidden) |a, b| { + if (a != b) hidden_differences += 1; + } + const logits_equal = std.mem.eql(u8, std.mem.sliceAsBytes(&traced_logits), std.mem.sliceAsBytes(&plain_logits)); + const control_exact = hidden_differences == 0 and logits_equal; + if (!control_exact) try errors.add("traced vs untraced: {d} final hidden bit differences, semantic logits bit equal {}", .{ hidden_differences, logits_equal }); + if (tracer.captures != layer_count * stage_count * chunks) try errors.add("{d} captures, expected {d}", .{ tracer.captures, layer_count * stage_count * chunks }); + + // 3. manifest entries for the stage files the tracer wrote; then the final outputs + var captures: std.ArrayList(u8) = .empty; + defer captures.deinit(gpa); + var name_buffer: [64]u8 = undefined; + for (0..layer_count) |layer| { + for (stages) |stage| { + const name = try Tracer.fileName(&name_buffer, layer, stage); + const at = Tracer.slotOf(layer, stage); + const got = tracer.next_row[at]; + if (got != rows) try errors.add("{s}: captured {d} of {d} rows", .{ name, got, rows }); + const nonfinite = tracer.nonfinite[at]; + if (nonfinite != 0) try errors.add("{s}: {d} nonfinite values", .{ name, nonfinite }); + const sha = std.fmt.bytesToHex(tracer.hashes[at].finalResult(), .lower); + try captures.print(gpa, "{s}\n {{\"layer\": {d}, \"stage\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"rows_captured\": {d}, \"nonfinite\": {d}}}", .{ + if (captures.items.len == 0) "" else ",", layer, @tagName(stage), name, sha[0..], rows, width, got, nonfinite, + }); + } + } + var written = tracer.written; + const finals = [_]struct { name: []const u8, bytes: []const u8, nonfinite: usize }{ + .{ .name = "final-hidden.bf16", .bytes = std.mem.sliceAsBytes(traced_hidden), .nonfinite = nonfiniteBf16(traced_hidden) }, + .{ .name = "semantic-logits.f32", .bytes = std.mem.sliceAsBytes(&traced_logits), .nonfinite = nonfiniteF32(&traced_logits) }, + .{ .name = "untraced-final-hidden.bf16", .bytes = std.mem.sliceAsBytes(plain_hidden), .nonfinite = nonfiniteBf16(plain_hidden) }, + .{ .name = "untraced-semantic-logits.f32", .bytes = std.mem.sliceAsBytes(&plain_logits), .nonfinite = nonfiniteF32(&plain_logits) }, + }; + var final_sha: [finals.len][64]u8 = undefined; + for (finals, &final_sha) |f, *sha| { + if (f.nonfinite != 0) try errors.add("{s}: {d} nonfinite values", .{ f.name, f.nonfinite }); + sha.* = try emit(out, io, f.name, f.bytes); + written += f.bytes.len; + } + + const exe_path = "/proc/self/exe"; + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, exe_path)) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const backbone_source_sha = sha256Hex(drama.backbone.trace_source); + const trace_source_sha = sha256Hex(@embedFile("drama_backbone_trace.zig")); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-backbone-trace\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"tokens_file\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"tokens_sha256\": \"{s}\",\n \"contract_tokens_sha256\": \"{s}\",\n \"rows\": {d},\n \"width\": {d},\n \"dtype\": \"bf16le\",\n \"layer_count\": {d}," ++ + "\n \"stages\": [", .{ tokens_sha[0..], contract_tokens_sha256, rows, width, layer_count }); + for (stages, 0..) |stage, i| try manifest.print(gpa, "{s}\"{s}\"", .{ if (i == 0) "" else ", ", @tagName(stage) }); + try manifest.print(gpa, "],\n \"stage_sources\": {s},\n \"row_order\": \"logical request position; each chunk's rows land at Model.pos\"," ++ + "\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"chunks\": [", .{ stage_sources, context, max_rows }); + for (0..chunks) |c| try manifest.print(gpa, "{s}{d}", .{ if (c == 0) "" else ", ", @min(max_rows, rows - c * max_rows) }); + try manifest.print(gpa, "],\n \"eos\": {d},\n \"semantic_start\": {d},\n \"semantic_end\": {d},\n \"captures\": [{s}\n ]," ++ + "\n \"final_hidden\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"dtype\": \"bf16le\", \"source\": \"Model.run Rows.hidden, final RMSNorm, traced run\"}}," ++ + "\n \"semantic_logits\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}], \"dtype\": \"f32le\", \"row\": {d}, \"layout\": \"EOS then semantic_start..semantic_end\", \"source\": \"Model.run Rows.semantic_logits, last row, traced run\"}},", .{ + model.eos, model.semantic_start, model.semantic_end, captures.items, + finals[0].name, final_sha[0][0..], rows, width, + finals[1].name, final_sha[1][0..], candidate_count, rows - 1, + }); + try manifest.print(gpa, "\n \"control\": {{\"kind\": \"reset, then production Model.run (void trace) over the same chunks\", \"untraced_final_hidden\": {{\"file\": \"{s}\", \"sha256\": \"{s}\"}}, \"untraced_semantic_logits\": {{\"file\": \"{s}\", \"sha256\": \"{s}\"}}, \"final_hidden_bit_differences\": {d}, \"semantic_logits_bit_equal\": {}, \"traced_untraced_bit_exact\": {}}}," ++ + "\n \"timing_s\": {{\"traced\": {d:.6}, \"untraced\": {d:.6}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}, \"trace_staging_pinned_bytes\": {d}, \"trace_host_bytes\": {d}}}," ++ + "\n \"binary_sha256\": {s},\n \"backbone_source_sha256\": \"{s}\",\n \"trace_source_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + finals[2].name, final_sha[2][0..], finals[3].name, final_sha[3][0..], + hidden_differences, logits_equal, control_exact, @as(f64, @floatFromInt(traced_ns)) / 1e9, + @as(f64, @floatFromInt(plain_ns)) / 1e9, model_usage.device, used.device, used.peak, + used.host, staging.bytes.len, trace_host_bytes, binary_json.items, + backbone_source_sha[0..], trace_source_sha[0..], evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + + std.debug.print("rows={d} chunks={d} layers={d} captures={d} bytes_written={d} traced_s={d:.6} untraced_s={d:.6} final_hidden_bit_differences={d} semantic_logits_bit_equal={} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d} pinned_bytes={d}\n", .{ + rows, chunks, layer_count, tracer.captures, written + manifest.items.len, + @as(f64, @floatFromInt(traced_ns)) / 1e9, @as(f64, @floatFromInt(plain_ns)) / 1e9, hidden_differences, logits_equal, evidence_valid, + errors.count, used.device, used.peak, used.host, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_codec_oracle.zig b/zig/tests/cuda/drama_codec_oracle.zig new file mode 100644 index 00000000000..eb8f342faca --- /dev/null +++ b/zig/tests/cuda/drama_codec_oracle.zig @@ -0,0 +1,48 @@ +//! Decodes fixed code prefixes (1024 rows of ten u32) through the production codec to f32 PCM. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-codec-oracle CHECKPOINT CODES_U32LE OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [1024 * 10 * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(init.io, args[2], .{}); + defer input.close(init.io); + const count = try input.readPositionalAll(init.io, &bytes, 0); + if (count != 1024 * 10 * 4) return error.Expected1024Frames; + const codes = std.mem.bytesAsSlice([10]u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + var output_dir = try std.Io.Dir.cwd().openDir(init.io, args[3], .{}); + defer output_dir.close(init.io); + const pcm = try init.gpa.alloc(f32, 1024 * 2048); + defer init.gpa.free(pcm); + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var codec = try drama.codec.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .max_frames = 1024 }); + defer codec.deinit(); + for ([_]usize{ 1, 2, 7, 128, 1024 }) |frames| { + const begin = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const samples = try codec.decode(stream, codes[0..frames], pcm); + const elapsed = std.Io.Clock.awake.now(init.io).toNanoseconds() - begin; + if (samples != frames * 2048) return error.UnexpectedSampleCount; + for (pcm[0..samples]) |sample| if (!std.math.isFinite(sample)) return error.NonFiniteAudio; + var name_buffer: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buffer, "native-{d}.f32", .{frames}); + try output_dir.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(pcm[0..samples]) }); + const used = cuda.usage(false); + std.debug.print("frames={d} samples={d} elapsed_s={d:.6} cuda_bytes={d} pinned_bytes={d}\n", .{ + frames, samples, @as(f64, @floatFromInt(elapsed)) / 1e9, used.device, used.host, + }); + } + return 0; +} diff --git a/zig/tests/cuda/drama_codec_rvq_replay.zig b/zig/tests/cuda/drama_codec_rvq_replay.zig new file mode 100644 index 00000000000..e2e4bcdc0f2 --- /dev/null +++ b/zig/tests/cuda/drama_codec_rvq_replay.zig @@ -0,0 +1,114 @@ +//! Diagnostic: swaps only the RVQ function of a production codec instance. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +fn hash(bytes: []const u8) [64]u8 { + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + return std.fmt.bytesToHex(digest, .lower); +} + +fn weightHash(model: *drama.codec.Model, stream: cuda.Stream) ![64]u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: usize = 0; + while (offset < model.weights.len) { + const n = @min(model.audio_host.bytes.len, model.weights.len - offset); + const staging = model.audio_host.bytes[0..n]; + try model.weights.downloadAsync(offset, staging, stream.handle); + try stream.synchronize(); + h.update(staging); + offset += n; + } + return std.fmt.bytesToHex(h.finalResult(), .lower); +} + +fn save(dir: std.Io.Dir, io: std.Io, name: []const u8, bytes: []const u8) !void { + const file = try dir.createFile(io, name, .{ .exclusive = true }); + defer file.close(io); + try file.writePositionalAll(io, bytes, 0); +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 5) { + std.debug.print("usage: tf-drama-codec-rvq-replay CHECKPOINT CODES_U32LE SHADOW_FATBIN OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [1024 * 10 * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(init.io, args[2], .{}); + defer input.close(init.io); + const count = try input.readPositionalAll(init.io, &bytes, 0); + if (count != 1024 * 10 * 4) return error.Expected1024Frames; + const codes = std.mem.bytesAsSlice([10]u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + const codes_hash = hash(bytes[0..count]); + var dir = try std.Io.Dir.cwd().openDir(init.io, args[4], .{}); + defer dir.close(init.io); + const pcm = try init.gpa.alloc(f32, 1024 * 2048 + 16); + defer init.gpa.free(pcm); + const image = try std.Io.Dir.cwd().readFileAllocOptions(init.io, args[3], init.gpa, .limited(1 << 28), .@"16", null); + defer init.gpa.free(image); + _ = try cuda.setAllocationLimit(4 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var shadow = try cuda.Module.load(&driver, image); + defer shadow.unload(); + const candidate = try shadow.function("drama_codec_rvq_latent_fp64_shadow"); + var codec = try drama.codec.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .max_frames = 1024 }); + defer codec.deinit(); + const original = codec.kernels.rvq; + defer codec.kernels.rvq = original; + const weights_before = try weightHash(&codec, stream); + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(init.gpa); + try manifest.print(init.gpa, "{{\"schema\":1,\"codes_sha256\":\"{s}\",\"weights_before_sha256\":\"{s}\",\"shadow_sha256\":\"{s}\",\"allocation_cap_bytes\":{d},\"runs\":[\n", .{ codes_hash, weights_before, hash(image), @as(u64, 4) << 30 }); + var first = true; + for ([_]usize{ 1, 2, 7, 128, 1024 }) |frames| { + for ([_][]const u8{ "baseline", "baseline_repeat", "candidate", "candidate_repeat", "restored" }, 0..) |label, phase| { + codec.kernels.rvq = if (phase == 2 or phase == 3) candidate else original; + const samples = frames * 2048; + const sentinel: f32 = @bitCast(@as(u32, 0x7fc0dead)); + @memset(pcm[0 .. samples + 16], sentinel); + const begin = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const written = try codec.decode(stream, codes[0..frames], pcm); + const elapsed = std.Io.Clock.awake.now(init.io).toNanoseconds() - begin; + if (written != samples) return error.UnexpectedSampleCount; + for (pcm[0..samples]) |v| if (!std.math.isFinite(v)) return error.NonFiniteAudio; + for (pcm[samples .. samples + 16]) |v| if (@as(u32, @bitCast(v)) != 0x7fc0dead) return error.OutputOverrun; + const code_bytes = std.mem.sliceAsBytes(codes[0..frames]); + try codec.codes_dev.downloadAsync(0, codec.codes_host.bytes[0..code_bytes.len], stream.handle); + try stream.synchronize(); + if (!std.mem.eql(u8, code_bytes, codec.codes_host.bytes[0..code_bytes.len])) return error.CodesChanged; + var name_buf: [80]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "{s}-{d}.f32", .{ label, frames }); + const audio = std.mem.sliceAsBytes(pcm[0..samples]); + try save(dir, init.io, name, audio); + const used = cuda.usage(false); + try manifest.print(init.gpa, "{s}{{\"phase\":\"{s}\",\"frames\":{d},\"samples\":{d},\"pcm_sha256\":\"{s}\",\"elapsed_s\":{d:.9},\"cuda_bytes\":{d},\"pinned_bytes\":{d},\"finite\":true,\"sentinel_untouched\":true,\"codes_unchanged\":true}}\n", .{ if (first) "" else ",", label, frames, written, hash(audio), @as(f64, @floatFromInt(elapsed)) / 1e9, used.device, used.host }); + first = false; + if (phase == 0 or phase == 2) { + // The RVQ latent alone, from an isolated launch of the function this phase decodes with. + const w = codec.w; + const base = codec.weights.ptr; + try codec.kernels.rvqLatent(stream, codec.codes_dev.ptr, base + w.semantic_book, base + w.residual_books, base + w.out_w, base + w.out_b, codec.acts[0].ptr, frames); + const latent = codec.audio_host.bytes[0 .. frames * 1024 * 2]; + try codec.acts[0].downloadAsync(0, latent, stream.handle); + try stream.synchronize(); + const latent_name = try std.fmt.bufPrint(&name_buf, "{s}-{d}.latent.f16", .{ label, frames }); + try save(dir, init.io, latent_name, latent); + } + } + } + const weights_after = try weightHash(&codec, stream); + if (!std.mem.eql(u8, &weights_before, &weights_after)) return error.WeightsChanged; + if (!std.mem.eql(u8, &codes_hash, &hash(bytes[0..count]))) return error.HostCodesChanged; + try manifest.print(init.gpa, "],\"weights_after_sha256\":\"{s}\",\"weights_unchanged\":true,\"host_codes_unchanged\":true}}\n", .{weights_after}); + try save(dir, init.io, "manifest.json", manifest.items); + return 0; +} diff --git a/zig/tests/cuda/drama_codec_stream_oracle.zig b/zig/tests/cuda/drama_codec_stream_oracle.zig new file mode 100644 index 00000000000..203d0287fcf --- /dev/null +++ b/zig/tests/cuda/drama_codec_stream_oracle.zig @@ -0,0 +1,106 @@ +//! Whole and chunked codec decodes of 1024 frame codes, each chunk over NaN-poisoned scratch; GPU lock is the caller's. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; + +const frames = 1024; +const samples_per_frame = 2048; +const lengths = [_]usize{ 1, 2, 7, 128, 1024 }; + +const Schedule = struct { name: []const u8, chunks: []const usize }; + +/// The host's policy (1, then 4s), one frame at a time, the gate lengths as chunk ends, one call, irregular sizes. +fn schedules(a: Allocator) ![5]Schedule { + var host: std.ArrayList(usize) = .empty; + var done: usize = 1; + try host.append(a, 1); + while (done < frames) : (done += host.items[host.items.len - 1]) try host.append(a, @min(4, frames - done)); + var irregular: std.ArrayList(usize) = .empty; + var state: u32 = 20261015; + done = 0; + while (done < frames) : (done += irregular.items[irregular.items.len - 1]) { + state = state *% 1664525 +% 1013904223; + try irregular.append(a, @min(1 + (state >> 8) % 300, frames - done)); + } + const every = try a.alloc(usize, frames); + @memset(every, 1); + return .{ + .{ .name = "host-1-then-4", .chunks = host.items }, + .{ .name = "every-frame", .chunks = every }, + .{ .name = "gate-lengths", .chunks = &.{ 1, 1, 5, 121, frames - 128 } }, + .{ .name = "one-call", .chunks = &.{frames} }, + .{ .name = "irregular", .chunks = irregular.items }, + }; +} + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len != 4) { + std.debug.print("usage: tf-drama-codec-stream-oracle CHECKPOINT CODES_U32LE OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [frames * 10 * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(io, args[2], .{}); + defer input.close(io); + if (try input.readPositionalAll(io, &bytes, 0) != frames * 10 * 4) return error.Expected1024Frames; + const code_bytes = bytes[0 .. frames * 10 * 4]; + const codes = std.mem.bytesAsSlice([10]u32, @as([]align(@alignOf(u32)) u8, code_bytes)); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(code_bytes, &digest, .{}); + var dir = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer dir.close(io); + + const pcm = try init.gpa.alloc(f32, frames * samples_per_frame); + defer init.gpa.free(pcm); + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var codec = try drama.codec.Model.init(init.gpa, io, &ctx, args[1], "", .{ .max_frames = frames }); + defer codec.deinit(); + + var name: [64]u8 = undefined; + for (lengths) |n| { + if (try codec.decode(stream, codes[0..n], pcm) != n * samples_per_frame) return error.UnexpectedSampleCount; + const file = try std.fmt.bufPrint(&name, "whole-{d}.f32", .{n}); + try dir.writeFile(io, .{ .sub_path = file, .data = std.mem.sliceAsBytes(pcm[0 .. n * samples_per_frame]), .flags = .{ .exclusive = true } }); + } + const plan = try schedules(a); + for (plan) |s| { + @memset(pcm, std.math.nan(f32)); + codec.begin(); + var end: usize = 0; + const began = std.Io.Clock.awake.now(io).toNanoseconds(); + for (s.chunks) |n| { + for (codec.acts) |b| try b.fill8(0xff, stream.handle); // FP16 0xffff is NaN + try codec.audio_dev.fill8(0xff, stream.handle); + end += n; + if (try codec.advance(stream, codes[0..end], pcm) != end * samples_per_frame) return error.UnexpectedSampleCount; + } + if (end != frames) return error.IncompleteSchedule; + const elapsed = std.Io.Clock.awake.now(io).toNanoseconds() - began; + const file = try std.fmt.bufPrint(&name, "chunked-{s}.f32", .{s.name}); + try dir.writeFile(io, .{ .sub_path = file, .data = std.mem.sliceAsBytes(pcm), .flags = .{ .exclusive = true } }); + std.debug.print("schedule={s} chunks={d} elapsed_s_including_poison={d:.6}\n", .{ s.name, s.chunks.len, @as(f64, @floatFromInt(elapsed)) / 1e9 }); + } + + var manifest: std.ArrayList(u8) = .empty; + try manifest.print(a, "{{\"codes_sha256\": \"{s}\", \"frames\": {d}, \"lengths\": [1, 2, 7, 128, 1024], \"schedules\": [", .{ std.fmt.bytesToHex(digest, .lower), frames }); + for (plan, 0..) |s, i| { + try manifest.print(a, "{s}\n {{\"name\": \"{s}\", \"chunks\": [", .{ if (i == 0) "" else ",", s.name }); + for (s.chunks, 0..) |n, j| try manifest.print(a, "{s}{d}", .{ if (j == 0) "" else ", ", n }); + try manifest.appendSlice(a, "]}"); + } + try manifest.appendSlice(a, "\n]}\n"); + try dir.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + return 0; +} diff --git a/zig/tests/cuda/drama_codec_trace.zig b/zig/tests/cuda/drama_codec_trace.zig new file mode 100644 index 00000000000..b197fc61467 --- /dev/null +++ b/zig/tests/cuda/drama_codec_trace.zig @@ -0,0 +1,466 @@ +//! Diagnostic: replays a production codec decode op by op with stage captures; the replay must equal production. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const Model = drama.codec.Model; +const Weights = @FieldType(Model, "w"); + +// codec.zig's private geometry (modded_dac_vq.yaml), restated; the asserts below tie it to the model's types. +const latent = 1024; +const codebook_dim = 8; +const semantic_size = 4096; +const residual_size = 1024; +const residual_books = 9; +const codebooks = 1 + residual_books; +const heads = 16; +const head_dim = 64; +const ffn = 3072; +const window = 128; +const rms_eps: f32 = 1e-5; +const layer_norm_eps: f32 = 1e-6; +const convnext_hidden = 4 * latent; +const decoder_dim = 1536; +const rates = [_]usize{ 8, 8, 4, 2 }; +const dilations = [_]usize{ 1, 3, 9 }; +const samples_per_frame = 2048; +const out_channels = decoder_dim >> rates.len; +const max_frames = 1024; + +comptime { + std.debug.assert(@typeInfo(@FieldType(Weights, "layers")).array.len == 8); + std.debug.assert(@typeInfo(@FieldType(Weights, "upsample")).array.len == 2); + std.debug.assert(@typeInfo(@FieldType(Weights, "blocks")).array.len == rates.len); + std.debug.assert(@typeInfo(@FieldType(@typeInfo(@FieldType(Weights, "blocks")).array.child, "units")).array.len == dilations.len); + std.debug.assert(out_channels == 96); +} + +const Dtype = enum { + f16, + f32, + + fn size(d: Dtype) usize { + return switch (d) { + .f16 => 2, + .f32 => 4, + }; + } + + fn numpy(d: Dtype) []const u8 { + return switch (d) { + .f16 => "float16", + .f32 => "float32", + }; + } +}; + +const Dumped = struct { sha: [64]u8, equal: bool }; + +const Tracer = struct { + gpa: Allocator, + io: std.Io, + dir: std.Io.Dir, + model: *Model, + stream: cuda.Stream, + frames: usize, + /// production.f32's bytes: the replayed PCM must equal them. + production: []const u8, + captures: std.ArrayList(u8) = .empty, + count: usize = 0, + written: usize = 0, + replay_equal: bool = false, + + fn wp(t: *const Tracer, offset: u64) u64 { + return t.model.weights.ptr + offset; + } + + /// The model-owned device buffer holding `n` bytes at `ptr`. + fn source(t: *const Tracer, ptr: u64, n: usize) !struct { buf: cuda.DeviceBuffer, offset: usize } { + const m = t.model; + const owned = [_]cuda.DeviceBuffer{ m.acts[0], m.acts[1], m.acts[2], m.audio_dev, m.weights }; + for (owned) |b| { + if (ptr >= b.ptr and ptr - b.ptr <= b.len and n <= b.len - (ptr - b.ptr)) return .{ .buf = b, .offset = ptr - b.ptr }; + } + return error.CaptureOutsideModelBuffers; + } + + /// Copies n device bytes into a new file through the pinned staging buffer, hashing them and comparing to expect. + fn dump(t: *Tracer, file_name: []const u8, ptr: u64, n: usize, expect: ?[]const u8) !Dumped { + const src = try t.source(ptr, n); + const staging = t.model.audio_host.bytes; + const file = try t.dir.createFile(t.io, file_name, .{ .exclusive = true }); + defer file.close(t.io); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var equal = if (expect) |e| e.len == n else false; + var done: usize = 0; + while (done < n) { + const len = @min(staging.len, n - done); + const chunk = staging[0..len]; + try src.buf.downloadAsync(src.offset + done, chunk, t.stream.handle); + try t.stream.synchronize(); + hash.update(chunk); + if (expect) |e| { + if (equal and !std.mem.eql(u8, chunk, e[done..][0..len])) equal = false; + } + try file.writePositionalAll(t.io, chunk, done); + done += len; + } + t.written += n; + return .{ .sha = std.fmt.bytesToHex(hash.finalResult(), .lower), .equal = equal }; + } + + /// One stage output [rows][cols], synchronized and written before the next launch can reuse its buffer. + fn capture(t: *Tracer, name: []const u8, ptr: u64, dtype: Dtype, rows: usize, cols: usize, op: []const u8) !void { + _ = try t.captureCompare(name, ptr, dtype, rows, cols, op, null); + } + + fn captureCompare(t: *Tracer, name: []const u8, ptr: u64, dtype: Dtype, rows: usize, cols: usize, op: []const u8, expect: ?[]const u8) !bool { + if (rows % t.frames != 0) return error.Invalid; + var file_buffer: [96]u8 = undefined; + const file_name = try std.fmt.bufPrint(&file_buffer, "{s}.{s}", .{ name, @tagName(dtype) }); + const n = rows * cols * dtype.size(); + const d = try t.dump(file_name, ptr, n, expect); + try t.captures.print(t.gpa, "{s}\n {{\"index\": {d}, \"name\": \"{s}\", \"file\": \"{s}\", \"dtype\": \"{s}\", \"byte_order\": \"little\", \"shape\": [{d}, {d}], \"rows_per_frame\": {d}, \"layout\": \"row-major [rows][cols]; rows time-major, cols channels\", \"bytes\": {d}, \"sha256\": \"{s}\", \"op\": \"{s}\"}}", .{ + if (t.count == 0) "" else ",", t.count, name, file_name, dtype.numpy(), rows, cols, rows / t.frames, n, d.sha[0..], op, + }); + t.count += 1; + return d.equal; + } + + /// codec.zig Model.forward, op for op, with captures between launches. + fn replay(t: *Tracer) !void { + const m = t.model; + const k = &m.kernels; + const w = &m.w; + const s = t.stream; + const frames = t.frames; + const h = 2; // bytes an FP16 element + const p = [3]u64{ m.acts[0].ptr, m.acts[1].ptr, m.acts[2].ptr }; + var nb: [64]u8 = undefined; + + try k.rvqLatent(s, m.codes_dev.ptr, t.wp(w.semantic_book), t.wp(w.residual_books), t.wp(w.out_w), t.wp(w.out_b), p[0], frames); + try t.capture("rvq_latent", p[0], .f16, frames, latent, "semantic + nine residual codebook rows through folded out_proj, summed"); + + // post_module + const x = p[0]; + const xn = p[1]; + const qkv = p[1] + frames * latent * h; + const att = p[1] + 4 * frames * latent * h; + const gu = p[2]; + const act = p[2] + frames * 2 * ffn * h; + const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); + for (&w.layers, 0..) |*l, i| { + try k.rmsNorm(s, x, t.wp(l.attention_norm), xn, frames, latent, rms_eps); + try t.capture(try std.fmt.bufPrint(&nb, "layer{d}.attention_norm", .{i}), xn, .f16, frames, latent, "attention_norm(x)"); + try k.gemm(s, .{ .x = xn, .w = t.wp(l.wqkv), .y = qkv, .m = frames, .n = 3 * latent, .cin = latent, .ldx = latent, .ldy = 3 * latent }); + try k.ropeQk(s, qkv, t.wp(w.rope), frames, latent); + try k.windowAttention(s, qkv, att, 0, frames, heads, window, scale); + try t.capture(try std.fmt.bufPrint(&nb, "layer{d}.attention_core", .{i}), att, .f16, frames, latent, "windowed attention output, wo input"); + try k.gemm(s, .{ .x = att, .w = t.wp(l.wo), .y = x, .m = frames, .n = latent, .cin = latent, .ldx = latent, .ldy = latent, .scale = t.wp(l.attention_scale), .residual = x, .ldr = latent }); + try t.capture(try std.fmt.bufPrint(&nb, "layer{d}.attention_residual", .{i}), x, .f16, frames, latent, "h = x + attention_layer_scale(wo(core)), ffn_norm input"); + try k.rmsNorm(s, x, t.wp(l.ffn_norm), xn, frames, latent, rms_eps); + try k.gemm(s, .{ .x = xn, .w = t.wp(l.w13), .y = gu, .m = frames, .n = 2 * ffn, .cin = latent, .ldx = latent, .ldy = 2 * ffn }); + try k.siluMul(s, gu, act, frames, ffn); + try t.capture(try std.fmt.bufPrint(&nb, "layer{d}.ffn_act", .{i}), act, .f16, frames, ffn, "silu(w1(n)) * w3(n), w2 input"); + try k.gemm(s, .{ .x = act, .w = t.wp(l.w2), .y = x, .m = frames, .n = latent, .cin = ffn, .ldx = ffn, .ldy = latent, .scale = t.wp(l.ffn_scale), .residual = x, .ldr = latent }); + try t.capture(try std.fmt.bufPrint(&nb, "layer{d}.out", .{i}), x, .f16, frames, latent, "transformer block output"); + } + try k.rmsNorm(s, x, t.wp(w.norm), p[1], frames, latent, rms_eps); + try t.capture("post_norm", p[1], .f16, frames, latent, "post_module final RMSNorm"); + + // upsample + var input = p[1]; + var spent = p[0]; + var rows = frames; + for (&w.upsample, 0..) |*u, i| { + const y = spent; + try k.gemm(s, .{ .x = input, .w = t.wp(u.conv), .y = y, .m = rows, .n = 2 * latent, .cin = latent, .ldx = latent, .ldy = 2 * latent, .bias = t.wp(u.conv_b), .bias_mode = .separate, .period = latent }); + rows *= 2; + try t.capture(try std.fmt.bufPrint(&nb, "upsample{d}.transconv", .{i}), y, .f16, rows, latent, "ConvTranspose1d k2 s2 + bias"); + const dw = p[2]; + const normed = p[2] + rows * latent * h; + try k.dwconv(s, y, t.wp(u.dw), t.wp(u.dw_b), dw, 0, rows, latent); + try t.capture(try std.fmt.bufPrint(&nb, "upsample{d}.dwconv", .{i}), dw, .f16, rows, latent, "ConvNeXt causal depthwise conv7 + bias"); + try k.layerNorm(s, dw, t.wp(u.norm_w), t.wp(u.norm_b), normed, rows, latent, layer_norm_eps); + try t.capture(try std.fmt.bufPrint(&nb, "upsample{d}.layer_norm", .{i}), normed, .f16, rows, latent, "ConvNeXt LayerNorm"); + const hidden = input; + try k.gemm(s, .{ .x = normed, .w = t.wp(u.pw1), .y = hidden, .m = rows, .n = convnext_hidden, .cin = latent, .ldx = latent, .ldy = convnext_hidden, .bias = t.wp(u.pw1_b), .bias_mode = .fused, .act = .gelu }); + try t.capture(try std.fmt.bufPrint(&nb, "upsample{d}.gelu", .{i}), hidden, .f16, rows, convnext_hidden, "GELU(pwconv1(n))"); + try k.gemm(s, .{ .x = hidden, .w = t.wp(u.pw2), .y = y, .m = rows, .n = latent, .cin = convnext_hidden, .ldx = convnext_hidden, .ldy = latent, .bias = t.wp(u.pw2_b), .bias_mode = .fused, .scale = t.wp(u.gamma), .residual = y, .ldr = latent }); + try t.capture(try std.fmt.bufPrint(&nb, "upsample{d}.out", .{i}), y, .f16, rows, latent, "upsample stage output: transconv + gamma * pwconv2(...)"); + input = y; + spent = hidden; + } + + // decoder + var cur = spent; + try k.gemm(s, .{ .x = input, .w = t.wp(w.conv0), .y = cur, .m = rows, .n = decoder_dim, .cin = latent, .ldx = latent, .ldy = decoder_dim, .taps = 7, .bias = t.wp(w.conv0_b), .bias_mode = .separate }); + try t.capture("decoder.conv0", cur, .f16, rows, decoder_dim, "decoder.model.0 causal conv7 1024 -> 1536"); + var spare = [2]u64{ input, p[2] }; + var ch: usize = decoder_dim; + for (&w.blocks, rates, 0..) |*b, rate, bi| { + const out_ch = ch / 2; + try k.snake(s, cur, t.wp(b.snake.alpha), t.wp(b.snake.inv), spare[0], rows, ch); + try k.gemm(s, .{ .x = spare[0], .w = t.wp(b.conv), .y = spare[1], .m = rows, .n = rate * out_ch, .cin = ch, .ldx = ch, .ldy = rate * out_ch, .taps = 2, .bias = t.wp(b.conv_b), .bias_mode = .separate, .period = out_ch }); + rows *= rate; + ch = out_ch; + var xb = spare[1]; + var sb = cur; + var tb = spare[0]; + for (&b.units, dilations) |*u, dilation| { + try k.snake(s, xb, t.wp(u.snake1.alpha), t.wp(u.snake1.inv), sb, rows, ch); + try k.gemm(s, .{ .x = sb, .w = t.wp(u.conv7), .y = tb, .m = rows, .n = ch, .cin = ch, .ldx = ch, .ldy = ch, .taps = 7, .dilation = dilation, .bias = t.wp(u.conv7_b), .bias_mode = .separate }); + try k.snake(s, tb, t.wp(u.snake2.alpha), t.wp(u.snake2.inv), tb, rows, ch); + try k.gemm(s, .{ .x = tb, .w = t.wp(u.conv1), .y = sb, .m = rows, .n = ch, .cin = ch, .ldx = ch, .ldy = ch, .bias = t.wp(u.conv1_b), .bias_mode = .separate, .residual = xb, .ldr = ch }); + const unit_out = sb; + sb = tb; + tb = xb; + xb = unit_out; + } + cur = xb; + spare = .{ sb, tb }; + try t.capture(try std.fmt.bufPrint(&nb, "decoder.block{d}.out", .{bi}), cur, .f16, rows, ch, "DecoderBlock: snake, causal transposed conv, residual units d1 d3 d9"); + } + try k.snake(s, cur, t.wp(w.out_snake.alpha), t.wp(w.out_snake.inv), cur, rows, ch); + try t.capture("decoder.out_snake", cur, .f16, rows, ch, "decoder.model.5 Snake1d"); + try k.convOutTanh(s, cur, t.wp(w.out_conv), t.wp(w.out_conv_b), m.audio_dev.ptr, 0, rows, ch); + if (rows != t.frames * samples_per_frame) return error.UnexpectedSampleCount; + t.replay_equal = try t.captureCompare("pcm", m.audio_dev.ptr, .f32, rows, 1, "decoder.model.6 causal conv7 96 -> 1, tanh (model.7)", t.production); + } +}; + +/// The weight image's tensors: offset, dtype, native shape and the transform from the reference tensor(s). +const Entries = struct { + gpa: Allocator, + names: Allocator, + image_len: usize, + list: std.ArrayList(u8) = .empty, + count: usize = 0, + + const identity = "{\"kind\": \"identity\"}"; + const stack = "{\"kind\": \"stack\"}"; + const concat_rows = "{\"kind\": \"concat_rows\"}"; + const snake_alpha = "{\"kind\": \"snake_alpha\"}"; + const snake_inverse = "{\"kind\": \"snake_inverse_alpha\"}"; + + fn fmt(e: *Entries, comptime f: []const u8, args: anytype) ![]const u8 { + return std.fmt.allocPrint(e.names, f, args); + } + + fn convTaps(e: *Entries, cout: usize, cin: usize, kernel: usize) ![]const u8 { + return e.fmt("{{\"kind\": \"conv_taps\", \"cout\": {d}, \"cin\": {d}, \"kernel\": {d}}}", .{ cout, cin, kernel }); + } + + fn transposedTaps(e: *Entries, cin: usize, cout: usize, stride: usize, kernel: usize) ![]const u8 { + return e.fmt("{{\"kind\": \"transposed_taps\", \"cin\": {d}, \"cout\": {d}, \"stride\": {d}, \"kernel\": {d}}}", .{ cin, cout, stride, kernel }); + } + + fn add(e: *Entries, name: []const u8, offset: u64, dtype: Dtype, shape: []const usize, layout: []const u8, sources: []const []const u8) !void { + var n: usize = dtype.size(); + for (shape) |d| n *= d; + if (offset % 256 != 0 or offset > e.image_len or n > e.image_len - offset) return error.WeightOutsideImage; + try e.list.print(e.gpa, "{s}\n {{\"name\": \"{s}\", \"offset\": {d}, \"bytes\": {d}, \"dtype\": \"{s}\", \"shape\": [", .{ + if (e.count == 0) "" else ",", name, offset, n, dtype.numpy(), + }); + for (shape, 0..) |d, i| try e.list.print(e.gpa, "{s}{d}", .{ if (i == 0) "" else ", ", d }); + try e.list.print(e.gpa, "], \"layout\": {s}, \"sources\": [", .{layout}); + for (sources, 0..) |src, i| try e.list.print(e.gpa, "{s}\"{s}\"", .{ if (i == 0) "" else ", ", src }); + try e.list.appendSlice(e.gpa, "]}"); + e.count += 1; + } + + fn one(e: *Entries, name: []const u8, offset: u64, dtype: Dtype, shape: []const usize, layout: []const u8, src: []const u8) !void { + try e.add(name, offset, dtype, shape, layout, &[_][]const u8{src}); + } + + fn snake(e: *Entries, name: []const u8, sn: anytype, module: []const u8, channels: usize) !void { + try e.one(try e.fmt("{s}.alpha", .{name}), sn.alpha, .f32, &.{channels}, snake_alpha, module); + try e.one(try e.fmt("{s}.inverse_alpha", .{name}), sn.inv, .f32, &.{channels}, snake_inverse, module); + } + + fn all(e: *Entries, w: *const Weights) !void { + try e.one("semantic_book", w.semantic_book, .f16, &.{ semantic_size, codebook_dim }, identity, "quantizer.semantic_quantizer.quantizers.0.codebook.weight"); + { + var src: [residual_books][]const u8 = undefined; + for (&src, 0..) |*v, i| v.* = try e.fmt("quantizer.quantizer.quantizers.{d}.codebook.weight", .{i}); + try e.add("residual_books", w.residual_books, .f16, &.{ residual_books, residual_size, codebook_dim }, stack, &src); + } + { + var ws: [codebooks][]const u8 = undefined; + var bs: [codebooks][]const u8 = undefined; + for (&ws, &bs, 0..) |*wv, *bv, i| { + const prefix = if (i == 0) "quantizer.semantic_quantizer.quantizers.0" else try e.fmt("quantizer.quantizer.quantizers.{d}", .{i - 1}); + wv.* = try e.fmt("{s}.out_proj.weight", .{prefix}); + bv.* = try e.fmt("{s}.out_proj.bias", .{prefix}); + } + try e.add("out_proj.weight", w.out_w, .f16, &.{ codebooks, latent, codebook_dim }, stack, &ws); + try e.add("out_proj.bias", w.out_b, .f16, &.{ codebooks, latent }, stack, &bs); + } + for (&w.layers, 0..) |*l, i| { + const p = try e.fmt("quantizer.post_module.layers.{d}", .{i}); + try e.one(try e.fmt("layer{d}.wqkv", .{i}), l.wqkv, .f16, &.{ 3 * latent, latent }, identity, try e.fmt("{s}.attention.wqkv.weight", .{p})); + try e.one(try e.fmt("layer{d}.wo", .{i}), l.wo, .f16, &.{ latent, latent }, identity, try e.fmt("{s}.attention.wo.weight", .{p})); + try e.add(try e.fmt("layer{d}.w13", .{i}), l.w13, .f16, &.{ 2 * ffn, latent }, concat_rows, &[_][]const u8{ + try e.fmt("{s}.feed_forward.w1.weight", .{p}), try e.fmt("{s}.feed_forward.w3.weight", .{p}), + }); + try e.one(try e.fmt("layer{d}.w2", .{i}), l.w2, .f16, &.{ latent, ffn }, identity, try e.fmt("{s}.feed_forward.w2.weight", .{p})); + try e.one(try e.fmt("layer{d}.attention_norm", .{i}), l.attention_norm, .f16, &.{latent}, identity, try e.fmt("{s}.attention_norm.weight", .{p})); + try e.one(try e.fmt("layer{d}.ffn_norm", .{i}), l.ffn_norm, .f16, &.{latent}, identity, try e.fmt("{s}.ffn_norm.weight", .{p})); + try e.one(try e.fmt("layer{d}.attention_scale", .{i}), l.attention_scale, .f16, &.{latent}, identity, try e.fmt("{s}.attention_layer_scale.gamma", .{p})); + try e.one(try e.fmt("layer{d}.ffn_scale", .{i}), l.ffn_scale, .f16, &.{latent}, identity, try e.fmt("{s}.ffn_layer_scale.gamma", .{p})); + } + try e.one("post_norm", w.norm, .f16, &.{latent}, identity, "quantizer.post_module.norm.weight"); + for (&w.upsample, 0..) |*u, i| { + const p = try e.fmt("quantizer.upsample.{d}", .{i}); + try e.one(try e.fmt("upsample{d}.conv", .{i}), u.conv, .f16, &.{ 2 * latent, latent }, try e.transposedTaps(latent, latent, 2, 2), try e.fmt("{s}.0.conv.weight", .{p})); + try e.one(try e.fmt("upsample{d}.conv_bias", .{i}), u.conv_b, .f16, &.{latent}, identity, try e.fmt("{s}.0.conv.bias", .{p})); + try e.one(try e.fmt("upsample{d}.dwconv", .{i}), u.dw, .f16, &.{ latent, 1, 7 }, identity, try e.fmt("{s}.1.dwconv.conv.weight", .{p})); + try e.one(try e.fmt("upsample{d}.dwconv_bias", .{i}), u.dw_b, .f16, &.{latent}, identity, try e.fmt("{s}.1.dwconv.conv.bias", .{p})); + try e.one(try e.fmt("upsample{d}.norm_weight", .{i}), u.norm_w, .f16, &.{latent}, identity, try e.fmt("{s}.1.norm.weight", .{p})); + try e.one(try e.fmt("upsample{d}.norm_bias", .{i}), u.norm_b, .f16, &.{latent}, identity, try e.fmt("{s}.1.norm.bias", .{p})); + try e.one(try e.fmt("upsample{d}.pwconv1", .{i}), u.pw1, .f16, &.{ convnext_hidden, latent }, identity, try e.fmt("{s}.1.pwconv1.weight", .{p})); + try e.one(try e.fmt("upsample{d}.pwconv1_bias", .{i}), u.pw1_b, .f16, &.{convnext_hidden}, identity, try e.fmt("{s}.1.pwconv1.bias", .{p})); + try e.one(try e.fmt("upsample{d}.pwconv2", .{i}), u.pw2, .f16, &.{ latent, convnext_hidden }, identity, try e.fmt("{s}.1.pwconv2.weight", .{p})); + try e.one(try e.fmt("upsample{d}.pwconv2_bias", .{i}), u.pw2_b, .f16, &.{latent}, identity, try e.fmt("{s}.1.pwconv2.bias", .{p})); + try e.one(try e.fmt("upsample{d}.gamma", .{i}), u.gamma, .f16, &.{latent}, identity, try e.fmt("{s}.1.gamma", .{p})); + } + try e.one("decoder.conv0", w.conv0, .f16, &.{ decoder_dim, 7, latent }, try e.convTaps(decoder_dim, latent, 7), "decoder.model.0.conv.weight"); + try e.one("decoder.conv0_bias", w.conv0_b, .f16, &.{decoder_dim}, identity, "decoder.model.0.conv.bias"); + var ch: usize = decoder_dim; + for (&w.blocks, rates, 0..) |*b, rate, bi| { + const out_ch = ch / 2; + const p = try e.fmt("decoder.model.{d}.block", .{bi + 1}); + try e.snake(try e.fmt("block{d}.snake", .{bi}), b.snake, try e.fmt("{s}.0", .{p}), ch); + try e.one(try e.fmt("block{d}.transconv", .{bi}), b.conv, .f16, &.{ rate * out_ch, 2 * ch }, try e.transposedTaps(ch, out_ch, rate, 2 * rate), try e.fmt("{s}.1.conv.weight", .{p})); + try e.one(try e.fmt("block{d}.transconv_bias", .{bi}), b.conv_b, .f16, &.{out_ch}, identity, try e.fmt("{s}.1.conv.bias", .{p})); + for (&b.units, 0..) |*u, j| { + const q = try e.fmt("{s}.{d}.block", .{ p, j + 2 }); + try e.snake(try e.fmt("block{d}.unit{d}.snake1", .{ bi, j }), u.snake1, try e.fmt("{s}.0", .{q}), out_ch); + try e.one(try e.fmt("block{d}.unit{d}.conv7", .{ bi, j }), u.conv7, .f16, &.{ out_ch, 7, out_ch }, try e.convTaps(out_ch, out_ch, 7), try e.fmt("{s}.1.conv.weight", .{q})); + try e.one(try e.fmt("block{d}.unit{d}.conv7_bias", .{ bi, j }), u.conv7_b, .f16, &.{out_ch}, identity, try e.fmt("{s}.1.conv.bias", .{q})); + try e.snake(try e.fmt("block{d}.unit{d}.snake2", .{ bi, j }), u.snake2, try e.fmt("{s}.2", .{q}), out_ch); + try e.one(try e.fmt("block{d}.unit{d}.conv1", .{ bi, j }), u.conv1, .f16, &.{ out_ch, 1, out_ch }, try e.convTaps(out_ch, out_ch, 1), try e.fmt("{s}.3.conv.weight", .{q})); + try e.one(try e.fmt("block{d}.unit{d}.conv1_bias", .{ bi, j }), u.conv1_b, .f16, &.{out_ch}, identity, try e.fmt("{s}.3.conv.bias", .{q})); + } + ch = out_ch; + } + try e.snake("out_snake", w.out_snake, "decoder.model.5", out_channels); + try e.one("out_conv", w.out_conv, .f16, &.{ 7, out_channels }, try e.convTaps(1, out_channels, 7), "decoder.model.6.conv.weight"); + try e.one("out_conv_bias", w.out_conv_b, .f16, &.{1}, identity, "decoder.model.6.conv.bias"); + try e.one("rope", w.rope, .f16, &.{ max_frames, head_dim / 2, 2 }, try e.fmt("{{\"kind\": \"rope_table\", \"positions\": {d}}}", .{max_frames}), "quantizer.post_module.freqs_cis"); + } +}; + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + const usage = "usage: tf-drama-codec-trace CHECKPOINT CODES_U32LE OUTPUT_DIRECTORY FRAMES [--no-weights]\n"; + if ((args.len != 5 and args.len != 6) or (args.len == 6 and !std.mem.eql(u8, args[5], "--no-weights"))) { + std.debug.print(usage, .{}); + return 2; + } + const with_weights = args.len == 5; + const frames = std.fmt.parseInt(usize, args[4], 10) catch 0; + if (frames < 1 or frames > max_frames) { + std.debug.print("FRAMES must be 1..{d}\n" ++ usage, .{max_frames}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + + var bytes: [max_frames * codebooks * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(io, args[2], .{}); + defer input.close(io); + const count = try input.readPositionalAll(io, &bytes, 0); + if (count != max_frames * codebooks * 4) return error.Expected1024Frames; + const codes_sha = sha256Hex(bytes[0..count]); + const codes = std.mem.bytesAsSlice([codebooks]u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + const dir = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer dir.close(io); + + const samples = frames * samples_per_frame; + const production = try gpa.alloc(f32, samples); + defer gpa.free(production); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var codec = try Model.init(gpa, io, &ctx, args[1], "", .{ .max_frames = max_frames }); + defer codec.deinit(); + if (codec.frame_length != samples_per_frame or codec.num_codebooks != codebooks or codec.max_frames != max_frames) return error.UnexpectedCodecGeometry; + + // 1. production decode, untouched + if (try codec.decode(stream, codes[0..frames], production) != samples) return error.UnexpectedSampleCount; + for (production) |v| if (!std.math.isFinite(v)) return error.NonFiniteAudio; + const production_bytes = std.mem.sliceAsBytes(production); + const production_sha = sha256Hex(production_bytes); + try dir.writeFile(io, .{ .sub_path = "production.f32", .data = production_bytes, .flags = .{ .exclusive = true } }); + + // 2. replay with captures: the same code upload decode performs, then the forward + try ctx.makeCurrent(); + const code_bytes = std.mem.sliceAsBytes(codes[0..frames]); + @memcpy(codec.codes_host.bytes[0..code_bytes.len], code_bytes); + try codec.codes_dev.uploadAsync(0, codec.codes_host.bytes[0..code_bytes.len], stream.handle); + var tracer: Tracer = .{ .gpa = gpa, .io = io, .dir = dir, .model = &codec, .stream = stream, .frames = frames, .production = production_bytes }; + defer tracer.captures.deinit(gpa); + try tracer.replay(); + + // 3. the packed weight image and its tensor map + var weights_json: std.ArrayList(u8) = .empty; + defer weights_json.deinit(gpa); + if (with_weights) { + const d = try tracer.dump("weights.bin", codec.weights.ptr, codec.weights.len, null); + var entries: Entries = .{ .gpa = gpa, .names = arena, .image_len = codec.weights.len }; + defer entries.list.deinit(gpa); + try entries.all(&codec.w); + try weights_json.print(gpa, "{{\"file\": \"weights.bin\", \"bytes\": {d}, \"sha256\": \"{s}\", \"alignment\": 256, \"tensors\": [{s}\n ]}}", .{ codec.weights.len, d.sha[0..], entries.list.items }); + } else { + try weights_json.appendSlice(gpa, "null"); + } + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"format\": \"drama-codec-trace/1\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"codes_file\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"codes_sha256\": \"{s}\",\n \"frames\": {d},\n \"max_frames\": {d},\n \"samples\": {d},\n \"samples_per_frame\": {d}," ++ + "\n \"production_pcm\": {{\"file\": \"production.f32\", \"dtype\": \"float32\", \"shape\": [{d}], \"sha256\": \"{s}\"}}," ++ + "\n \"replay_pcm_equal\": {s},\n \"captures\": [{s}\n ],\n \"weights\": {s}\n}}\n", .{ + codes_sha[0..], frames, max_frames, samples, samples_per_frame, samples, production_sha[0..], + if (tracer.replay_equal) "true" else "false", tracer.captures.items, weights_json.items, + }); + try dir.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + + const used = cuda.usage(false); + std.debug.print("frames={d} captures={d} bytes_written={d} replay_pcm_equal={s} cuda_bytes={d} pinned_bytes={d}\n", .{ + frames, tracer.count, tracer.written + production_bytes.len + manifest.items.len, if (tracer.replay_equal) "true" else "false", used.device, used.host, + }); + return if (tracer.replay_equal) 0 else 3; +} diff --git a/zig/tests/cuda/drama_codec_weight_replay.zig b/zig/tests/cuda/drama_codec_weight_replay.zig new file mode 100644 index 00000000000..24aa493e163 --- /dev/null +++ b/zig/tests/cuda/drama_codec_weight_replay.zig @@ -0,0 +1,121 @@ +//! Diagnostic: replaces only the packed weights of a production codec instance. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +fn hash(bytes: []const u8) [64]u8 { + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + return std.fmt.bytesToHex(digest, .lower); +} + +fn weightHash(model: *drama.codec.Model, stream: cuda.Stream) ![64]u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: usize = 0; + while (offset < model.weights.len) { + const n = @min(model.audio_host.bytes.len, model.weights.len - offset); + const staging = model.audio_host.bytes[0..n]; + try model.weights.downloadAsync(offset, staging, stream.handle); + try stream.synchronize(); + h.update(staging); + offset += n; + } + return std.fmt.bytesToHex(h.finalResult(), .lower); +} + +fn replaceWeights(model: *drama.codec.Model, stream: cuda.Stream, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + var h = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: usize = 0; + while (offset < model.weights.len) { + const n = @min(model.audio_host.bytes.len, model.weights.len - offset); + const staging = model.audio_host.bytes[0..n]; + if (try file.readPositionalAll(io, staging, offset) != n) return error.ShortWeightImage; + h.update(staging); + try model.weights.uploadAsync(offset, staging, stream.handle); + try stream.synchronize(); // Reusing the pinned staging buffer requires upload completion. + offset += n; + } + var extra: [1]u8 = undefined; + if (try file.readPositionalAll(io, &extra, offset) != 0) return error.LongWeightImage; + const expected = std.fmt.bytesToHex(h.finalResult(), .lower); + if (!std.mem.eql(u8, &expected, &try weightHash(model, stream))) return error.WeightUploadMismatch; + return expected; +} + +fn save(dir: std.Io.Dir, io: std.Io, name: []const u8, bytes: []const u8) !void { + const file = try dir.createFile(io, name, .{ .exclusive = true }); + defer file.close(io); + try file.writePositionalAll(io, bytes, 0); +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 6) { + std.debug.print("usage: tf-drama-codec-weight-replay CHECKPOINT CODES_U32LE BASE_WEIGHTS CANDIDATE_WEIGHTS OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [1024 * 10 * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const input = try std.Io.Dir.cwd().openFile(init.io, args[2], .{}); + defer input.close(init.io); + const count = try input.readPositionalAll(init.io, &bytes, 0); + if (count != 1024 * 10 * 4) return error.Expected1024Frames; + const codes = std.mem.bytesAsSlice([10]u32, @as([]align(@alignOf(u32)) u8, bytes[0..count])); + const codes_hash = hash(bytes[0..count]); + var dir = try std.Io.Dir.cwd().openDir(init.io, args[5], .{}); + defer dir.close(init.io); + const pcm = try init.gpa.alloc(f32, 1024 * 2048 + 16); + defer init.gpa.free(pcm); + _ = try cuda.setAllocationLimit(4 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var codec = try drama.codec.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .max_frames = 1024 }); + defer codec.deinit(); + const weights_before = try weightHash(&codec, stream); + var current_weights = weights_before; + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(init.gpa); + try manifest.print(init.gpa, "{{\"schema\":1,\"codes_sha256\":\"{s}\",\"weights_before_sha256\":\"{s}\",\"allocation_cap_bytes\":{d},\"runs\":[\n", .{ codes_hash, weights_before, @as(u64, 4) << 30 }); + var first = true; + for ([_][]const u8{ "baseline", "baseline_repeat", "candidate", "candidate_repeat", "restored" }, 0..) |label, phase| { + if (phase == 2) current_weights = try replaceWeights(&codec, stream, init.io, args[4]); + if (phase == 4) { + current_weights = try replaceWeights(&codec, stream, init.io, args[3]); + if (!std.mem.eql(u8, &weights_before, ¤t_weights)) return error.RestorationMismatch; + } + for ([_]usize{ 1, 2, 7, 128, 1024 }) |frames| { + const samples = frames * 2048; + const sentinel: f32 = @bitCast(@as(u32, 0x7fc0dead)); + @memset(pcm[0 .. samples + 16], sentinel); + const begin = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const written = try codec.decode(stream, codes[0..frames], pcm); + const elapsed = std.Io.Clock.awake.now(init.io).toNanoseconds() - begin; + if (written != samples) return error.UnexpectedSampleCount; + for (pcm[0..samples]) |v| if (!std.math.isFinite(v)) return error.NonFiniteAudio; + for (pcm[samples .. samples + 16]) |v| if (@as(u32, @bitCast(v)) != 0x7fc0dead) return error.OutputOverrun; + const code_bytes = std.mem.sliceAsBytes(codes[0..frames]); + try codec.codes_dev.downloadAsync(0, codec.codes_host.bytes[0..code_bytes.len], stream.handle); + try stream.synchronize(); + if (!std.mem.eql(u8, code_bytes, codec.codes_host.bytes[0..code_bytes.len])) return error.CodesChanged; + var name_buf: [80]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "{s}-{d}.f32", .{ label, frames }); + const audio = std.mem.sliceAsBytes(pcm[0..samples]); + try save(dir, init.io, name, audio); + const used = cuda.usage(false); + try manifest.print(init.gpa, "{s}{{\"phase\":\"{s}\",\"frames\":{d},\"samples\":{d},\"pcm_sha256\":\"{s}\",\"weights_sha256\":\"{s}\",\"elapsed_s\":{d:.9},\"cuda_bytes\":{d},\"pinned_bytes\":{d},\"finite\":true,\"sentinel_untouched\":true,\"codes_unchanged\":true}}\n", .{ if (first) "" else ",", label, frames, written, hash(audio), current_weights, @as(f64, @floatFromInt(elapsed)) / 1e9, used.device, used.host }); + first = false; + } + if (!std.mem.eql(u8, ¤t_weights, &try weightHash(&codec, stream))) return error.WeightsChanged; + } + if (!std.mem.eql(u8, &codes_hash, &hash(bytes[0..count]))) return error.HostCodesChanged; + try manifest.print(init.gpa, "],\"weights_after_sha256\":\"{s}\",\"weights_restored\":true,\"host_codes_unchanged\":true}}\n", .{current_weights}); + try save(dir, init.io, "manifest.json", manifest.items); + return 0; +} diff --git a/zig/tests/cuda/drama_conv_tests.zig b/zig/tests/cuda/drama_conv_tests.zig new file mode 100644 index 00000000000..c9bfd73e37a --- /dev/null +++ b/zig/tests/cuda/drama_conv_tests.zig @@ -0,0 +1,109 @@ +//! Causal convolution's phase-specific precision, raw history, stride and chunk boundaries; no checkpoint required. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); + +const channels = 257; // Exercise a partial second CUDA block. +const stride = channels + 3; +const rows = 7; +const guard = 32; +const sentinel: u16 = 0x7fc1; +const input = [rows][3]u16{ + .{ 0xc06e, 0xbfee, 0x0000 }, .{ 0xbfa5, 0x3f12, 0x401b }, + .{ 0x3f92, 0x4040, 0xc02e }, .{ 0x4065, 0xc009, 0xbe92 }, + .{ 0xbfc9, 0x3e92, 0x4009 }, .{ 0x3f5b, 0x402e, 0xc040 }, + .{ 0x4052, 0xc01b, 0xbf12 }, +}; +const weights = [3][4]u16{ + .{ 0xbf9c, 0x0000, 0x3f9c, 0xbde4 }, + .{ 0xbf2b, 0x3f0e, 0xbf47, 0x3ee4 }, + .{ 0xbde4, 0x3f8e, 0xbe64, 0x3f80 }, +}; +const initial = [3][3]u16{ + .{ 0xbfa3, 0xbf23, 0x0000 }, .{ 0x3ee9, 0x3f8c, 0xbf69 }, .{ 0xbee9, 0x3e3a, 0x3f51 }, +}; +// Evaluated from the stored BF16 operands; row zero tells one-row prefill from decode. +const prefill = [rows][3]u16{ + .{ 0x3f92, 0x3d02, 0xbe8e }, .{ 0xbd0f, 0x3f4c, 0x4055 }, + .{ 0xbe8d, 0xbde8, 0xbde9 }, .{ 0x40b0, 0xbe86, 0x4037 }, + .{ 0x40c3, 0x403c, 0xbe8c }, .{ 0xbde1, 0xbe61, 0xbdd4 }, + .{ 0xbdb7, 0xbe8a, 0x4014 }, +}; +const decode = [rows][3]u16{ + .{ 0x3f91, 0x3d05, 0xbe8e }, .{ 0xbd0f, 0x3f4c, 0x4055 }, + .{ 0xbe8d, 0xbde8, 0xbde9 }, .{ 0x40b0, 0xbe85, 0x4037 }, + .{ 0x40c3, 0x403c, 0xbe8c }, .{ 0xbde1, 0xbe60, 0xbdd4 }, + .{ 0xbdb9, 0xbe8a, 0x4014 }, +}; + +fn runCase(gpu: check.Gpu, stream: cuda.Stream, kernel: cuda.Function, chunk: usize, expected: *const [rows][3]u16) !void { + var x: [rows * stride]u16 = @splat(sentinel); + var w: [channels * 4]u16 = undefined; + var history: [guard + 3 * channels + guard]u16 = @splat(sentinel); + var output: [guard + rows * channels + guard]u16 = @splat(sentinel); + for (0..channels) |c| { + for (0..rows) |r| x[r * stride + c] = input[r][c % 3]; + for (0..4) |k| w[4 * c + k] = weights[c % 3][k]; + for (0..3) |r| history[guard + r * channels + c] = initial[r][c % 3]; + } + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&x)); + defer dx.free(); + var dw = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&w)); + defer dw.free(); + var dh = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&history)); + defer dh.free(); + var dy = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&output)); + defer dy.free(); + try gpu.ctx.synchronize(); + var start: usize = 0; + while (start < rows) { + const count = @min(chunk, rows - start); + var args: cuda.Args = .{}; + args.add(dx.ptr + start * stride * 2); + args.add(@as(i32, stride)); + args.add(dw.ptr); + args.add(dh.ptr + guard * 2); + args.add(dy.ptr + (guard + start * channels) * 2); + args.add(@as(i32, @intCast(count))); + args.add(@as(i32, channels)); + try cuda.launch.launch(kernel, .{ .grid = .{ .x = (channels + 255) / 256 }, .block = .{ .x = 256 } }, stream, &args); + try stream.synchronize(); + try dh.download(0, std.mem.asBytes(&history)); + // History contains raw inputs, including the initial state until three rows have arrived. + const seen = start + count; + for (0..3) |r| for (0..channels) |c| { + const index = seen + r; + const want = if (index < 3) initial[index][c % 3] else input[index - 3][c % 3]; + try check.expect(history[guard + r * channels + c] == want, "conv history at row {d}, channel {d}, chunk {d}", .{ seen, c, chunk }); + }; + start = seen; + } + try dy.download(0, std.mem.asBytes(&output)); + for (0..rows) |r| for (0..channels) |c| { + try check.expect(output[guard + r * channels + c] == expected[r][c % 3], "conv output row {d}, channel {d}, chunk {d}: {x} != {x}", .{ r, c, chunk, output[guard + r * channels + c], expected[r][c % 3] }); + }; + for (0..guard) |i| { + try check.expect(output[i] == sentinel and output[guard + rows * channels + i] == sentinel, "conv output guard {d}", .{i}); + try check.expect(history[i] == sentinel and history[guard + 3 * channels + i] == sentinel, "conv history guard {d}", .{i}); + } + var x_after: @TypeOf(x) = undefined; + var w_after: @TypeOf(w) = undefined; + try dx.download(0, std.mem.asBytes(&x_after)); + try dw.download(0, std.mem.asBytes(&w_after)); + try check.sameBytes("conv input unchanged", std.mem.asBytes(&x_after), std.mem.asBytes(&x)); + try check.sameBytes("conv weights unchanged", std.mem.asBytes(&w_after), std.mem.asBytes(&w)); +} + +pub fn run(gpu: check.Gpu) !void { + var module = try cuda.Module.load(gpu.d, cuda.kernels.drama_backbone); + defer module.unload(); + var stream = try cuda.Stream.init(gpu.d, true); + defer stream.deinit(); + const prefill_fn = try module.function("drama_gdn_conv_prefill"); + const decode_fn = try module.function("drama_gdn_conv"); + for ([_]usize{ 1, 3, 7 }) |chunk| { + try runCase(gpu, stream, prefill_fn, chunk, &prefill); + try runCase(gpu, stream, decode_fn, chunk, &decode); + } + check.pass("Drama convolution: prefill/decode precision, raw history, chunks 1/3/7, stride and partial block", .{}); +} diff --git a/zig/tests/cuda/drama_gdn_canonical_oracle.zig b/zig/tests/cuda/drama_gdn_canonical_oracle.zig new file mode 100644 index 00000000000..08894213ff8 --- /dev/null +++ b/zig/tests/cuda/drama_gdn_canonical_oracle.zig @@ -0,0 +1,416 @@ +//! Verification driver: runs the production GDN controller on raw fixtures and writes outputs for a checker. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const gdn = drama.backbone.gdn; +const Allocator = std.mem.Allocator; +const Sha256 = std.crypto.hash.sha2.Sha256; + +const producer = "tf-drama-gdn-canonical-oracle"; +pub const cases_schema = "drama-gdn-canonical-cases/1"; +const result_schema = "drama-gdn-canonical-native/1"; +const frozen_image_sha256 = "60ec0492bd5926c12bec45b1a555022d080bfe187bb9180d89aec36a0ac43b7f"; +const frozen_decode = "drama_gdn_recur"; +const frozen_prefill = "drama_gdn_recur_prefill"; +pub const dv = 128; +const chunk = gdn.chunk_rows; +const gdn_cases = @import("drama_gdn_oracle_cases.zig"); +const gdn_runner = @import("drama_gdn_oracle_runner.zig"); +const workspaceCapacity = gdn_cases.workspaceCapacity; +const parseCases = gdn_cases.parseCases; +const LayerMem = gdn_runner.LayerMem; +const GeoMem = gdn_runner.GeoMem; +const OpRecord = gdn_runner.OpRecord; +const Runner = gdn_runner.Runner; +pub const layer_count = 2; +const passes = 2; +pub const guard = 4096; // bytes; a multiple of 256 keeps every placed buffer aligned like cuMemAlloc +pub const y_guard_rows = 2; +pub const fill = 0xff; // bf16 0xFFFF and f32 0xFFFFFFFF are NaN: no finite result has these bytes +const device_limit = 1 << 30; +pub const max_file = 1 << 28; +/// Workspace fields read for the gate probe when present as device addresses: FP32 [capacity rows][nv] each. +pub const probe_fields = [_][]const u8{ "g", "gc", "beta" }; +pub const probe_available = blk: { + for (probe_fields) |f| { + if (!@hasField(gdn.Workspace, f)) break :blk false; + if (@FieldType(gdn.Workspace, f) != u64) break :blk false; + } + break :blk true; +}; + +comptime { + std.debug.assert(chunk == 64); +} + +pub const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + pub fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + const message = try std.fmt.allocPrint(e.gpa, f, args); + defer e.gpa.free(message); + if (e.count < 200) std.debug.print("error: {s}\n", .{message}); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n " else ",\n "); + try jsonString(&e.json, e.gpa, message); + e.count += 1; + } +}; + +pub fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +pub fn nowNs(io: std.Io) i128 { + return std.Io.Clock.awake.now(io).toNanoseconds(); +} + +pub fn notFill(bytes: []const u8) usize { + var n: usize = 0; + for (bytes) |b| { + if (b != fill) n += 1; + } + return n; +} + +pub fn nonfiniteBf16(values: []const u16) usize { + var n: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) n += 1; + } + return n; +} + +pub fn unwrittenBf16(values: []const u16) usize { + var n: usize = 0; + for (values) |bits| { + if (bits == 0xffff) n += 1; + } + return n; +} + +pub fn nonfiniteF32(bytes: []align(16) const u8) usize { + var n: usize = 0; + for (std.mem.bytesAsSlice(u32, bytes)) |bits| { + if ((bits & 0x7f800000) == 0x7f800000) n += 1; + } + return n; +} + +pub fn bitsDifferent(comptime T: type, a: []align(16) const u8, b: []align(16) const u8) usize { + var n: usize = 0; + for (std.mem.bytesAsSlice(T, a), std.mem.bytesAsSlice(T, b)) |x, y| { + if (x != y) n += 1; + } + return n; +} + +pub fn int(v: usize) i32 { + return @intCast(v); +} + +pub fn sameBank(a: ?u1, b: ?u1) bool { + if (a) |x| { + if (b) |y| return x == y; + return false; + } + return b == null; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 5) { + std.debug.print("usage: tf-drama-gdn-canonical-oracle GLUE_FATBIN FROZEN_FATBIN CASES_DIR OUTPUT_DIR\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const started = nowNs(io); + + // 1. fixtures and images, CPU only + const cases_dir = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer cases_dir.close(io); + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + const cs = parseCases(arena, io, cases_dir) catch |err| switch (err) { + error.BadCases => return 2, + else => return err, + }; + const glue_image = try std.Io.Dir.cwd().readFileAllocOptions(io, args[1], arena, .limited(max_file), .@"16", null); + const frozen_image = try std.Io.Dir.cwd().readFileAllocOptions(io, args[2], arena, .limited(max_file), .@"16", null); + const glue_sha = sha256Hex(glue_image); + const frozen_sha = sha256Hex(frozen_image); + if (!std.mem.eql(u8, &frozen_sha, frozen_image_sha256)) { + std.debug.print("FROZEN_FATBIN sha256 {s} is not the frozen image {s}\n", .{ frozen_sha[0..], frozen_image_sha256 }); + return 2; + } + if (std.mem.eql(u8, &glue_sha, frozen_image_sha256)) { + std.debug.print("GLUE_FATBIN is the frozen pre-chunk image\n", .{}); + return 2; + } + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, dv))); // backbone.zig's deltaNet scale + + // 2. device memory, once + _ = try cuda.setAllocationLimit(device_limit); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var name_buffer: [128]u8 = undefined; + const device_name = try arena.dupe(u8, try ctx.name(&name_buffer)); + const capability = try ctx.capability(); + const driver_version = try driver.version(); + const usage_start = cuda.usage(true); + + var glue = try cuda.Module.load(&driver, glue_image); + defer glue.unload(); + const kernels = try gdn.Kernels.init(&glue); + var frozen = try cuda.Module.load(&driver, frozen_image); + defer frozen.unload(); + const frozen_decode_fn = try frozen.function(frozen_decode); + const frozen_prefill_fn = try frozen.function(frozen_prefill); + + const stream_bufs = try arena.alloc([2]cuda.DeviceBuffer, cs.streams.len); + var streams_made: usize = 0; + defer for (stream_bufs[0..streams_made]) |*p| { + p[0].free(); + p[1].free(); + }; + var scratch_len: usize = 0; + for (cs.streams, stream_bufs) |s, *p| { + p[0] = try cuda.DeviceBuffer.fromHost(&driver, s.qkv.bytes); + p[1] = cuda.DeviceBuffer.fromHost(&driver, s.ba.bytes) catch |e| { + p[0].free(); + return e; + }; + streams_made += 1; + scratch_len = @max(scratch_len, s.qkv.bytes.len, s.ba.bytes.len); + } + + const mems = try arena.alloc(?GeoMem, cs.geometries.len); + @memset(mems, null); + defer for (mems) |*slot| if (slot.*) |*m| { + m.a_log.free(); + m.dt_bias.free(); + for (&m.layers) |*lm| { + lm.region.free(); + lm.old.free(); + } + m.ws.free(); + m.y.free(); + m.y_old.free(); + m.y_base.free(); + m.base_state.free(); + slot.* = null; + }; + var geometry_json: std.ArrayList(u8) = .empty; + defer geometry_json.deinit(gpa); + for (cs.geometries, mems) |g, *slot| { + if (!g.used) continue; + const sb = g.stateBytes(); + const y_bytes = (g.max_rows + 2 * y_guard_rows) * g.rowBytes(); + var m: GeoMem = undefined; + m.a_log = try cuda.DeviceBuffer.fromHost(&driver, g.a_log.bytes); + m.dt_bias = try cuda.DeviceBuffer.fromHost(&driver, g.dt_bias.bytes); + for (&m.layers) |*lm| { + lm.bank_bytes = sb; + lm.qkv_cache_bytes = g.qkvCacheBytes(); + lm.ba_cache_bytes = g.baCacheBytes(); + lm.region = try cuda.DeviceBuffer.alloc(&driver, LayerMem.total(sb, lm.qkv_cache_bytes, lm.ba_cache_bytes)); + try lm.region.fill8(fill, null); + lm.old = try cuda.DeviceBuffer.alloc(&driver, sb); + const o = lm.offsets(); + lm.state = .{ .banks = .{ lm.region.ptr + o[0], lm.region.ptr + o[1] }, .qkv_cache = lm.region.ptr + o[2], .ba_cache = lm.region.ptr + o[3] }; + } + m.ws = try cuda.DeviceBuffer.alloc(&driver, guard + g.ws_bytes + guard); + m.y = try cuda.DeviceBuffer.alloc(&driver, y_bytes); + m.y_old = try cuda.DeviceBuffer.alloc(&driver, g.max_rows * g.rowBytes()); + m.y_base = try cuda.DeviceBuffer.alloc(&driver, g.max_rows * g.rowBytes()); + m.base_state = try cuda.DeviceBuffer.alloc(&driver, sb); + slot.* = m; + scratch_len = @max(scratch_len, y_bytes, sb, m.ws.len); + try geometry_json.print(gpa, "{s}\n {{\"name\": \"{s}\", \"nk\": {d}, \"nv\": {d}, \"dv\": {d}, \"width\": {d}, \"state_bytes\": {d}, \"qkv_cache_bytes\": {d}, \"ba_cache_bytes\": {d}, \"layer_region_bytes\": {d}, \"layers\": {d}, \"workspace_allocated_bytes\": {d}, \"workspace_largest_layout_bytes\": {d}, \"output_rows_allocated\": {d}, \"guard_bytes\": {d}, \"output_guard_rows\": {d}}}", .{ + if (geometry_json.items.len == 0) "" else ",", g.name, g.nk, g.nv, dv, g.width(), sb, g.qkvCacheBytes(), g.baCacheBytes(), m.layers[0].region.len, layer_count, m.ws.len, g.ws_bytes, g.max_rows, guard, y_guard_rows, + }); + } + try ctx.synchronize(); + const usage_after_setup = cuda.usage(false); + const mem_after_setup = try ctx.memInfo(); + + const scratch = try gpa.alignedAlloc(u8, .@"16", scratch_len); + defer gpa.free(scratch); + const scratch2 = try gpa.alignedAlloc(u8, .@"16", scratch_len); + defer gpa.free(scratch2); + + var runner: Runner = .{ + .gpa = gpa, + .io = io, + .d = &driver, + .stream = stream, + .kernels = &kernels, + .frozen_decode_fn = frozen_decode_fn, + .frozen_prefill_fn = frozen_prefill_fn, + .cs = &cs, + .stream_bufs = stream_bufs, + .out = out, + .errors = &errors, + .scale = scale, + .scratch = scratch, + .scratch2 = scratch2, + }; + + // 3. cases, two passes each + var cases_json: std.ArrayList(u8) = .empty; + defer cases_json.deinit(gpa); + var path_buffer: [256]u8 = undefined; + var max_ops: usize = 0; + for (cs.cases) |c| max_ops = @max(max_ops, c.ops.len); + const records = [passes][]OpRecord{ try gpa.alloc(OpRecord, max_ops), try gpa.alloc(OpRecord, max_ops) }; + defer for (records) |r| gpa.free(r); + var total_ops: usize = 0; + for (cs.cases) |c| { + const m = &mems[c.geometry].?; + const g = cs.geometries[c.geometry]; + try out.createDir(io, c.name, .default_dir); + var ys: [layer_count]std.ArrayList(u8) = @splat(.empty); + var old_ys: [layer_count]std.ArrayList(u8) = @splat(.empty); + var base_ys: [layer_count]std.ArrayList(u8) = @splat(.empty); + defer for (&ys, &old_ys, &base_ys) |*a, *b, *e| { + a.deinit(gpa); + b.deinit(gpa); + e.deinit(gpa); + }; + const case_start = nowNs(io); + for (0..passes) |pass| try runner.runCase(c, m, records[pass][0..c.ops.len], pass, &ys, &old_ys, &base_ys); + const case_ns = nowNs(io) - case_start; + total_ops += c.ops.len; + const usage_now = cuda.usage(false); + if (usage_now.device != usage_after_setup.device or usage_now.host != usage_after_setup.host) + try errors.add("{s}: counted allocations changed while running ({d} -> {d} device bytes)", .{ c.name, usage_after_setup.device, usage_now.device }); + + // per layer concatenated outputs + var files_json: std.ArrayList(u8) = .empty; + defer files_json.deinit(gpa); + for (0..layer_count) |layer| { + for ([_]struct { []const u8, *std.ArrayList(u8) }{ .{ "y", &ys[layer] }, .{ "old.y", &old_ys[layer] }, .{ "decbase.y", &base_ys[layer] } }) |entry| { + const kind, const list = entry; + if (list.items.len == 0) continue; + const name = try std.fmt.bufPrint(&path_buffer, "{s}/L{d}.{s}.bf16", .{ c.name, layer, kind }); + try out.writeFile(io, .{ .sub_path = name, .data = list.items, .flags = .{ .exclusive = true } }); + const file_sha = sha256Hex(list.items); + try files_json.print(gpa, "{s}\"L{d}.{s}.bf16\": {{\"sha256\": \"{s}\", \"rows\": {d}}}", .{ if (files_json.items.len == 0) "" else ", ", layer, kind, file_sha[0..], list.items.len / g.rowBytes() }); + } + } + + _, const ws_bytes = gdn.Workspace.layout(c.max_rows, g.nk, g.nv); + try cases_json.print(gpa, "{s}\n {{\"name\": \"{s}\", \"geometry\": \"{s}\", \"max_rows\": {d}, \"workspace_layout_bytes\": {d}, \"workspace_capacity_rows_contract\": {d}, \"init\": [", .{ + if (cases_json.items.len == 0) "" else ",", c.name, g.name, c.max_rows, ws_bytes, workspaceCapacity(c.max_rows), + }); + for (c.init, 0..) |iv, i| try cases_json.print(gpa, "{s}\"{s}\"", .{ if (i == 0) "" else ", ", if (iv) |x| cs.inits[x].name else "zero" }); + try cases_json.print(gpa, "], \"wall_s\": {d:.6}, \"files\": {{{s}}}, \"ops\": [", .{ @as(f64, @floatFromInt(case_ns)) / 1e9, files_json.items }); + for (c.ops, 0..) |op, oi| { + const a = records[0][oi]; + const b = records[1][oi]; + const repeat_equal = a.sameOutputs(b); + if (!repeat_equal) try errors.add("{s} op {d}: pass 1 did not reproduce pass 0 (outputs, states, metadata or controls)", .{ c.name, oi }); + try cases_json.print(gpa, "{s}\n {{\"index\": {d}, \"op\": \"{s}\", \"layer\": {d}", .{ if (oi == 0) "" else ",", oi, @tagName(op.kind), op.layer }); + if (op.kind == .reset) { + try cases_json.print(gpa, ", \"state\": \"{s}\", \"poison_cache\": {}", .{ if (op.init) |x| cs.inits[x].name else "zero", op.poison_cache }); + } else { + try cases_json.print(gpa, ", \"stream\": \"{s}\", \"start\": {d}, \"rows\": {d}, \"probe\": {}, \"y_sha256\": \"{s}\", \"old_y_sha256\": \"{s}\", \"old_state_sha256\": \"{s}\", \"y_unwritten\": {d}, \"y_nonfinite\": {d}, \"y_guard_before_changed\": {d}, \"y_guard_after_changed\": {d}, \"state_nonfinite\": {d}, \"ws_front_guard_changed\": {d}, \"ws_tail_changed\": {d}, \"inputs_unchanged\": {}, \"elapsed_s\": [{d:.9}, {d:.9}]", .{ + cs.streams[op.stream].name, op.start, op.rows, op.probe, a.y_sha[0..], a.old_y_sha[0..], a.old_state_sha[0..], a.y_unwritten, a.y_nonfinite, a.y_guard_before_changed, a.y_guard_after_changed, a.state_nonfinite, a.ws_front_guard_changed, a.ws_tail_changed, a.inputs_unchanged and b.inputs_unchanged, @as(f64, @floatFromInt(a.elapsed_ns)) / 1e9, @as(f64, @floatFromInt(b.elapsed_ns)) / 1e9, + }); + if (op.kind == .decode) try cases_json.print(gpa, ", \"decode_baseline\": {{\"y_sha256\": \"{s}\", \"state_sha256\": \"{s}\", \"y_bits_different\": {d}, \"state_bits_different\": {d}}}", .{ a.base_y_sha[0..], a.base_state_sha[0..], a.base_y_bits_different, a.base_state_bits_different }); + if (op.probe) { + try cases_json.print(gpa, ", \"gate_probe\": {{\"available\": {}, \"in_layout\": {}", .{ probe_available, a.probe_in_layout }); + for (probe_fields, 0..) |f, fi| try cases_json.print(gpa, ", \"{s}\": {{\"sha256\": \"{s}\", \"nonfinite\": {d}}}", .{ f, a.probe_sha[fi][0..], a.probe_nonfinite[fi] }); + try cases_json.appendSlice(gpa, "}"); + } + } + try cases_json.print(gpa, ", \"pending_before\": {d}, \"committed_bank_before\": {d}, \"pending_after\": {d}, \"committed_bank_after\": {d}, \"current_bank\": {s}, \"state_sha256\": \"{s}\", \"layer_guards_changed\": {d}, \"repeat_bit_exact\": {}}}", .{ + a.pending_before, a.committed_before, a.pending_after, a.committed_after, if (a.current_bank) |x| (if (x == 0) "0" else "1") else "null", a.state_sha[0..], a.layer_guards_changed, repeat_equal, + }); + } + try cases_json.appendSlice(gpa, "\n ]}"); + std.debug.print("{s}: ops={d} wall_s={d:.3} errors_so_far={d}\n", .{ c.name, c.ops.len, @as(f64, @floatFromInt(case_ns)) / 1e9, errors.count }); + } + const usage_end = cuda.usage(false); + const mem_end = try ctx.memInfo(); + + // 4. result.json + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const source_sha = sha256Hex(@embedFile("drama_gdn_canonical_oracle.zig")); + const evidence_valid = errors.count == 0; + var mj: std.ArrayList(u8) = .empty; + defer mj.deinit(gpa); + try mj.print(gpa, "{{\n \"schema\": \"{s}\",\n \"producer\": \"{s}\",\n \"glue_fatbin\": ", .{ result_schema, producer }); + try jsonString(&mj, gpa, args[1]); + try mj.print(gpa, ",\n \"glue_fatbin_sha256\": \"{s}\",\n \"glue_fatbin_bytes\": {d},\n \"frozen_fatbin\": ", .{ glue_sha[0..], glue_image.len }); + try jsonString(&mj, gpa, args[2]); + try mj.print(gpa, ",\n \"frozen_fatbin_sha256\": \"{s}\",\n \"cases_dir\": ", .{frozen_sha[0..]}); + try jsonString(&mj, gpa, args[3]); + try mj.print(gpa, ",\n \"cases_sha256\": \"{s}\",\n \"binary_sha256\": {s},\n \"oracle_source_sha256\": \"{s}\",\n \"device\": ", .{ cs.sha[0..], binary_json.items, source_sha[0..] }); + try jsonString(&mj, gpa, device_name); + try mj.print(gpa, ",\n \"capability\": {d},\n \"driver_version\": {d},\n \"scale_f32_bits\": {d},\n \"chunk_rows\": {d},\n \"passes\": {d},\n \"layers\": {d}," ++ + "\n \"gate_probe_fields_available\": {},\n \"controller\": \"drama.backbone.gdn: State.resetMetadata/current, Workspace.layout/place, Kernels.init/prefill/decode; frozen controls: {s} (decode baseline, old decode) and {s} (old sequential prefill)\"," ++ + "\n \"geometries\": [{s}\n ],\n \"cases\": [{s}\n ]," ++ + "\n \"allocations\": {{\"counted_device_bytes_start\": {d}, \"counted_device_bytes_after_setup\": {d}, \"counted_device_bytes_end\": {d}, \"counted_device_peak_bytes\": {d}, \"counted_pinned_host_bytes_end\": {d}, \"device_limit_bytes\": {d}, \"driver_free_bytes_after_setup\": {d}, \"driver_free_bytes_end\": {d}, \"driver_total_bytes\": {d}, \"host_scratch_bytes\": {d}}}," ++ + "\n \"ops_per_pass\": {d},\n \"wall_s\": {d:.6},\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + capability, driver_version, @as(u32, @bitCast(scale)), chunk, passes, layer_count, + probe_available, frozen_decode, frozen_prefill, geometry_json.items, cases_json.items, usage_start.device, + usage_after_setup.device, usage_end.device, usage_end.peak, usage_end.host, @as(u64, device_limit), mem_after_setup.free, + mem_end.free, mem_end.total, 2 * scratch_len, total_ops, @as(f64, @floatFromInt(nowNs(io) - started)) / 1e9, evidence_valid, + errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "result.json", .data = mj.items, .flags = .{ .exclusive = true } }); + std.debug.print("cases={d} ops_per_pass={d} evidence_valid={} errors={d}\n", .{ cs.cases.len, total_ops, evidence_valid, errors.count }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_gdn_layer0_trace.zig b/zig/tests/cuda/drama_gdn_layer0_trace.zig new file mode 100644 index 00000000000..e4d3afb308b --- /dev/null +++ b/zig/tests/cuda/drama_gdn_layer0_trace.zig @@ -0,0 +1,158 @@ +//! Diagnostic: production layer-0 attention on frozen inputs; args CHECKPOINT INPUT EXPECTED OUTPUT_DIR. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const Model = drama.backbone.Model; +const H = 2048; +const R = 128; +const source_rows = 182; +const lengths = [_]usize{ 1, 7, 128, 182 }; +const LD = drama.backbone.weights.gdn_in_rows; +const Capture = struct { file: []const u8, dtype: []const u8, shape: [2]usize, sha256: [64]u8 }; +const View = struct { name: []const u8, ptr: u64, cols: usize, rows: usize, f32: bool = false }; + +fn sha(bytes: []const u8) [64]u8 { + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + return std.fmt.bytesToHex(digest, .lower); +} +fn finite(bytes: []align(16) const u8, is_f32: bool) bool { + if (is_f32) { + for (std.mem.bytesAsSlice(f32, bytes)) |x| if (!std.math.isFinite(x)) return false; + } else { + for (std.mem.bytesAsSlice(u16, bytes)) |x| if ((x & 0x7f80) == 0x7f80) return false; + } + return true; +} +fn download(driver: *cuda.Driver, staging: []align(16) u8, view: View) ![]align(16) const u8 { + const bytes = view.rows * view.cols * @as(usize, if (view.f32) 4 else 2); + const buffer: cuda.DeviceBuffer = .{ .d = driver, .ptr = view.ptr, .len = bytes, .borrowed = true }; + try buffer.download(0, staging[0..bytes]); + if (!finite(staging[0..bytes], view.f32)) return error.NonfiniteCapture; + return staging[0..bytes]; +} +fn capture(gpa: std.mem.Allocator, io: std.Io, out: std.Io.Dir, driver: *cuda.Driver, staging: []align(16) u8, prefix: []const u8, view: View) !Capture { + const bytes = try download(driver, staging, view); + const file = try std.fmt.allocPrint(gpa, "{s}{s}.{s}", .{ prefix, view.name, if (view.f32) "f32" else "bf16" }); + errdefer gpa.free(file); + try out.writeFile(io, .{ .sub_path = file, .data = bytes, .flags = .{ .exclusive = true } }); + return .{ .file = file, .dtype = if (view.f32) "f32le" else "bf16le", .shape = .{ view.rows, view.cols }, .sha256 = sha(bytes) }; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 5) return error.UsageCheckpointInputExpectedOutputDirectory; + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + const total_bytes = source_rows * H * 2; + const input_data = try std.Io.Dir.cwd().readFileAllocOptions(io, args[2], gpa, .limited(total_bytes + 1), .@"16", null); + defer gpa.free(input_data); + const expected = try std.Io.Dir.cwd().readFileAllocOptions(io, args[3], gpa, .limited(total_bytes + 1), .@"16", null); + defer gpa.free(expected); + if (input_data.len != total_bytes or expected.len != total_bytes) return error.FixtureShape; + if (!finite(input_data, false) or !finite(expected, false)) return error.NonfiniteFixture; + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try Model.init(gpa, io, &ctx, args[1], "", .{ .context = 512, .max_rows = R }); + defer model.deinit(); + if (!drama.backbone.config.linear(0) or model.hidden != H) return error.UnexpectedArchitecture; + var input = try cuda.HostBuffer.alloc(&driver, total_bytes); + defer input.free(); + var output = try cuda.HostBuffer.alloc(&driver, total_bytes); + defer output.free(); + const staging = try gpa.alignedAlloc(u8, .@"16", LD * H * 2); + defer gpa.free(staging); + const w = &model.w.layers[0]; + const weight_views = [_]View{ + .{ .name = "weight_in", .ptr = w.gdn_in, .rows = LD, .cols = H }, + .{ .name = "weight_conv", .ptr = w.conv, .rows = 8192, .cols = 4 }, + .{ .name = "weight_a_log", .ptr = w.a_log, .rows = 32, .cols = 1, .f32 = true }, + .{ .name = "weight_dt_bias", .ptr = w.dt_bias, .rows = 32, .cols = 1, .f32 = true }, + .{ .name = "weight_norm", .ptr = w.gnorm, .rows = 1, .cols = 128 }, + .{ .name = "weight_out", .ptr = w.gdn_out, .rows = H, .cols = 4096 }, + }; + var captures: std.ArrayList(Capture) = .empty; + defer { + for (captures.items) |c| gpa.free(c.file); + captures.deinit(gpa); + } + try captures.ensureTotalCapacity(gpa, weight_views.len + lengths.len * 6); + for (weight_views) |view| captures.appendAssumeCapacity(try capture(gpa, io, out, &driver, staging, "", view)); + for (lengths) |rows| { + const bytes = rows * H * 2; + const row0: usize = if (rows == source_rows) R else 0; + const captured_rows = rows - row0; + const captured_at = row0 * H * 2; + const chunks: []const usize = if (rows == source_rows) &.{ R, source_rows - R } else &.{rows}; + @memcpy(input.bytes[0..bytes], input_data[0..bytes]); + const views = [_]View{ + .{ .name = "input", .ptr = model.s.normed, .rows = captured_rows, .cols = H }, + .{ .name = "proj", .ptr = model.s.proj, .rows = captured_rows, .cols = LD }, + .{ .name = "conv", .ptr = model.s.conv, .rows = captured_rows, .cols = 8192 }, + .{ .name = "core", .ptr = model.s.core, .rows = captured_rows, .cols = 4096 }, + .{ .name = "gated", .ptr = model.s.gated, .rows = captured_rows, .cols = 4096 }, + .{ .name = "output", .ptr = model.s.x, .rows = captured_rows, .cols = H }, + }; + var hashes: [views.len][64]u8 = undefined; + var prefix_buffer: [32]u8 = undefined; + const prefix = try std.fmt.bufPrint(&prefix_buffer, "rows-{d}-", .{rows}); + for (0..2) |repeat| { + try model.reset(stream); + @memset(output.bytes[0..bytes], 0xff); + try model.replayOperator(stream, 0, .attention, chunks, input.bytes[0..bytes], output.bytes[0..bytes]); + if (!std.mem.eql(u8, output.bytes[0..bytes], expected[0..bytes])) return error.NativeFrozenSelfControl; + if (!std.mem.eql(u8, input.bytes[0..bytes], input_data[0..bytes])) return error.HostInputMutated; + for (views, 0..) |view, i| { + if (repeat == 0) { + const c = try capture(gpa, io, out, &driver, staging, prefix, view); + hashes[i] = c.sha256; + captures.appendAssumeCapacity(c); + } else if (!std.mem.eql(u8, &sha(try download(&driver, staging, view)), &hashes[i])) { + return error.ScratchRepeatMismatch; + } + } + if (!std.mem.eql(u8, &hashes[0], &sha(input_data[captured_at..bytes]))) return error.DeviceInputMutated; + if (!std.mem.eql(u8, &hashes[5], &sha(output.bytes[captured_at..bytes]))) return error.OutputCaptureMismatch; + } + } + for (weight_views, 0..) |view, i| { + if (!std.mem.eql(u8, &sha(try download(&driver, staging, view)), &captures.items[i].sha256)) return error.WeightMutated; + } + const used = cuda.usage(false); + const manifest = try std.json.Stringify.valueAlloc(gpa, .{ + .producer = "tf-drama-gdn-layer0-trace", + .evidence_valid = true, + .layer = 0, + .rows = lengths, + .repeats = 2, + .native_frozen_prefix_controls = true, + .capture_row_offsets = [_]usize{ 0, 0, 0, 128 }, + .capture_rows = [_]usize{ 1, 7, 128, 54 }, + .scratch_repeat_controls = true, + .input_and_weight_immutability = true, + .input_sha256 = sha(input_data), + .expected_sha256 = sha(expected), + .driver_source_sha256 = sha(@embedFile("drama_gdn_layer0_trace.zig")), + .backbone_source_sha256 = sha(drama.backbone.trace_source), + .backbone_image_sha256 = sha(cuda.kernels.drama_backbone), + .gemm_image_sha256 = sha(cuda.kernels.drama_backbone_gemm), + .norm_image_sha256 = sha(cuda.kernels.norms), + .cuda_bytes = used.device, + .cuda_peak_bytes = used.peak, + .pinned_host_bytes = used.host, + .captures = captures.items, + }, .{ .whitespace = .indent_2 }); + defer gpa.free(manifest); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest, .flags = .{ .exclusive = true } }); + std.debug.print("layer=0 rows=1,7,128,182 repeats=2 frozen_native_exact=true captures={d} cuda_bytes={d}\n", .{ captures.items.len, used.device }); + return 0; +} diff --git a/zig/tests/cuda/drama_gdn_oracle_cases.zig b/zig/tests/cuda/drama_gdn_oracle_cases.zig new file mode 100644 index 00000000000..1ffd8ccc40f --- /dev/null +++ b/zig/tests/cuda/drama_gdn_oracle_cases.zig @@ -0,0 +1,285 @@ +//! tf-drama-gdn-canonical-oracle's cases.json: geometries, input streams, initial states and ops, strictly checked. +const std = @import("std"); +const drama = @import("drama"); +const gdn = drama.backbone.gdn; +const Allocator = std.mem.Allocator; +const chunk = gdn.chunk_rows; +const gdn_oracle = @import("drama_gdn_canonical_oracle.zig"); +const cases_schema = gdn_oracle.cases_schema; +const dv = gdn_oracle.dv; +const layer_count = gdn_oracle.layer_count; +const max_file = gdn_oracle.max_file; +const sha256Hex = gdn_oracle.sha256Hex; + +const BadCases = error{BadCases}; + +fn bad(comptime f: []const u8, args: anytype) BadCases { + std.debug.print("cases manifest: " ++ f ++ "\n", args); + return error.BadCases; +} + +const File = struct { name: []const u8, sha: []const u8, bytes: []align(16) const u8 }; + +pub const Geometry = struct { + name: []const u8, + nk: usize, + nv: usize, + a_log: File, + dt_bias: File, + max_rows: usize = 0, // largest case max_rows: output rows allocated + ws_bytes: usize = 0, // largest Workspace.layout size over this geometry's cases + used: bool = false, + + pub fn width(g: Geometry) usize { + return (2 * g.nk + g.nv) * dv; + } + pub fn stateBytes(g: Geometry) usize { + return g.nv * dv * dv * 4; + } + pub fn rowBytes(g: Geometry) usize { + return g.nv * dv * 2; + } + pub fn qkvCacheBytes(g: Geometry) usize { + return chunk * g.width() * 2; + } + pub fn baCacheBytes(g: Geometry) usize { + return chunk * 2 * g.nv * 2; + } +}; + +const Stream = struct { name: []const u8, geometry: usize, rows: usize, ld_qkv: usize, ld_ba: usize, qkv: File, ba: File }; +const Init = struct { name: []const u8, geometry: usize, file: File }; +const OpKind = enum { prefill, decode, reset }; +pub const Op = struct { + kind: OpKind, + layer: usize, + stream: usize = 0, + start: usize = 0, + rows: usize = 0, + probe: bool = false, + init: ?usize = null, // reset: null = zero state + poison_cache: bool = false, +}; +pub const Case = struct { + name: []const u8, + geometry: usize, + max_rows: usize, + init: [layer_count]?usize, + ops: []const Op, + save_old_states: bool, + last_op: [layer_count]?usize, // the layer's last prefill/decode op +}; + +pub const Cases = struct { + sha: [64]u8, + geometries: []Geometry, + streams: []Stream, + inits: []Init, + cases: []Case, +}; + +fn get(o: std.json.ObjectMap, key: []const u8) BadCases!std.json.Value { + return o.get(key) orelse bad("missing key {s}", .{key}); +} + +fn uintOf(o: std.json.ObjectMap, key: []const u8) BadCases!usize { + const v = try get(o, key); + if (v != .integer or v.integer < 0) return bad("{s} is not a non-negative integer", .{key}); + return @intCast(v.integer); +} + +fn textOf(o: std.json.ObjectMap, key: []const u8) BadCases![]const u8 { + const v = try get(o, key); + if (v != .string) return bad("{s} is not a string", .{key}); + return v.string; +} + +fn boolOr(o: std.json.ObjectMap, key: []const u8, default: bool) BadCases!bool { + const v = o.get(key) orelse return default; + if (v != .bool) return bad("{s} is not a bool", .{key}); + return v.bool; +} + +fn objectOf(v: std.json.Value, what: []const u8) BadCases!std.json.ObjectMap { + if (v != .object) return bad("{s} is not an object", .{what}); + return v.object; +} + +fn arrayOf(o: std.json.ObjectMap, key: []const u8) BadCases![]std.json.Value { + const v = try get(o, key); + if (v != .array) return bad("{s} is not an array", .{key}); + return v.array.items; +} + +/// Names become file names: lowercase letters, digits, '_', '-', '.', not leading '.', at most 96 bytes. +fn safeName(s: []const u8) BadCases![]const u8 { + if (s.len == 0 or s.len > 96 or s[0] == '.') return bad("unsafe name '{s}'", .{s}); + for (s) |c| switch (c) { + 'a'...'z', '0'...'9', '_', '-', '.' => {}, + else => return bad("unsafe name '{s}'", .{s}), + }; + return s; +} + +fn isSha256Hex(s: []const u8) bool { + if (s.len != 64) return false; + for (s) |c| switch (c) { + '0'...'9', 'a'...'f' => {}, + else => return false, + }; + return true; +} + +fn loadFile(arena: Allocator, io: std.Io, dir: std.Io.Dir, v: std.json.Value, what: []const u8, size: usize) !File { + const o = try objectOf(v, what); + const name = try safeName(try textOf(o, "file")); + const sha = try textOf(o, "sha256"); + if (!isSha256Hex(sha)) return bad("{s}: sha256 is not 64 lowercase hex digits", .{what}); + const bytes = dir.readFileAllocOptions(io, name, arena, .limited(max_file), .@"16", null) catch |err| + return bad("{s}: {s} unreadable: {s}", .{ what, name, @errorName(err) }); + if (bytes.len != size) return bad("{s}: {s} has {d} bytes, expected {d}", .{ what, name, bytes.len, size }); + const got = sha256Hex(bytes); + if (!std.mem.eql(u8, &got, sha)) return bad("{s}: {s} sha256 {s} is not the manifest's {s}", .{ what, name, got[0..], sha }); + return .{ .name = name, .sha = sha, .bytes = bytes }; +} + +fn findName(comptime T: type, items: []const T, name: []const u8, what: []const u8) BadCases!usize { + for (items, 0..) |item, i| { + if (std.mem.eql(u8, item.name, name)) return i; + } + return bad("unknown {s} '{s}'", .{ what, name }); +} + +pub fn workspaceCapacity(max_rows: usize) usize { + return @max(chunk, max_rows / chunk * chunk); +} + +pub fn parseCases(arena: Allocator, io: std.Io, dir: std.Io.Dir) !Cases { + const text = dir.readFileAlloc(io, "cases.json", arena, .limited(1 << 24)) catch |err| return bad("cases.json unreadable: {s}", .{@errorName(err)}); + const doc = std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}) catch |err| return bad("cases.json is not JSON: {s}", .{@errorName(err)}); + const root = try objectOf(doc, "cases.json"); + if (!std.mem.eql(u8, try textOf(root, "schema"), cases_schema)) return bad("schema is not {s}", .{cases_schema}); + + const gs = try arrayOf(root, "geometries"); + const geometries = try arena.alloc(Geometry, gs.len); + for (gs, geometries) |v, *g| { + const o = try objectOf(v, "geometry"); + const nk = try uintOf(o, "nk"); + const nv = try uintOf(o, "nv"); + if (nk == 0 or nv == 0 or nv % nk != 0) return bad("geometry nk {d} nv {d}: nv must be a positive multiple of nk", .{ nk, nv }); + if ((try uintOf(o, "dv")) != dv) return bad("geometry dv must be {d}", .{dv}); + g.* = .{ + .name = try safeName(try textOf(o, "name")), + .nk = nk, + .nv = nv, + .a_log = try loadFile(arena, io, dir, try get(o, "a_log"), "a_log", nv * 4), + .dt_bias = try loadFile(arena, io, dir, try get(o, "dt_bias"), "dt_bias", nv * 4), + }; + } + for (geometries, 0..) |g, i| for (geometries[0..i]) |h| if (std.mem.eql(u8, g.name, h.name)) return bad("duplicate geometry {s}", .{g.name}); + + const ss = try arrayOf(root, "streams"); + const streams = try arena.alloc(Stream, ss.len); + for (ss, streams) |v, *s| { + const o = try objectOf(v, "stream"); + const gi = try findName(Geometry, geometries, try textOf(o, "geometry"), "geometry"); + const g = geometries[gi]; + const rows = try uintOf(o, "rows"); + const ld_qkv = try uintOf(o, "ld_qkv"); + const ld_ba = try uintOf(o, "ld_ba"); + if (rows == 0) return bad("stream with zero rows", .{}); + if (ld_qkv < g.width() or ld_ba < 2 * g.nv) return bad("stream strides {d}/{d} below the row widths {d}/{d}", .{ ld_qkv, ld_ba, g.width(), 2 * g.nv }); + if (ld_qkv % 8 != 0 or ld_ba % 8 != 0) return bad("stream strides must keep 16-byte rows", .{}); + s.* = .{ + .name = try safeName(try textOf(o, "name")), + .geometry = gi, + .rows = rows, + .ld_qkv = ld_qkv, + .ld_ba = ld_ba, + .qkv = try loadFile(arena, io, dir, try get(o, "qkv"), "qkv", rows * ld_qkv * 2), + .ba = try loadFile(arena, io, dir, try get(o, "ba"), "ba", rows * ld_ba * 2), + }; + } + + const is = try arrayOf(root, "states"); + const inits = try arena.alloc(Init, is.len); + for (is, inits) |v, *s| { + const o = try objectOf(v, "state"); + const gi = try findName(Geometry, geometries, try textOf(o, "geometry"), "geometry"); + s.* = .{ + .name = try safeName(try textOf(o, "name")), + .geometry = gi, + .file = try loadFile(arena, io, dir, try get(o, "data"), "state", geometries[gi].stateBytes()), + }; + } + + const cs = try arrayOf(root, "cases"); + const cases = try arena.alloc(Case, cs.len); + for (cs, cases) |v, *c| { + const o = try objectOf(v, "case"); + const name = try safeName(try textOf(o, "name")); + const gi = try findName(Geometry, geometries, try textOf(o, "geometry"), "geometry"); + const max_rows = try uintOf(o, "max_rows"); + if (max_rows == 0) return bad("{s}: max_rows 0", .{name}); + const init_list = try arrayOf(o, "init"); + if (init_list.len != layer_count) return bad("{s}: init must name {d} layer states", .{ name, layer_count }); + var init: [layer_count]?usize = undefined; + for (init_list, &init) |iv, *slot| slot.* = try initRef(inits, iv, gi, name); + const ov = try arrayOf(o, "ops"); + if (ov.len == 0) return bad("{s}: no ops", .{name}); + const ops = try arena.alloc(Op, ov.len); + var last: [layer_count]?usize = @splat(null); + for (ov, ops, 0..) |item, *op, oi| { + const p = try objectOf(item, "op"); + const kind = std.meta.stringToEnum(OpKind, try textOf(p, "op")) orelse return bad("{s} op {d}: unknown op", .{ name, oi }); + const layer = try uintOf(p, "layer"); + if (layer >= layer_count) return bad("{s} op {d}: layer {d}", .{ name, oi, layer }); + op.* = .{ .kind = kind, .layer = layer }; + switch (kind) { + .reset => { + op.init = try initRef(inits, try get(p, "state"), gi, name); + op.poison_cache = try boolOr(p, "poison_cache", false); + }, + .prefill, .decode => { + op.stream = try findName(Stream, streams, try textOf(p, "stream"), "stream"); + op.start = try uintOf(p, "start"); + op.rows = try uintOf(p, "rows"); + op.probe = try boolOr(p, "probe", false); + const s = streams[op.stream]; + if (s.geometry != gi) return bad("{s} op {d}: stream {s} has another geometry", .{ name, oi, s.name }); + if (op.rows == 0 or op.rows > max_rows) return bad("{s} op {d}: rows {d} outside 1..max_rows {d}", .{ name, oi, op.rows, max_rows }); + if (op.start + op.rows > s.rows) return bad("{s} op {d}: rows {d}+{d} beyond stream {s}", .{ name, oi, op.start, op.rows, s.name }); + if (op.probe and kind != .prefill) return bad("{s} op {d}: probe on a decode", .{ name, oi }); + last[layer] = oi; + }, + } + } + c.* = .{ + .name = name, + .geometry = gi, + .max_rows = max_rows, + .init = init, + .ops = ops, + .save_old_states = try boolOr(o, "save_old_states", false), + .last_op = last, + }; + const g = &geometries[gi]; + g.used = true; + g.max_rows = @max(g.max_rows, max_rows); + _, const ws_bytes = gdn.Workspace.layout(max_rows, g.nk, g.nv); + g.ws_bytes = @max(g.ws_bytes, ws_bytes); + } + for (cases, 0..) |c, i| for (cases[0..i]) |d| if (std.mem.eql(u8, c.name, d.name)) return bad("duplicate case {s}", .{c.name}); + return .{ .sha = sha256Hex(text), .geometries = geometries, .streams = streams, .inits = inits, .cases = cases }; +} + +/// A state reference: the string "zero" or the name of a state of geometry `gi`. +fn initRef(inits: []const Init, v: std.json.Value, gi: usize, case_name: []const u8) BadCases!?usize { + if (v != .string) return bad("{s}: state reference is not a string", .{case_name}); + if (std.mem.eql(u8, v.string, "zero")) return null; + const i = try findName(Init, inits, v.string, "state"); + if (inits[i].geometry != gi) return bad("{s}: state {s} has another geometry", .{ case_name, v.string }); + return i; +} + +// recorded failures, hashing, JSON diff --git a/zig/tests/cuda/drama_gdn_oracle_runner.zig b/zig/tests/cuda/drama_gdn_oracle_runner.zig new file mode 100644 index 00000000000..114e2a4ffbc --- /dev/null +++ b/zig/tests/cuda/drama_gdn_oracle_runner.zig @@ -0,0 +1,395 @@ +//! tf-drama-gdn-canonical-oracle's device side: guarded controller memory and the runner that executes each case. +const std = @import("std"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const gdn = drama.backbone.gdn; +const Allocator = std.mem.Allocator; +const chunk = gdn.chunk_rows; +const gdn_oracle = @import("drama_gdn_canonical_oracle.zig"); +const gdn_cases = @import("drama_gdn_oracle_cases.zig"); +const dv = gdn_oracle.dv; +const layer_count = gdn_oracle.layer_count; +const guard = gdn_oracle.guard; +const y_guard_rows = gdn_oracle.y_guard_rows; +const fill = gdn_oracle.fill; +const probe_fields = gdn_oracle.probe_fields; +const probe_available = gdn_oracle.probe_available; +const Geometry = gdn_cases.Geometry; +const Op = gdn_cases.Op; +const Case = gdn_cases.Case; +const Cases = gdn_cases.Cases; +const Errors = gdn_oracle.Errors; +const sha256Hex = gdn_oracle.sha256Hex; +const nowNs = gdn_oracle.nowNs; +const notFill = gdn_oracle.notFill; +const nonfiniteBf16 = gdn_oracle.nonfiniteBf16; +const unwrittenBf16 = gdn_oracle.unwrittenBf16; +const nonfiniteF32 = gdn_oracle.nonfiniteF32; +const bitsDifferent = gdn_oracle.bitsDifferent; +const int = gdn_oracle.int; +const sameBank = gdn_oracle.sameBank; + +/// One layer's caller-owned controller memory with guards between every buffer, and its frozen-control states. +pub const LayerMem = struct { + region: cuda.DeviceBuffer, + old: cuda.DeviceBuffer, // the frozen sequential chain's state (frozen prefill/decode exports) + state: gdn.State, + bank_bytes: usize, + qkv_cache_bytes: usize, + ba_cache_bytes: usize, + + pub fn offsets(m: LayerMem) [4]usize { + const b0 = guard; + const b1 = b0 + m.bank_bytes + guard; + const q = b1 + m.bank_bytes + guard; + const a = q + m.qkv_cache_bytes + guard; + return .{ b0, b1, q, a }; + } + + pub fn total(bank: usize, qkvc: usize, bac: usize) usize { + return 5 * guard + 2 * bank + qkvc + bac; + } + + /// [start, len) of the five guards. + fn guards(m: LayerMem) [5][2]usize { + const o = m.offsets(); + return .{ .{ 0, guard }, .{ o[0] + m.bank_bytes, guard }, .{ o[1] + m.bank_bytes, guard }, .{ o[2] + m.qkv_cache_bytes, guard }, .{ o[3] + m.ba_cache_bytes, guard } }; + } +}; + +pub const GeoMem = struct { + a_log: cuda.DeviceBuffer, + dt_bias: cuda.DeviceBuffer, + layers: [layer_count]LayerMem, + ws: cuda.DeviceBuffer, // guard | workspace (largest layout) | guard + y: cuda.DeviceBuffer, // guard rows | max_rows | guard rows, bf16 rows of nv * 128 + y_old: cuda.DeviceBuffer, + y_base: cuda.DeviceBuffer, + base_state: cuda.DeviceBuffer, +}; + +fn view(d: *const cuda.Driver, ptr: u64, len: usize) cuda.DeviceBuffer { + return .{ .d = d, .ptr = ptr, .len = len, .borrowed = true }; +} + +const Recur = struct { qkv: u64, ld_qkv: usize, ba: u64, ld_ba: usize, a_log: u64, dt_bias: u64, state: u64, y: u64, rows: usize, nk: usize, nv: usize, scale: f32 }; + +/// The frozen image's exports with backbone-kernels-pre-chunk.zig's launch: grid (128 / 32, nv), 128 threads. +fn launchFrozen(f: cuda.Function, s: cuda.Stream, r: Recur) !void { + var a: cuda.Args = .{}; + a.add(r.qkv); + a.add(int(r.ld_qkv)); + a.add(r.ba); + a.add(int(r.ld_ba)); + a.add(r.a_log); + a.add(r.dt_bias); + a.add(r.state); + a.add(r.y); + a.add(int(r.rows)); + a.add(int(r.nk)); + a.add(int(r.nv)); + a.add(r.scale); + try cuda.launch.launch(f, .{ .grid = .{ .x = dv / 32, .y = @intCast(r.nv), .z = 1 }, .block = .{ .x = 128 } }, s, &a); +} + +/// What one op observed in one pass. +pub const OpRecord = struct { + pending_before: usize = 0, + committed_before: u1 = 0, + pending_after: usize = 0, + committed_after: u1 = 0, + current_bank: ?u1 = null, + y_sha: [64]u8 = @splat('-'), + state_sha: [64]u8 = @splat('-'), + old_y_sha: [64]u8 = @splat('-'), + old_state_sha: [64]u8 = @splat('-'), + base_y_sha: [64]u8 = @splat('-'), + base_state_sha: [64]u8 = @splat('-'), + base_y_bits_different: usize = 0, + base_state_bits_different: usize = 0, + y_unwritten: usize = 0, + y_nonfinite: usize = 0, + y_guard_before_changed: usize = 0, + y_guard_after_changed: usize = 0, + state_nonfinite: usize = 0, + ws_front_guard_changed: usize = 0, + ws_tail_changed: usize = 0, + layer_guards_changed: usize = 0, + inputs_unchanged: bool = true, + elapsed_ns: i128 = 0, + probe_sha: [probe_fields.len][64]u8 = @splat(@splat('-')), + probe_nonfinite: [probe_fields.len]usize = @splat(0), + probe_in_layout: bool = false, + + pub fn sameOutputs(a: OpRecord, b: OpRecord) bool { + return a.pending_after == b.pending_after and a.committed_after == b.committed_after and sameBank(a.current_bank, b.current_bank) and + std.mem.eql(u8, &a.y_sha, &b.y_sha) and std.mem.eql(u8, &a.state_sha, &b.state_sha) and + std.mem.eql(u8, &a.old_y_sha, &b.old_y_sha) and std.mem.eql(u8, &a.old_state_sha, &b.old_state_sha) and + std.mem.eql(u8, &a.base_y_sha, &b.base_y_sha) and std.mem.eql(u8, &a.base_state_sha, &b.base_state_sha) and + std.mem.eql(u8, std.mem.sliceAsBytes(&a.probe_sha), std.mem.sliceAsBytes(&b.probe_sha)); + } +}; + +pub const Runner = struct { + gpa: Allocator, + io: std.Io, + d: *const cuda.Driver, + stream: cuda.Stream, + kernels: *const gdn.Kernels, + frozen_decode_fn: cuda.Function, + frozen_prefill_fn: cuda.Function, + cs: *const Cases, + stream_bufs: []const [2]cuda.DeviceBuffer, // per stream: qkv, ba + out: std.Io.Dir, + errors: *Errors, + scale: f32, + // host scratch, sized once for the largest geometry and stream + scratch: []align(16) u8, + scratch2: []align(16) u8, + + fn sync(r: *const Runner) !void { + try r.stream.synchronize(); + } + + fn download(r: *const Runner, ptr: u64, len: usize, dst: []align(16) u8) ![]align(16) u8 { + const buf = dst[0..len]; + try view(r.d, ptr, len).download(0, buf); + return buf; + } + + /// Zero (or NaN-poison) the layer's caches, zero both banks, resetMetadata, then a nonzero state into bank0. + fn reset(r: *Runner, g: Geometry, m: *GeoMem, layer: usize, init: ?usize, poison_cache: bool, rec: *OpRecord) !void { + const lm = &m.layers[layer]; + const o = lm.offsets(); + const base = lm.region.ptr; + try view(r.d, base + o[0], lm.bank_bytes).fill8(0, r.stream.handle); + try view(r.d, base + o[1], lm.bank_bytes).fill8(0, r.stream.handle); + const cache_value: u8 = if (poison_cache) fill else 0; + try view(r.d, base + o[2], lm.qkv_cache_bytes).fill8(cache_value, r.stream.handle); + try view(r.d, base + o[3], lm.ba_cache_bytes).fill8(cache_value, r.stream.handle); + try lm.old.fill8(0, r.stream.handle); + rec.pending_before = lm.state.pending; + rec.committed_before = lm.state.committed_bank; + lm.state.resetMetadata(); + try r.sync(); + if (init) |i| { + const bytes = r.cs.inits[i].file.bytes; + try view(r.d, lm.state.banks[0], g.stateBytes()).upload(0, bytes); + try lm.old.upload(0, bytes); + } + rec.pending_after = lm.state.pending; + rec.committed_after = lm.state.committed_bank; + rec.current_bank = bankOf(lm.state); + if (lm.state.pending != 0 or lm.state.committed_bank != 0 or !sameBank(rec.current_bank, 0)) + try r.errors.add("layer {d}: after resetMetadata pending {d} committed_bank {d}, current() not bank0", .{ layer, lm.state.pending, lm.state.committed_bank }); + const cur = try r.download(lm.state.current(), g.stateBytes(), r.scratch); + rec.state_sha = sha256Hex(cur); + if (init) |i| { + if (!std.mem.eql(u8, cur, r.cs.inits[i].file.bytes)) try r.errors.add("layer {d}: bank0 does not hold the uploaded initial state", .{layer}); + } else if (notZero(cur)) try r.errors.add("layer {d}: zeroed bank0 is not zero", .{layer}); + } + + fn notZero(bytes: []const u8) bool { + for (bytes) |b| { + if (b != 0) return true; + } + return false; + } + + fn bankOf(s: gdn.State) ?u1 { + const c = s.current(); + if (c == s.banks[0]) return 0; + if (c == s.banks[1]) return 1; + return null; + } + + fn checkInputs(r: *Runner, g: Geometry, m: *GeoMem, op: Op) !bool { + const s = r.cs.streams[op.stream]; + const bufs = r.stream_bufs[op.stream]; + var same = true; + for ([_]struct { []align(16) const u8, cuda.DeviceBuffer }{ .{ s.qkv.bytes, bufs[0] }, .{ s.ba.bytes, bufs[1] }, .{ g.a_log.bytes, m.a_log }, .{ g.dt_bias.bytes, m.dt_bias } }) |pair| { + const host, const dev = pair; + const got = try r.download(dev.ptr, host.len, r.scratch2); + if (!std.mem.eql(u8, got, host)) same = false; + } + return same; + } + + fn checkLayerGuards(r: *Runner, m: *GeoMem) !usize { + var changed: usize = 0; + for (m.layers) |lm| { + for (lm.guards()) |gr| changed += notFill(try r.download(lm.region.ptr + gr[0], gr[1], r.scratch2)); + } + return changed; + } + + /// Rows [0, n) of the guarded output buffer, after checking coverage and both guards. + fn checkY(r: *Runner, g: Geometry, buf: cuda.DeviceBuffer, n: usize, rec: *OpRecord) ![]align(16) u8 { + const rb = g.rowBytes(); + const all = try r.download(buf.ptr, buf.len, r.scratch2); + rec.y_guard_before_changed = notFill(all[0 .. y_guard_rows * rb]); + const rows: []align(16) u8 = @alignCast(all[y_guard_rows * rb ..][0 .. n * rb]); + rec.y_guard_after_changed = notFill(all[(y_guard_rows + n) * rb ..]); + const values = std.mem.bytesAsSlice(u16, rows); + rec.y_unwritten = unwrittenBf16(values); + rec.y_nonfinite = nonfiniteBf16(values); + return rows; + } + + pub fn runCase(r: *Runner, c: Case, m: *GeoMem, records: []OpRecord, pass: usize, ys: *[layer_count]std.ArrayList(u8), old_ys: *[layer_count]std.ArrayList(u8), base_ys: *[layer_count]std.ArrayList(u8)) !void { + const g = r.cs.geometries[c.geometry]; + const ws_proto, const ws_bytes = gdn.Workspace.layout(c.max_rows, g.nk, g.nv); + const ws_base = m.ws.ptr + guard; + const ws = ws_proto.place(ws_base); + const rb = g.rowBytes(); + const y_ptr = m.y.ptr + y_guard_rows * rb; + var path_buffer: [256]u8 = undefined; + + // a pass starts from both layers' case initial states + for (0..layer_count) |layer| { + var rec: OpRecord = .{}; + try r.reset(g, m, layer, c.init[layer], false, &rec); + } + for (c.ops, records, 0..) |op, *rec, oi| { + rec.* = .{}; + const lm = &m.layers[op.layer]; + if (op.kind == .reset) { + try r.reset(g, m, op.layer, op.init, op.poison_cache, rec); + rec.layer_guards_changed = try r.checkLayerGuards(m); + continue; + } + const sb = r.stream_bufs[op.stream]; + const s = r.cs.streams[op.stream]; + const run: gdn.Run = .{ + .qkv = sb[0].ptr + op.start * s.ld_qkv * 2, + .ld_qkv = s.ld_qkv, + .ba = sb[1].ptr + op.start * s.ld_ba * 2, + .ld_ba = s.ld_ba, + .a_log = m.a_log.ptr, + .dt_bias = m.dt_bias.ptr, + .y = y_ptr, + .rows = op.rows, + .nk = g.nk, + .nv = g.nv, + .dv = dv, + .scale = r.scale, + }; + const frozen: Recur = .{ .qkv = run.qkv, .ld_qkv = run.ld_qkv, .ba = run.ba, .ld_ba = run.ld_ba, .a_log = run.a_log, .dt_bias = run.dt_bias, .state = lm.old.ptr, .y = m.y_old.ptr, .rows = op.rows, .nk = g.nk, .nv = g.nv, .scale = r.scale }; + rec.pending_before = lm.state.pending; + rec.committed_before = lm.state.committed_bank; + try m.y.fill8(fill, r.stream.handle); + if (op.kind == .prefill) { + try m.ws.fill8(fill, r.stream.handle); + try r.sync(); + const t0 = nowNs(r.io); + try r.kernels.prefill(r.stream, &lm.state, ws, run); + try r.sync(); + rec.elapsed_ns = nowNs(r.io) - t0; + rec.ws_front_guard_changed = notFill(try r.download(m.ws.ptr, guard, r.scratch2)); + rec.ws_tail_changed = notFill(try r.download(ws_base + ws_bytes, m.ws.len - guard - ws_bytes, r.scratch2)); + if (op.probe) try r.probe(c, g, ws, ws_base, ws_bytes, op, oi, rec, pass, &path_buffer); + } else { + // the unchanged frozen decode on a copy of the state decode must start from, the same rows + try m.y_base.fill8(fill, r.stream.handle); + try m.base_state.copyFrom(0, lm.state.current(), g.stateBytes(), r.stream.handle); + try r.sync(); + const t0 = nowNs(r.io); + try r.kernels.decode(r.stream, &lm.state, run); + try r.sync(); + rec.elapsed_ns = nowNs(r.io) - t0; + var base = frozen; + base.state = m.base_state.ptr; + base.y = m.y_base.ptr; + try launchFrozen(r.frozen_decode_fn, r.stream, base); + try r.sync(); + } + rec.pending_after = lm.state.pending; + rec.committed_after = lm.state.committed_bank; + rec.current_bank = bankOf(lm.state); + if (rec.current_bank == null) try r.errors.add("{s} op {d}: State.current() is neither bank", .{ c.name, oi }); + + // the controller's outputs, then its state, before any control touches device memory again + const y = try r.checkY(g, m.y, op.rows, rec); + rec.y_sha = sha256Hex(y); + if (pass == 0) try ys[op.layer].appendSlice(r.gpa, y); + const y_copy = try r.gpa.alignedAlloc(u8, .@"16", y.len); + defer r.gpa.free(y_copy); + @memcpy(y_copy, y); + const state = try r.download(lm.state.current(), g.stateBytes(), r.scratch); + rec.state_sha = sha256Hex(state); + rec.state_nonfinite = nonfiniteF32(state); + if (pass == 0) { + const name = try std.fmt.bufPrint(&path_buffer, "{s}/op-{d:0>4}.state.f32", .{ c.name, oi }); + try r.out.writeFile(r.io, .{ .sub_path = name, .data = state, .flags = .{ .exclusive = true } }); + } + if (op.kind == .decode) { + const by = try r.download(m.y_base.ptr, op.rows * rb, r.scratch2); + rec.base_y_sha = sha256Hex(by); + rec.base_y_bits_different = bitsDifferent(u16, by, y_copy); + if (pass == 0) try base_ys[op.layer].appendSlice(r.gpa, by); + const bs = try r.download(m.base_state.ptr, g.stateBytes(), r.scratch2); + rec.base_state_sha = sha256Hex(bs); + rec.base_state_bits_different = bitsDifferent(u32, bs, state); + if (rec.base_y_bits_different != 0 or rec.base_state_bits_different != 0) { + try r.errors.add("{s} op {d}: decode differs from the frozen decode export on identical state and rows ({d} output, {d} state elements)", .{ c.name, oi, rec.base_y_bits_different, rec.base_state_bits_different }); + if (pass == 0) { + const name = try std.fmt.bufPrint(&path_buffer, "{s}/op-{d:0>4}.decbase.state.f32", .{ c.name, oi }); + try r.out.writeFile(r.io, .{ .sub_path = name, .data = bs, .flags = .{ .exclusive = true } }); + } + } + } + + // the frozen sequential chain on its own state: frozen prefill export for prefill, frozen decode for decode + try launchFrozen(if (op.kind == .prefill) r.frozen_prefill_fn else r.frozen_decode_fn, r.stream, frozen); + try r.sync(); + const oy = try r.download(m.y_old.ptr, op.rows * rb, r.scratch2); + rec.old_y_sha = sha256Hex(oy); + if (pass == 0) try old_ys[op.layer].appendSlice(r.gpa, oy); + const os = try r.download(lm.old.ptr, g.stateBytes(), r.scratch2); + rec.old_state_sha = sha256Hex(os); + if (pass == 0 and (c.save_old_states or c.last_op[op.layer] == oi)) { + const name = try std.fmt.bufPrint(&path_buffer, "{s}/op-{d:0>4}.old.state.f32", .{ c.name, oi }); + try r.out.writeFile(r.io, .{ .sub_path = name, .data = os, .flags = .{ .exclusive = true } }); + } + + rec.inputs_unchanged = try r.checkInputs(g, m, op); + rec.layer_guards_changed = try r.checkLayerGuards(m); + var prefix_buffer: [192]u8 = undefined; + const prefix = try std.fmt.bufPrint(&prefix_buffer, "{s} pass {d} op {d} ({s} layer {d} rows {d})", .{ c.name, pass, oi, @tagName(op.kind), op.layer, op.rows }); + if (!rec.inputs_unchanged) try r.errors.add("{s}: inputs changed", .{prefix}); + if (rec.y_unwritten != 0 or rec.y_nonfinite != 0) try r.errors.add("{s}: output rows unwritten {d}, nonfinite {d}", .{ prefix, rec.y_unwritten, rec.y_nonfinite }); + if (rec.y_guard_before_changed != 0 or rec.y_guard_after_changed != 0) try r.errors.add("{s}: output overrun: {d} bytes before, {d} bytes after the rows changed", .{ prefix, rec.y_guard_before_changed, rec.y_guard_after_changed }); + if (rec.state_nonfinite != 0) try r.errors.add("{s}: {d} nonfinite state values", .{ prefix, rec.state_nonfinite }); + if (rec.ws_front_guard_changed != 0 or rec.ws_tail_changed != 0) try r.errors.add("{s}: workspace wrote outside its layout ({d} front-guard bytes, {d} bytes past layout {d})", .{ prefix, rec.ws_front_guard_changed, rec.ws_tail_changed, ws_bytes }); + if (rec.layer_guards_changed != 0) try r.errors.add("{s}: {d} bank/cache guard bytes changed", .{ prefix, rec.layer_guards_changed }); + if (rec.pending_after >= chunk) try r.errors.add("{s} pass {d} op {d}: pending {d} is not below {d}", .{ c.name, pass, oi, rec.pending_after, chunk }); + } + } + + fn probe(r: *Runner, c: Case, g: Geometry, ws: gdn.Workspace, ws_base: u64, ws_bytes: usize, op: Op, oi: usize, rec: *OpRecord, pass: usize, path_buffer: *[256]u8) !void { + if (comptime !probe_available) { + if (pass == 0) try r.errors.add("{s} op {d}: gate probe requested but gdn.Workspace has no u64 fields g, gc and beta", .{ c.name, oi }); + return; + } else { + const bytes = op.rows * g.nv * 4; + rec.probe_in_layout = true; + inline for (probe_fields, 0..) |name, fi| { + const ptr: u64 = @field(ws, name); + if (ptr < ws_base or ptr + bytes > ws_base + ws_bytes) { + rec.probe_in_layout = false; + try r.errors.add("{s} op {d}: Workspace.{s} [{d} rows][{d}] f32 is not inside the placed layout", .{ c.name, oi, name, op.rows, g.nv }); + } else { + const got = try r.download(ptr, bytes, r.scratch2); + rec.probe_sha[fi] = sha256Hex(got); + rec.probe_nonfinite[fi] = nonfiniteF32(got); + if (pass == 0) { + const file = try std.fmt.bufPrint(path_buffer, "{s}/op-{d:0>4}.ws-{s}.f32", .{ c.name, oi, name }); + try r.out.writeFile(r.io, .{ .sub_path = file, .data = got, .flags = .{ .exclusive = true } }); + } + } + } + } + } +}; + +// --------------------------------------------------------------------------------------------------------------- diff --git a/zig/tests/cuda/drama_qk_tests.zig b/zig/tests/cuda/drama_qk_tests.zig new file mode 100644 index 00000000000..67b66016917 --- /dev/null +++ b/zig/tests/cuda/drama_qk_tests.zig @@ -0,0 +1,134 @@ +//! Gemma Q/K norm and interleaved RoPE on synthetic operands, against FlashInfer and SGLang BF16 goldens. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); + +const rows = 7; +const qheads = 16; +const kheads = 2; +const dim = 256; +const qw = qheads * dim; +const kw = kheads * dim; +const qkv = 2 * qw + 2 * kw; +const start = 181; +const context = 192; +const guard = 32; +const sentinel: u16 = 0x7fc1; +const Expected = struct { index: usize, bits: u16 }; +const expected_q = [_]Expected{ + .{ .index = 0, .bits = 0xbcc7 }, + .{ .index = 1, .bits = 0x3b2c }, + .{ .index = 63, .bits = 0xbc8a }, + .{ .index = 64, .bits = 0xbc0b }, + .{ .index = 255, .bits = 0x3d4b }, + .{ .index = 256, .bits = 0xbedf }, + .{ .index = 4095, .bits = 0x3b19 }, + .{ .index = 24576, .bits = 0xbce2 }, + .{ .index = 24577, .bits = 0xbc52 }, + .{ .index = 24639, .bits = 0xbcab }, + .{ .index = 24640, .bits = 0xbc41 }, + .{ .index = 24831, .bits = 0x3cfa }, + .{ .index = 24832, .bits = 0x3f05 }, + .{ .index = 28671, .bits = 0x0000 }, +}; +// Indices 1065 and 2055 separate unrounded arithmetic from the reference's rounding. +const expected_k = [_]Expected{ + .{ .index = 0, .bits = 0x3c99 }, + .{ .index = 1, .bits = 0x3c67 }, + .{ .index = 63, .bits = 0x3a7e }, + .{ .index = 64, .bits = 0x3d41 }, + .{ .index = 255, .bits = 0xbe93 }, + .{ .index = 256, .bits = 0xbec1 }, + .{ .index = 511, .bits = 0xbc4d }, + .{ .index = 1065, .bits = 0x3fde }, + .{ .index = 2055, .bits = 0x3a3b }, + .{ .index = 3072, .bits = 0xbbb4 }, + .{ .index = 3073, .bits = 0x3c87 }, + .{ .index = 3135, .bits = 0xbc35 }, + .{ .index = 3136, .bits = 0x3c89 }, + .{ .index = 3327, .bits = 0xbeb9 }, + .{ .index = 3328, .bits = 0xbf3d }, + .{ .index = 3583, .bits = 0x3c2b }, +}; + +fn bf16Exact(value: f32) u16 { + return @truncate(@as(u32, @bitCast(value)) >> 16); +} + +fn runCase(gpu: check.Gpu, stream: cuda.Stream, kernel: cuda.Function, chunk: usize) !void { + var x: [rows * qkv]u16 = undefined; + var weights: [2][dim]u16 = undefined; + const scale = [_]f32{ 0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16 }; + // Integer mantissas and powers of two make all operands exactly BF16-representable, without a host rounding oracle. + for (&x, 0..) |*value, i| { + const mantissa: i32 = @intCast((37 * i + 11) % 257); + value.* = bf16Exact(@as(f32, @floatFromInt(mantissa - 128)) / 16 * scale[i % scale.len]); + } + for (0..dim) |i| { + const q: i32 = @intCast((5 * i + 3) % 17); + const k: i32 = @intCast((7 * i + 1) % 19); + weights[0][i] = bf16Exact(@as(f32, @floatFromInt(q - 8)) / 16); + weights[1][i] = bf16Exact(@as(f32, @floatFromInt(k - 9)) / 32); + } + var queries: [guard + rows * qw + guard]u16 = @splat(sentinel); + var keys: [guard + context * kw + guard]u16 = @splat(sentinel); + var values: @TypeOf(keys) = @splat(sentinel); + var dx = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&x)); + defer dx.free(); + var dw = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&weights)); + defer dw.free(); + var dq = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&queries)); + defer dq.free(); + var dk = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&keys)); + defer dk.free(); + var dv = try cuda.DeviceBuffer.fromHost(gpu.d, std.mem.asBytes(&values)); + defer dv.free(); + try gpu.ctx.synchronize(); + var at: usize = 0; + while (at < rows) { + const count = @min(chunk, rows - at); + var args: cuda.Args = .{}; + args.add(dx.ptr + at * qkv * 2); + args.add(dw.ptr); + args.add(dw.ptr + dim * 2); + args.add(dq.ptr + (guard + at * qw) * 2); + args.add(dk.ptr + guard * 2); + args.add(dv.ptr + guard * 2); + args.add(@as(i32, @intCast(start + at))); + args.add(@as(i32, qheads)); + args.add(@as(i32, kheads)); + args.add(@as(i32, dim)); + args.add(@as(i32, 64)); + args.add(@as(f32, 10000000)); + args.add(@as(f32, 1e-6)); + try cuda.launch.launch(kernel, .{ .grid = .{ .x = @intCast(count * (qheads + kheads)) }, .block = .{ .x = 256 } }, stream, &args); + at += count; + } + try stream.synchronize(); + try dq.download(0, std.mem.asBytes(&queries)); + try dk.download(0, std.mem.asBytes(&keys)); + try dv.download(0, std.mem.asBytes(&values)); + for (expected_q) |e| try check.expect(queries[guard + e.index] == e.bits, "Drama query index {d}, chunk {d}: {x} != {x}", .{ e.index, chunk, queries[guard + e.index], e.bits }); + for (expected_k) |e| try check.expect(keys[guard + start * kw + e.index] == e.bits, "Drama key index {d}, chunk {d}: {x} != {x}", .{ e.index, chunk, keys[guard + start * kw + e.index], e.bits }); + for (0..guard) |i| try check.expect(queries[i] == sentinel and queries[guard + rows * qw + i] == sentinel, "Drama query guard {d}, chunk {d}", .{ i, chunk }); + for (keys, values, 0..) |key, value, i| { + if (i < guard + start * kw or i >= guard + (start + rows) * kw) + try check.expect(key == sentinel and value == sentinel, "Drama KV cache outside append range at {d}, chunk {d}", .{ i, chunk }); + } + var x_after: @TypeOf(x) = undefined; + var weights_after: @TypeOf(weights) = undefined; + try dx.download(0, std.mem.asBytes(&x_after)); + try dw.download(0, std.mem.asBytes(&weights_after)); + try check.sameBytes("Drama QKV input unchanged", std.mem.asBytes(&x_after), std.mem.asBytes(&x)); + try check.sameBytes("Drama Q/K gamma unchanged", std.mem.asBytes(&weights_after), std.mem.asBytes(&weights)); +} + +pub fn run(gpu: check.Gpu) !void { + var module = try cuda.Module.load(gpu.d, cuda.kernels.drama_tower); + defer module.unload(); + var stream = try cuda.Stream.init(gpu.d, true); + defer stream.deinit(); + const kernel = try module.function("drama_rope_cache"); + for ([_]usize{ 1, 3, 7 }) |chunk| try runCase(gpu, stream, kernel, chunk); + check.pass("Drama Q/K: reference-rounded norm and RoPE, positions 181..187, chunks 1/3/7, cache bounds", .{}); +} diff --git a/zig/tests/cuda/drama_semantic_fixture.zig b/zig/tests/cuda/drama_semantic_fixture.zig new file mode 100644 index 00000000000..d8f2019411b --- /dev/null +++ b/zig/tests/cuda/drama_semantic_fixture.zig @@ -0,0 +1,113 @@ +//! Captures paired backbone hidden states and sampled frames in drama_host.zig's order, 128 frames, no codec. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const Frame = drama.tower.Frame; +const width = 2048; +const rows = 128; +const context = 512; + +fn plainFrame(token: u32) Frame { + var frame: Frame = @splat(0); + frame[0] = token; + return frame; +} + +fn lastRow(buffer: cuda.DeviceBuffer, count: usize, row_bytes: usize) !cuda.DeviceBuffer { + if (count == 0 or buffer.len != count * row_bytes) return error.DramaRowsMismatch; + return .{ .d = buffer.d, .ptr = buffer.ptr + (count - 1) * row_bytes, .len = row_bytes, .borrowed = true }; +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-semantic-fixture CHECKPOINT TOKENS_U32LE OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var bytes: [(context - rows) * 4 + 1]u8 align(@alignOf(u32)) = undefined; + const file = try std.Io.Dir.cwd().openFile(init.io, args[2], .{}); + defer file.close(init.io); + const size = try file.readPositionalAll(init.io, &bytes, 0); + if (size < 8 or size > (context - rows) * 4 or size % 4 != 0) return error.ExpectedTwoTo384Tokens; + const tokens = std.mem.bytesAsSlice(u32, @as([]align(@alignOf(u32)) u8, bytes[0..size])); + for (tokens) |token| if (token >= drama.backbone.config.vocab) return error.InvalidPromptToken; + var out = try std.Io.Dir.cwd().openDir(init.io, args[3], .{}); + defer out.close(init.io); + const hidden_capture = try init.gpa.alloc(u16, rows * width); + defer init.gpa.free(hidden_capture); + var captured_frames: [rows + 1]Frame = undefined; + var staged: [rows + 1]Frame = undefined; + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var backbone = try drama.backbone.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .context = context, .max_rows = rows }); + defer backbone.deinit(); + var tower = try drama.tower.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .context = context, .max_rows = rows }); + defer tower.deinit(); + if (backbone.hidden != width) return error.DramaHiddenMismatch; + for (tokens) |token| if (token >= backbone.semantic_start and token <= backbone.semantic_end) return error.TextFixtureMustNotContainSemanticTokens; + try backbone.reset(stream); + try tower.reset(stream, tokens, 0); + + var last: drama.backbone.Rows = undefined; + var start: usize = 0; + while (start < tokens.len) { + const end = @min(start + rows, tokens.len); + const n = end - start; + const look = @min(end + 1, tokens.len); + for (tokens[start..look], staged[0 .. look - start]) |token, *frame| frame.* = plainFrame(token); + const extra = try tower.setInput(stream, staged[0..n]); + last = try backbone.run(stream, .prefill, tokens[start..end], extra); + if (last.rows != n) return error.DramaRowsMismatch; + const taught = look - start - 1; + if (taught > 0) try tower.prefill(stream, last.hidden, staged[1 .. 1 + taught]); + if (end == tokens.len and taught > 0) _ = try tower.setInput(stream, staged[n - 1 .. n]); + start = end; + } + + // Row 0 is the final prompt row; frame i + 1 is the label of hidden row i. + captured_frames[0] = plainFrame(tokens[tokens.len - 1]); + var hidden = try lastRow(last.hidden, last.rows, width * 2); + var logits = try lastRow(last.semantic_logits, 1, drama.backbone.weights.head_cols * 4); + const sampling: drama.tower.Sampling = .{ .temperature = 1, .top_p = 0.9, .top_k = 30 }; + for (0..rows) |i| { + try stream.synchronize(); + try hidden.download(0, std.mem.sliceAsBytes(hidden_capture[i * width .. (i + 1) * width])); + const frame = try tower.generate(stream, logits, hidden, sampling); + if (frame[0] == backbone.eos) { + std.debug.print("early_eos generated_frames={d}; no padded fixture is written\n", .{i}); + return error.InsufficientGeneratedFrames; + } + if (frame[0] < backbone.semantic_start or frame[0] > backbone.semantic_end) return error.BadSpeechFrame; + if (frame[0] - backbone.semantic_start != frame[1]) return error.SemanticCodeMismatch; + for (frame[1..]) |code| if (code >= 4096) return error.InvalidCodebookIndex; + captured_frames[i + 1] = frame; + if (i + 1 < rows) { + staged[0] = frame; + const extra = try tower.setInput(stream, staged[0..1]); + const decoded = try backbone.run(stream, .decode, staged[0][0..1], extra); + if (decoded.rows != 1) return error.DramaRowsMismatch; + hidden = try lastRow(decoded.hidden, 1, width * 2); + logits = try lastRow(decoded.semantic_logits, 1, drama.backbone.weights.head_cols * 4); + } + } + for (hidden_capture) |bits| { + const value: f32 = @bitCast(@as(u32, bits) << 16); + if (!std.math.isFinite(value)) return error.NonFiniteBackboneHidden; + } + try out.writeFile(init.io, .{ .sub_path = "hidden.bf16", .data = std.mem.sliceAsBytes(hidden_capture) }); + try out.writeFile(init.io, .{ .sub_path = "frames.u32le", .data = std.mem.sliceAsBytes(&captured_frames) }); + const used = cuda.usage(false); + var metadata: [1024]u8 = undefined; + const text = try std.fmt.bufPrint(&metadata, "{{\"prompt_rows\":{d},\"hidden_rows\":{d},\"frame_rows\":{d},\"hidden_width\":{d},\"context\":{d},\"first_position\":{d},\"semantic_start\":{d},\"semantic_end\":{d},\"seed\":0,\"temperature\":1,\"top_p\":0.9,\"top_k\":30,\"stopped_at_fixture_bound\":true,\"codec_loaded\":false,\"cuda_bytes\":{d},\"pinned_bytes\":{d},\"scope\":\"Native-generated fixed-input suffix; independent tower replay rebases positions and omits earlier prompt KV. Not reference generation or complete speech.\"}}\n", .{ tokens.len, rows, rows + 1, width, context, tokens.len - 1, backbone.semantic_start, backbone.semantic_end, used.device, used.host }); + try out.writeFile(init.io, .{ .sub_path = "capture.json", .data = text }); + std.debug.print("{s}", .{text}); + return 0; +} diff --git a/zig/tests/cuda/drama_tower_context_capture.zig b/zig/tests/cuda/drama_tower_context_capture.zig new file mode 100644 index 00000000000..bc8c341a79d --- /dev/null +++ b/zig/tests/cuda/drama_tower_context_capture.zig @@ -0,0 +1,112 @@ +//! tf-drama-tower-context-trace's tracer and the per-schedule store of every stage capture, with their checks. +const std = @import("std"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const Allocator = std.mem.Allocator; +const tower = drama.tower; +const Stage = tower.Stage; +const context_trace = @import("drama_tower_context_trace.zig"); +const total_rows = context_trace.total_rows; +const layer_count = context_trace.layer_count; +const stages = context_trace.stages; +const stage_count = context_trace.stage_count; +const per_layer = context_trace.per_layer; +const captures_per_call = context_trace.captures_per_call; +const Errors = context_trace.Errors; +const differences = context_trace.differences; + +/// Every stage of one schedule at request positions 0..187; coverage counts how often each row was written. +pub const Store = struct { + data: [layer_count][stage_count][]u16, + coverage: [layer_count][stage_count][]u8, + + pub fn alloc(arena: Allocator) !Store { + var s: Store = undefined; + for (0..layer_count) |layer| for (stages, 0..) |stage, k| { + const count: usize = if (stage == .shared_input and layer != 0) 0 else total_rows; + s.data[layer][k] = try arena.alloc(u16, count * tower.stageWidth(stage)); + s.coverage[layer][k] = try arena.alloc(u8, count); + @memset(s.coverage[layer][k], 0); + }; + return s; + } + + pub fn rows(s: *const Store, layer: usize, k: usize, row0: usize, n: usize) []u16 { + const w = tower.stageWidth(stages[k]); + return s.data[layer][k][row0 * w .. (row0 + n) * w]; + } + + pub fn captured(layer: usize, k: usize) bool { + return !(stages[k] == .shared_input and layer != 0); + } +}; + +pub const Tracer = struct { + store: *Store, + compare: bool, // false: record into store; true: count differences against it + staging: []align(16) u8, + call_row0: usize = 0, + call_rows: usize = 0, + calls: usize = 0, + expected: usize = 0, + out_of_order: usize = 0, + incomplete_calls: usize = 0, + bad_rows: usize = 0, + duplicate_rows: usize = 0, + compare_differences: usize = 0, + + pub fn begin(t: *Tracer, row0: usize, rows: usize) void { + t.call_row0 = row0; + t.call_rows = rows; + t.expected = 0; + } + + pub fn end(t: *Tracer) void { + if (t.expected != captures_per_call) t.incomplete_calls += 1; + t.calls += 1; + } + + pub fn capture(t: *Tracer, stream: cuda.Stream, layer: usize, stage: Stage, src: cuda.DeviceBuffer, row0: usize) !void { + const k = @backingInt(stage); + const index = if (stage == .shared_input) 0 else 1 + layer * per_layer + (k - 1); + if (index != t.expected or layer >= layer_count or (stage == .shared_input and layer != 0)) t.out_of_order += 1; + t.expected = index + 1; + if (layer >= layer_count or !Store.captured(layer, k)) return; + const bytes_len = t.call_rows * tower.stageWidth(stage) * 2; + if (row0 != t.call_row0 or src.len != bytes_len or row0 + t.call_rows > total_rows) { + t.bad_rows += 1; + return; + } + if (bytes_len > t.staging.len) return error.TraceCaptureShape; + try src.downloadAsync(0, t.staging[0..bytes_len], stream.handle); + try stream.synchronize(); + const dst = t.store.rows(layer, k, row0, t.call_rows); + if (t.compare) { + t.compare_differences += differences(dst, std.mem.bytesAsSlice(u16, t.staging[0..bytes_len])); + } else { + @memcpy(std.mem.sliceAsBytes(dst), t.staging[0..bytes_len]); + for (t.store.coverage[layer][k][row0 .. row0 + t.call_rows]) |*c| { + if (c.* != 0) t.duplicate_rows += 1; + c.* +|= 1; + } + } + } +}; + +pub fn checkTracer(t: *const Tracer, label: []const u8, expected_calls: usize, errors: *Errors) !void { + if (t.calls != expected_calls or t.out_of_order != 0 or t.incomplete_calls != 0 or t.bad_rows != 0 or t.duplicate_rows != 0) + try errors.add("{s}: calls {d} (expected {d}), out of order {d}, incomplete calls {d}, bad rows {d}, duplicate rows {d}", .{ + label, t.calls, expected_calls, t.out_of_order, t.incomplete_calls, t.bad_rows, t.duplicate_rows, + }); + if (t.compare_differences != 0) try errors.add("{s}: {d} captured values differ from the first traced run", .{ label, t.compare_differences }); +} + +pub fn uncovered(store: *const Store) usize { + var count: usize = 0; + for (0..layer_count) |layer| for (0..stage_count) |k| { + for (store.coverage[layer][k]) |c| { + if (c != 1) count += 1; + } + }; + return count; +} diff --git a/zig/tests/cuda/drama_tower_context_oracle.zig b/zig/tests/cuda/drama_tower_context_oracle.zig new file mode 100644 index 00000000000..2286978fb6d --- /dev/null +++ b/zig/tests/cuda/drama_tower_context_oracle.zig @@ -0,0 +1,425 @@ +//! Diagnostic: the production tower teacher-forced over a prompt prefix, then a suffix, at absolute positions. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const tower = drama.tower; +const Frame = tower.Frame; +const Impl = @typeInfo(@FieldType(tower.Model, "impl")).pointer.child; + +const width = 2048; +const kv_width = 512; +const vocab = 4096; +const max_rows = 128; +const context = 512; +const prefix_rows = 181; +const suffix_rows = 128; +const hidden_rows = prefix_rows + suffix_rows; +const frame_rows = hidden_rows + 1; +const prefix_chunks = [_]usize{ 128, 53 }; // the production host's teacher-forced prompt chunks +const row_counts = [_]usize{ 1, 7, suffix_rows }; +const projection_count = 6; // tower.zig `projections.len` +const head_kind = 5; // tower.zig `projections[5]` = { 4096, hidden } +const head_index = 8; // codebook 9: audio_decoder_mtp.heads.8 +const head_plan = (1 - 1) * projection_count + head_kind; // rows = 1, as generate() and tf-drama-tower-oracle +const layer_count = @typeInfo(@FieldType(Impl, "layers")).array.len; + +const Mode = enum { batch, repeat, streaming, rebased }; +const modes = std.meta.tags(Mode); + +comptime { + std.debug.assert(layer_count == 13); + var sum: usize = 0; + for (prefix_chunks) |c| sum += c; + std.debug.assert(sum == prefix_rows); + std.debug.assert(hidden_rows <= context); + for (prefix_chunks) |c| std.debug.assert(c <= max_rows); +} + +/// Recorded failures that leave the files written but the evidence invalid. Messages hold no quote or backslash. +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +/// One schedule's outputs, sized for the largest suffix; a case uses the first n rows. +const Run = struct { + hidden: []u16, // [max_rows][width] suffix final hidden + head: []u16, // [vocab] + kv: []u16, // [layer][keys, values][n][kv_width] suffix cache rows + prefix_hidden: []u16, // [prefix_rows][width] + prefix_kv: []u16, // [layer][keys, values][prefix_rows][kv_width] + + fn alloc(arena: Allocator) !Run { + return .{ + .hidden = try arena.alloc(u16, max_rows * width), + .head = try arena.alloc(u16, vocab), + .kv = try arena.alloc(u16, layer_count * 2 * max_rows * kv_width), + .prefix_hidden = try arena.alloc(u16, prefix_rows * width), + .prefix_kv = try arena.alloc(u16, layer_count * 2 * prefix_rows * kv_width), + }; + } + + fn kvRows(r: Run, n: usize, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * n * kv_width; + return r.kv[at .. at + n * kv_width]; + } + + fn prefixKvRows(r: Run, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * prefix_rows * kv_width; + return r.prefix_kv[at .. at + prefix_rows * kv_width]; + } +}; + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +/// tower.zig cache layout: per layer a keys block then a values block of `context` rows of kv_width BF16. +fn cacheOffset(layer: usize, which: usize, row: usize) usize { + return ((layer * 2 + which) * context + row) * kv_width * 2; +} + +/// The oracle's head: rows = 1 plan, heads[8], one output_hidden row, after a NaN fill so a no-op cannot pass. +fn head(p: *Impl, stream: cuda.Stream, row: usize, out: []u16) !void { + try p.head_logits.fill8(0xff, stream.handle); + try p.plans.items[head_plan].run(p.output_hidden.ptr + row * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(out)); +} + +/// One teacher-forced schedule (see the file comment); row r always uses frames[r] and labels frames[r + 1]. +fn runSchedule(model: *tower.Model, stream: cuda.Stream, dev: cuda.DeviceBuffer, frames: []const Frame, n: usize, mode: Mode, r: Run) !void { + const p = model.impl; + try model.reset(stream, &.{}, 0); + if (mode != .rebased) { + var row: usize = 0; + for (prefix_chunks) |c| { + _ = try model.setInput(stream, frames[row .. row + c]); + try model.prefill(stream, view(dev, row * width * 2, c * width * 2), frames[row + 1 .. row + c + 1]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(r.prefix_hidden[row * width .. (row + c) * width])); + row += c; + } + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, 0), std.mem.sliceAsBytes(r.prefixKvRows(layer, which))); + }; + } + const a = prefix_rows; // absolute fixture row of the first suffix row + switch (mode) { + .batch, .repeat, .rebased => { + _ = try model.setInput(stream, frames[a .. a + n]); + try model.prefill(stream, view(dev, a * width * 2, n * width * 2), frames[a + 1 .. a + n + 1]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(r.hidden[0 .. n * width])); + try head(p, stream, n - 1, r.head); + }, + .streaming => { + for (0..n) |i| { + _ = try model.setInput(stream, frames[a + i .. a + i + 1]); + try model.prefill(stream, view(dev, (a + i) * width * 2, width * 2), frames[a + i + 1 .. a + i + 2]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(r.hidden[i * width .. (i + 1) * width])); + } + try head(p, stream, 0, r.head); + }, + } + const position0: usize = if (mode == .rebased) 0 else prefix_rows; + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, position0), std.mem.sliceAsBytes(r.kvRows(n, layer, which))); + }; +} + +fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// Writes one BF16 array as a new file and appends `"key": {file, sha256, shape, nonfinite}` to json. +fn emit(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), key: []const u8, name: []const u8, data: []const u16, rows: usize, cols: usize, errors: *Errors) !usize { + const bytes = std.mem.sliceAsBytes(data); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + const bad = nonfiniteBf16(data); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "\"{s}\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}}}", .{ key, name, sha[0..], rows, cols, bad }); + return bytes.len; +} + +/// One schedule's suffix outputs as new files: native-N-MODE-{hidden,head9,layer-LL-keys,layer-LL-values}.bf16. +fn emitRun(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), n: usize, mode: Mode, r: Run, errors: *Errors) !usize { + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + try json.print(gpa, "\"{s}\": {{", .{@tagName(mode)}); + var name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-hidden.bf16", .{ n, @tagName(mode) }); + written += try emit(gpa, io, dir, json, "hidden", name, r.hidden[0 .. n * width], n, width, errors); + try json.appendSlice(gpa, ", "); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-head9.bf16", .{ n, @tagName(mode) }); + written += try emit(gpa, io, dir, json, "head9", name, r.head, 1, vocab, errors); + try json.appendSlice(gpa, ", \"kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-layer-{d:0>2}-{s}.bf16", .{ n, @tagName(mode), layer, kind }); + if (layer != 0 or which != 0) try json.appendSlice(gpa, ", "); + written += try emit(gpa, io, dir, json, key, name, r.kvRows(n, layer, which), n, kv_width, errors); + }; + try json.appendSlice(gpa, "}}"); + return written; +} + +const Diff = struct { hidden: usize, head9: usize, kv: usize, prefix_hidden: usize, prefix_kv: usize }; + +fn compareRuns(n: usize, a: Run, b: Run, prefixes: bool) Diff { + return .{ + .hidden = differences(a.hidden[0 .. n * width], b.hidden[0 .. n * width]), + .head9 = differences(a.head, b.head), + .kv = differences(a.kv[0 .. layer_count * 2 * n * kv_width], b.kv[0 .. layer_count * 2 * n * kv_width]), + .prefix_hidden = if (prefixes) differences(a.prefix_hidden, b.prefix_hidden) else 0, + .prefix_kv = if (prefixes) differences(a.prefix_kv, b.prefix_kv) else 0, + }; +} + +fn printDiff(json: *std.ArrayList(u8), gpa: Allocator, d: Diff) !void { + try json.print(gpa, "{{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}, \"prefix_hidden\": {d}, \"prefix_kv\": {d}}}", .{ d.hidden, d.head9, d.kv, d.prefix_hidden, d.prefix_kv }); +} + +fn seconds(ns: anytype) f64 { + return @as(f64, @floatFromInt(ns)) / 1e9; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-context-oracle CHECKPOINT FIXTURE_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const fixture = try std.Io.Dir.cwd().openDir(io, args[2], .{}); + defer fixture.close(io); + const out = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer out.close(io); + + // Every input is read before any CUDA call, so a missing or short fixture never touches the device. + const hidden = try arena.alloc(u16, hidden_rows * width); + var frames: [frame_rows]Frame = undefined; + try readExact(io, fixture, "hidden.bf16", std.mem.sliceAsBytes(hidden)); + try readExact(io, fixture, "frames.u32le", std.mem.sliceAsBytes(&frames)); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha = sha256Hex(std.mem.sliceAsBytes(&frames)); + for (hidden) |bits| if ((bits & 0x7f80) == 0x7f80) return error.NonfiniteFixtureHidden; + + var runs: [modes.len]Run = undefined; + for (&runs) |*r| r.* = try Run.alloc(arena); + const base_prefix_hidden = try arena.alloc(u16, prefix_rows * width); + const base_prefix_kv = try arena.alloc(u16, layer_count * 2 * prefix_rows * kv_width); + const device_check = try arena.alloc(u16, hidden_rows * width); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try tower.Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + const p = model.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2 or + p.cache.len != layer_count * 2 * context * kv_width * 2) return error.UnexpectedTowerLayout; + const model_usage = cuda.usage(false); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, hidden_rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + + var cases: std.ArrayList(u8) = .empty; + defer cases.deinit(gpa); + var prefix_json: std.ArrayList(u8) = .empty; + defer prefix_json.deinit(gpa); + var written: usize = 0; + var have_base_prefix = false; + for (row_counts, 0..) |n, case_index| { + var timing: [modes.len]f64 = undefined; + for (modes, 0..) |mode, i| { + // The repeat runs on a poisoned cache: any read of a row this request did not write turns into NaN. + if (mode == .repeat) { + try p.cache.fill8(0xff, stream.handle); + try stream.synchronize(); + } + const start = std.Io.Clock.awake.now(io).toNanoseconds(); + try runSchedule(&model, stream, device_hidden, &frames, n, mode, runs[i]); + timing[i] = seconds(std.Io.Clock.awake.now(io).toNanoseconds() - start); + } + const batch = runs[@backingInt(Mode.batch)]; + const repeat_diff = compareRuns(n, batch, runs[@backingInt(Mode.repeat)], true); + if (repeat_diff.hidden != 0 or repeat_diff.head9 != 0 or repeat_diff.kv != 0 or repeat_diff.prefix_hidden != 0 or repeat_diff.prefix_kv != 0) + try errors.add("rows {d}: batch vs poisoned-cache repeat bit differences hidden {d} head9 {d} kv {d} prefix_hidden {d} prefix_kv {d}", .{ + n, repeat_diff.hidden, repeat_diff.head9, repeat_diff.kv, repeat_diff.prefix_hidden, repeat_diff.prefix_kv, + }); + const streaming = runs[@backingInt(Mode.streaming)]; + const streaming_prefix = Diff{ .hidden = 0, .head9 = 0, .kv = 0, .prefix_hidden = differences(batch.prefix_hidden, streaming.prefix_hidden), .prefix_kv = differences(batch.prefix_kv, streaming.prefix_kv) }; + if (streaming_prefix.prefix_hidden != 0 or streaming_prefix.prefix_kv != 0) + try errors.add("rows {d}: streaming prefix differs from batch prefix hidden {d} kv {d}", .{ n, streaming_prefix.prefix_hidden, streaming_prefix.prefix_kv }); + if (!have_base_prefix) { + @memcpy(base_prefix_hidden, batch.prefix_hidden); + @memcpy(base_prefix_kv, batch.prefix_kv); + have_base_prefix = true; + var name_buffer: [96]u8 = undefined; + try prefix_json.appendSlice(gpa, "{"); + written += try emit(gpa, io, out, &prefix_json, "hidden", "native-prefix-hidden.bf16", base_prefix_hidden, prefix_rows, width, &errors); + try prefix_json.appendSlice(gpa, ", \"kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + const name = try std.fmt.bufPrint(&name_buffer, "native-prefix-layer-{d:0>2}-{s}.bf16", .{ layer, kind }); + if (layer != 0 or which != 0) try prefix_json.appendSlice(gpa, ", "); + written += try emit(gpa, io, out, &prefix_json, key, name, batch.prefixKvRows(layer, which), prefix_rows, kv_width, &errors); + }; + try prefix_json.appendSlice(gpa, "}}"); + } + const across_cases = .{ differences(base_prefix_hidden, batch.prefix_hidden), differences(base_prefix_kv, batch.prefix_kv) }; + if (across_cases[0] != 0 or across_cases[1] != 0) + try errors.add("rows {d}: batch prefix differs from the first case prefix hidden {d} kv {d}", .{ n, across_cases[0], across_cases[1] }); + + try cases.print(gpa, "{s}\n {{\"rows\": {d}, \"suffix_positions\": [{d}, {d}], \"head_row\": \"last suffix row\"," ++ + " \"timing_s\": {{\"batch\": {d:.6}, \"repeat\": {d:.6}, \"streaming\": {d:.6}, \"rebased\": {d:.6}}}," ++ + " \"prefix_differences_vs_first_case\": {{\"hidden\": {d}, \"kv\": {d}}}, \"batch_vs_repeat_bit_differences\": ", .{ + if (case_index == 0) "" else ",", n, prefix_rows, prefix_rows + n - 1, timing[0], timing[1], timing[2], timing[3], across_cases[0], across_cases[1], + }); + try printDiff(&cases, gpa, repeat_diff); + try cases.appendSlice(gpa, ", \"streaming_vs_batch_prefix_bit_differences\": "); + try printDiff(&cases, gpa, streaming_prefix); + try cases.appendSlice(gpa, ", \"files\": {"); + for (modes, 0..) |mode, i| { + if (i != 0) try cases.appendSlice(gpa, ", "); + written += try emitRun(gpa, io, out, &cases, n, mode, runs[i], &errors); + } + try cases.appendSlice(gpa, "}}"); + std.debug.print("suffix_rows={d} repeat_hidden_diff={d} repeat_kv_diff={d} repeat_prefix_kv_diff={d} streaming_prefix_kv_diff={d}\n", .{ + n, repeat_diff.hidden, repeat_diff.kv, repeat_diff.prefix_kv, streaming_prefix.prefix_kv, + }); + } + + // Input immutability: the device rows every schedule read, and the host fixture bytes, are what was loaded. + try device_hidden.download(0, std.mem.sliceAsBytes(device_check)); + const device_input_differences = differences(device_check, hidden); + if (device_input_differences != 0) try errors.add("device input hidden changed in {d} values", .{device_input_differences}); + const host_hidden_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(hidden)), &hidden_sha); + const host_frames_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(&frames)), &frames_sha); + if (!host_hidden_unchanged or !host_frames_unchanged) try errors.add("host fixture changed: hidden unchanged {} frames unchanged {}", .{ host_hidden_unchanged, host_frames_unchanged }); + const used = cuda.usage(false); + + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const tower_source_sha = sha256Hex(tower.trace_source); + const driver_source_sha = sha256Hex(@embedFile("drama_tower_context_oracle.zig")); + const kernel_image_sha = sha256Hex(cuda.kernels.drama_tower); + if (cuda.kernels.drama_tower.len == 0) try errors.add("embedded drama_tower kernel image is empty", .{}); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-context-oracle\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"fixture_directory\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"input_hidden_sha256\": \"{s}\",\n \"input_frames_sha256\": \"{s}\",\n \"width\": {d},\n \"dtype\": \"bf16le\",\n \"layer_count\": {d}," ++ + "\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"prefix_rows\": {d},\n \"prefix_chunks\": [{d}, {d}],\n \"suffix_rows\": [{d}, {d}, {d}]," ++ + "\n \"schedules\": [\"batch\", \"repeat\", \"streaming\", \"rebased\"]," ++ + "\n \"row_mapping\": \"fixture row r is request position r (rebased: suffix row j at position j); input frame frames[r], next-frame label frames[r+1]; suffix KV rows are cache positions 181.. (rebased 0..)\"," ++ + "\n \"repeat_control\": \"KV cache filled with 0xFF before the repeat schedule; reset does not clear it\"," ++ + "\n \"head\": {{\"weight\": \"audio_decoder_mtp.heads.{d}.weight\", \"plan\": \"plans[{d}] (rows 1, kind {d})\", \"input\": \"last suffix row of output_hidden\"}}," ++ + "\n \"prefix\": {s},\n \"cases\": [{s}\n ]," ++ + "\n \"input_immutable\": {{\"device_hidden_differences\": {d}, \"host_hidden_unchanged\": {}, \"host_frames_unchanged\": {}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}}}," ++ + "\n \"bytes_written\": {d}," ++ + "\n \"binary_sha256\": {s},\n \"tower_source_sha256\": \"{s}\",\n \"driver_source_sha256\": \"{s}\",\n \"tower_kernel_image_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + hidden_sha[0..], frames_sha[0..], width, layer_count, + context, max_rows, prefix_rows, prefix_chunks[0], + prefix_chunks[1], row_counts[0], row_counts[1], row_counts[2], + head_index, head_plan, head_kind, prefix_json.items, + cases.items, device_input_differences, host_hidden_unchanged, host_frames_unchanged, + model_usage.device, used.device, used.peak, used.host, + written, binary_json.items, tower_source_sha[0..], driver_source_sha[0..], + kernel_image_sha[0..], evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("cases={d} bytes_written={d} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d} pinned_bytes={d}\n", .{ + row_counts.len, written + manifest.items.len, evidence_valid, errors.count, used.device, used.peak, used.host, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_tower_context_trace.zig b/zig/tests/cuda/drama_tower_context_trace.zig new file mode 100644 index 00000000000..653e472e086 --- /dev/null +++ b/zig/tests/cuda/drama_tower_context_trace.zig @@ -0,0 +1,514 @@ +//! Diagnostic: every tower stage along the full-context trajectory of a seven-row suffix, batch and streaming. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const Sha256 = std.crypto.hash.sha2.Sha256; +const tower = drama.tower; +const Stage = tower.Stage; +const Frame = tower.Frame; +const context_capture = @import("drama_tower_context_capture.zig"); +const Store = context_capture.Store; +const Tracer = context_capture.Tracer; +const checkTracer = context_capture.checkTracer; +const uncovered = context_capture.uncovered; +const Impl = @typeInfo(@FieldType(tower.Model, "impl")).pointer.child; +const LayerWeights = @typeInfo(@FieldType(Impl, "layers")).array.child; + +const width = 2048; +const kv_width = 512; +const vocab = 4096; +const max_rows = 128; +const context = 512; +const prefix_rows = 181; +const suffix = 7; +pub const total_rows = prefix_rows + suffix; +const fixture_hidden_rows = 309; +const fixture_frame_rows = fixture_hidden_rows + 1; +const prefix_chunks = [_]usize{ 128, 53 }; +const projection_count = 6; // tower.zig `projections.len` +const head_kind = 5; // tower.zig `projections[5]` = { 4096, hidden } +const head_index = 8; // codebook 9: audio_decoder_mtp.heads.8 +const head_plan = (1 - 1) * projection_count + head_kind; +pub const layer_count = @typeInfo(@FieldType(Impl, "layers")).array.len; +pub const stages = std.meta.tags(Stage); +pub const stage_count = stages.len; +pub const per_layer = stage_count - 1; // every stage except shared_input, once per layer +pub const captures_per_call = 1 + layer_count * per_layer; +const max_stage_width = 12288; // gate_up + +const Schedule = enum { batch, streaming }; +const schedules = std.meta.tags(Schedule); + +comptime { + std.debug.assert(layer_count == 13); + std.debug.assert(stages[0] == .shared_input and stage_count == 16); + for (stages) |s| std.debug.assert(tower.stageWidth(s) <= max_stage_width); + var sum: usize = 0; + for (prefix_chunks) |c| sum += c; + std.debug.assert(sum == prefix_rows and total_rows <= fixture_hidden_rows and total_rows <= context); +} + +pub const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + pub fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +const Finals = struct { + hidden: []u16, // [suffix][width] + head: []u16, // [vocab] + kv: []u16, // [layer][keys, values][suffix][kv_width] + prefix_hidden: []u16, // [prefix_rows][width] + prefix_kv: []u16, // [layer][keys, values][prefix_rows][kv_width] + + fn alloc(arena: Allocator) !Finals { + return .{ .hidden = try arena.alloc(u16, suffix * width), .head = try arena.alloc(u16, vocab), .kv = try arena.alloc(u16, layer_count * 2 * suffix * kv_width), .prefix_hidden = try arena.alloc(u16, prefix_rows * width), .prefix_kv = try arena.alloc(u16, layer_count * 2 * prefix_rows * kv_width) }; + } + + fn kvRows(f: Finals, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * suffix * kv_width; + return f.kv[at .. at + suffix * kv_width]; + } + + fn prefixKvRows(f: Finals, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * prefix_rows * kv_width; + return f.prefix_kv[at .. at + prefix_rows * kv_width]; + } +}; + +const Diff = struct { hidden: usize, head9: usize, kv: usize, prefix_hidden: usize, prefix_kv: usize }; + +fn compareFinals(a: Finals, b: Finals) Diff { + return .{ .hidden = differences(a.hidden, b.hidden), .head9 = differences(a.head, b.head), .kv = differences(a.kv, b.kv), .prefix_hidden = differences(a.prefix_hidden, b.prefix_hidden), .prefix_kv = differences(a.prefix_kv, b.prefix_kv) }; +} + +fn zero(d: Diff) bool { + return d.hidden == 0 and d.head9 == 0 and d.kv == 0 and d.prefix_hidden == 0 and d.prefix_kv == 0; +} + +fn printDiff(json: *std.ArrayList(u8), gpa: Allocator, d: Diff) !void { + try json.print(gpa, "{{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}, \"prefix_hidden\": {d}, \"prefix_kv\": {d}}}", .{ d.hidden, d.head9, d.kv, d.prefix_hidden, d.prefix_kv }); +} + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +/// tower.zig cache layout: per layer a keys block then a values block of `context` rows of kv_width BF16. +fn cacheOffset(layer: usize, which: usize, row: usize) usize { + return ((layer * 2 + which) * context + row) * kv_width * 2; +} + +/// tf-drama-tower-context-oracle's head: rows = 1 plan, heads[8], one output_hidden row, after a NaN fill. +fn head(p: *Impl, stream: cuda.Stream, row: usize, out: []u16) !void { + try p.head_logits.fill8(0xff, stream.handle); + try p.plans.items[head_plan].run(p.output_hidden.ptr + row * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(out)); +} + +/// One prefill of `rows` fixture rows from `row0` (positions row0..); traced when `trace` is a tracer pointer. +fn call(model: *tower.Model, stream: cuda.Stream, dev: cuda.DeviceBuffer, frames: []const Frame, row0: usize, rows: usize, trace: anytype) !void { + _ = try model.setInput(stream, frames[row0 .. row0 + rows]); + const hidden_rows = view(dev, row0 * width * 2, rows * width * 2); + const labels = frames[row0 + 1 .. row0 + rows + 1]; + if (@TypeOf(trace) == void) { + try model.prefill(stream, hidden_rows, labels); + } else { + trace.begin(row0, rows); + try model.prefillTraced(stream, hidden_rows, labels, trace); + trace.end(); + } +} + +fn runSchedule(model: *tower.Model, stream: cuda.Stream, dev: cuda.DeviceBuffer, frames: []const Frame, schedule: Schedule, trace: anytype, f: Finals) !void { + const p = model.impl; + try model.reset(stream, &.{}, 0); + var row: usize = 0; + for (prefix_chunks) |c| { + try call(model, stream, dev, frames, row, c, trace); + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.prefix_hidden[row * width .. (row + c) * width])); + row += c; + } + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, 0), std.mem.sliceAsBytes(f.prefixKvRows(layer, which))); + }; + switch (schedule) { + .batch => { + try call(model, stream, dev, frames, prefix_rows, suffix, trace); + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.hidden)); + try head(p, stream, suffix - 1, f.head); + }, + .streaming => { + for (0..suffix) |i| { + try call(model, stream, dev, frames, prefix_rows + i, 1, trace); + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.hidden[i * width .. (i + 1) * width])); + } + try head(p, stream, 0, f.head); + }, + } + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, prefix_rows), std.mem.sliceAsBytes(f.kvRows(layer, which))); + }; +} + +fn hashBuffer(hash: *Sha256, buffer: cuda.DeviceBuffer, host: []u8) !void { + var offset: usize = 0; + while (offset < buffer.len) { + const n = @min(host.len, buffer.len - offset); + try buffer.download(offset, host[0..n]); + hash.update(host[0..n]); + offset += n; + } +} + +/// SHA-256 over every device weight the tower reads: layers in field order, the nine heads, the embedding table. +fn weightDigest(p: *Impl, host: []u8) ![64]u8 { + var hash = Sha256.init(.{}); + for (p.layers) |layer_weights| { + inline for (@typeInfo(LayerWeights).@"struct".field_names) |name| try hashBuffer(&hash, @field(layer_weights, name), host); + } + for (p.heads) |h| try hashBuffer(&hash, h, host); + try hashBuffer(&hash, p.embeddings, host); + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +pub fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, path: []const u8, bytes: []u8) !void { + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// Writes one BF16 array as a new file and appends `"file": .., "sha256": .., "shape": [r, c], "nonfinite": n`. +fn emitFields(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), name: []const u8, data: []const u16, rows: usize, cols: usize, errors: *Errors) !usize { + const bytes = std.mem.sliceAsBytes(data); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + const bad = nonfiniteBf16(data); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}", .{ name, sha[0..], rows, cols, bad }); + return bytes.len; +} + +fn emitKeyed(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), key: []const u8, name: []const u8, data: []const u16, rows: usize, cols: usize, errors: *Errors) !usize { + try json.print(gpa, "\"{s}\": {{", .{key}); + const written = try emitFields(gpa, io, dir, json, name, data, rows, cols, errors); + try json.appendSlice(gpa, "}"); + return written; +} + +fn emitFinals(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), schedule: Schedule, f: Finals, errors: *Errors) !usize { + const s = @tagName(schedule); + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + try json.appendSlice(gpa, "{"); + written += try emitKeyed(gpa, io, dir, json, "hidden", try std.fmt.bufPrint(&name_buffer, "native-{s}-hidden.bf16", .{s}), f.hidden, suffix, width, errors); + try json.appendSlice(gpa, ", "); + written += try emitKeyed(gpa, io, dir, json, "head9", try std.fmt.bufPrint(&name_buffer, "native-{s}-head9.bf16", .{s}), f.head, 1, vocab, errors); + try json.appendSlice(gpa, ", "); + written += try emitKeyed(gpa, io, dir, json, "prefix_hidden", try std.fmt.bufPrint(&name_buffer, "native-{s}-prefix-hidden.bf16", .{s}), f.prefix_hidden, prefix_rows, width, errors); + try json.appendSlice(gpa, ", \"kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + if (layer != 0 or which != 0) try json.appendSlice(gpa, ", "); + written += try emitKeyed(gpa, io, dir, json, key, try std.fmt.bufPrint(&name_buffer, "native-{s}-layer-{d:0>2}-{s}.bf16", .{ s, layer, kind }), f.kvRows(layer, which), suffix, kv_width, errors); + }; + try json.appendSlice(gpa, "}, \"prefix_kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + if (layer != 0 or which != 0) try json.appendSlice(gpa, ", "); + written += try emitKeyed(gpa, io, dir, json, key, try std.fmt.bufPrint(&name_buffer, "native-{s}-prefix-layer-{d:0>2}-{s}.bf16", .{ s, layer, kind }), f.prefixKvRows(layer, which), prefix_rows, kv_width, errors); + }; + try json.appendSlice(gpa, "}}"); + return written; +} + +/// The stage files of one schedule: batch all 188 rows, streaming its 7 suffix rows. +fn emitStages(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), schedule: Schedule, store: *const Store, errors: *Errors) !usize { + const row0: usize = if (schedule == .batch) 0 else prefix_rows; + const n: usize = total_rows - row0; + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + var first = true; + try json.appendSlice(gpa, "["); + for (0..layer_count) |layer| for (stages, 0..) |stage, k| { + if (!Store.captured(layer, k)) continue; + try json.print(gpa, "{s}\n {{\"layer\": {d}, \"stage\": \"{s}\", \"row0\": {d}, ", .{ if (first) "" else ",", layer, @tagName(stage), row0 }); + first = false; + const name = try std.fmt.bufPrint(&name_buffer, "native-{s}-layer-{d:0>2}-{s}.bf16", .{ @tagName(schedule), layer, @tagName(stage) }); + written += try emitFields(gpa, io, dir, json, name, store.rows(layer, k, row0, n), n, tower.stageWidth(stage), errors); + try json.appendSlice(gpa, "}"); + }; + try json.appendSlice(gpa, "]"); + return written; +} + +/// Layer-12 output and every layer's key / value captures equal the exported hidden and KV rows. +fn consistency(store: *const Store, f: Finals) usize { + const output = @backingInt(Stage.output); + const key = @backingInt(Stage.key); + const value = @backingInt(Stage.value); + var count = differences(store.rows(layer_count - 1, output, 0, prefix_rows), f.prefix_hidden) + + differences(store.rows(layer_count - 1, output, prefix_rows, suffix), f.hidden); + for (0..layer_count) |layer| { + count += differences(store.rows(layer, key, 0, prefix_rows), f.prefixKvRows(layer, 0)); + count += differences(store.rows(layer, value, 0, prefix_rows), f.prefixKvRows(layer, 1)); + count += differences(store.rows(layer, key, prefix_rows, suffix), f.kvRows(layer, 0)); + count += differences(store.rows(layer, value, prefix_rows, suffix), f.kvRows(layer, 1)); + } + return count; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 5) { + std.debug.print("usage: tf-drama-tower-context-trace CHECKPOINT HIDDEN.bf16 FRAMES.u32le OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + + // Every input is read before any CUDA call. + const hidden = try arena.alloc(u16, fixture_hidden_rows * width); + var frames: [fixture_frame_rows]Frame = undefined; + try readExact(io, args[2], std.mem.sliceAsBytes(hidden)); + try readExact(io, args[3], std.mem.sliceAsBytes(&frames)); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha = sha256Hex(std.mem.sliceAsBytes(&frames)); + for (hidden) |bits| if ((bits & 0x7f80) == 0x7f80) return error.NonfiniteFixtureHidden; + + var stores: [schedules.len]Store = undefined; + for (&stores) |*store| store.* = try Store.alloc(arena); + var finals: [schedules.len][3]Finals = undefined; // traced, untraced, repeat + for (&finals) |*per| for (per) |*f| { + f.* = try Finals.alloc(arena); + }; + const device_check = try arena.alloc(u16, fixture_hidden_rows * width); + const host_chunk = try gpa.alloc(u8, 64 << 20); + defer gpa.free(host_chunk); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try tower.Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + const p = model.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2 or + p.cache.len != layer_count * 2 * context * kv_width * 2) return error.UnexpectedTowerLayout; + const model_usage = cuda.usage(false); + const weights_before = try weightDigest(p, host_chunk); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, fixture_hidden_rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + var staging = try cuda.HostBuffer.alloc(&driver, max_rows * max_stage_width * 2); + defer staging.free(); + + var schedule_json: std.ArrayList(u8) = .empty; + defer schedule_json.deinit(gpa); + var written: usize = 0; + for (schedules, 0..) |schedule, si| { + const label = @tagName(schedule); + const expected_calls = prefix_chunks.len + @as(usize, if (schedule == .batch) 1 else suffix); + var traced: Tracer = .{ .store = &stores[si], .compare = false, .staging = staging.bytes }; + try runSchedule(&model, stream, device_hidden, &frames, schedule, &traced, finals[si][0]); + try runSchedule(&model, stream, device_hidden, &frames, schedule, {}, finals[si][1]); + try p.cache.fill8(0xff, stream.handle); + try stream.synchronize(); + var again: Tracer = .{ .store = &stores[si], .compare = true, .staging = staging.bytes }; + try runSchedule(&model, stream, device_hidden, &frames, schedule, &again, finals[si][2]); + try checkTracer(&traced, label, expected_calls, &errors); + try checkTracer(&again, label, expected_calls, &errors); + const missing = uncovered(&stores[si]); + if (missing != 0) try errors.add("{s}: {d} stage rows not written exactly once", .{ label, missing }); + const untraced_diff = compareFinals(finals[si][0], finals[si][1]); + const repeat_diff = compareFinals(finals[si][0], finals[si][2]); + if (!zero(untraced_diff)) try errors.add("{s}: traced vs untraced finals differ hidden {d} head9 {d} kv {d} prefix_hidden {d} prefix_kv {d}", .{ label, untraced_diff.hidden, untraced_diff.head9, untraced_diff.kv, untraced_diff.prefix_hidden, untraced_diff.prefix_kv }); + if (!zero(repeat_diff)) try errors.add("{s}: traced vs poisoned repeat finals differ hidden {d} head9 {d} kv {d} prefix_hidden {d} prefix_kv {d}", .{ label, repeat_diff.hidden, repeat_diff.head9, repeat_diff.kv, repeat_diff.prefix_hidden, repeat_diff.prefix_kv }); + const inconsistent = consistency(&stores[si], finals[si][0]); + if (inconsistent != 0) try errors.add("{s}: {d} layer-12 output or key/value capture values differ from the exported hidden/KV", .{ label, inconsistent }); + + try schedule_json.print(gpa, "{s}\n \"{s}\": {{\"calls\": [", .{ if (si == 0) "" else ",", label }); + var row: usize = 0; + for (0..expected_calls) |c| { + const rows: usize = if (c < prefix_chunks.len) prefix_chunks[c] else if (schedule == .batch) suffix else 1; + try schedule_json.print(gpa, "{s}{{\"row0\": {d}, \"rows\": {d}}}", .{ if (c == 0) "" else ", ", row, rows }); + row += rows; + } + try schedule_json.print(gpa, "], \"trace\": {{\"calls\": {d}, \"captures_per_call\": {d}, \"out_of_order\": {d}, \"incomplete_calls\": {d}," ++ + " \"bad_rows\": {d}, \"duplicate_rows\": {d}, \"uncovered_rows\": {d}, \"repeat_capture_differences\": {d}, \"repeat_calls\": {d}," ++ + " \"repeat_out_of_order\": {d}}}, \"output_kv_capture_inconsistencies\": {d}, \"traced_vs_untraced\": ", .{ + traced.calls, captures_per_call, traced.out_of_order, traced.incomplete_calls, traced.bad_rows, traced.duplicate_rows, missing, + again.compare_differences, again.calls, again.out_of_order, inconsistent, + }); + try printDiff(&schedule_json, gpa, untraced_diff); + try schedule_json.appendSlice(gpa, ", \"traced_vs_repeat\": "); + try printDiff(&schedule_json, gpa, repeat_diff); + try schedule_json.appendSlice(gpa, ", \"finals\": "); + written += try emitFinals(gpa, io, out, &schedule_json, schedule, finals[si][0], &errors); + try schedule_json.appendSlice(gpa, ", \"stages\": "); + written += try emitStages(gpa, io, out, &schedule_json, schedule, &stores[si], &errors); + try schedule_json.appendSlice(gpa, "}"); + std.debug.print("{s}: calls={d} untraced_diff={d}/{d}/{d} repeat_capture_diff={d} uncovered={d}\n", .{ + label, traced.calls, untraced_diff.hidden, untraced_diff.head9, untraced_diff.kv, again.compare_differences, missing, + }); + } + + // The streaming prefix calls are the batch prefix calls: finals and every stage row must be identical. + const bi = @backingInt(Schedule.batch); + const st = @backingInt(Schedule.streaming); + const prefix_finals = .{ differences(finals[bi][0].prefix_hidden, finals[st][0].prefix_hidden), differences(finals[bi][0].prefix_kv, finals[st][0].prefix_kv) }; + var prefix_stage_differences: usize = 0; + for (0..layer_count) |layer| for (0..stage_count) |k| { + if (Store.captured(layer, k)) prefix_stage_differences += differences(stores[bi].rows(layer, k, 0, prefix_rows), stores[st].rows(layer, k, 0, prefix_rows)); + }; + if (prefix_finals[0] != 0 or prefix_finals[1] != 0 or prefix_stage_differences != 0) + try errors.add("streaming prefix differs from batch: hidden {d} kv {d} stage values {d}", .{ prefix_finals[0], prefix_finals[1], prefix_stage_differences }); + + try device_hidden.download(0, std.mem.sliceAsBytes(device_check)); + const device_input_differences = differences(device_check, hidden); + if (device_input_differences != 0) try errors.add("device input hidden changed in {d} values", .{device_input_differences}); + const host_hidden_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(hidden)), &hidden_sha); + const host_frames_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(&frames)), &frames_sha); + if (!host_hidden_unchanged or !host_frames_unchanged) try errors.add("host fixture changed: hidden unchanged {} frames unchanged {}", .{ host_hidden_unchanged, host_frames_unchanged }); + const weights_after = try weightDigest(p, host_chunk); + const weights_unchanged = std.mem.eql(u8, &weights_before, &weights_after); + if (!weights_unchanged) try errors.add("device weights changed during the run", .{}); + const used = cuda.usage(false); + + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const tower_source_sha = sha256Hex(tower.trace_source); + const driver_source_sha = sha256Hex(@embedFile("drama_tower_context_trace.zig")); + const kernel_image_sha = sha256Hex(cuda.kernels.drama_tower); + if (cuda.kernels.drama_tower.len == 0) try errors.add("embedded drama_tower kernel image is empty", .{}); + const evidence_valid = errors.count == 0; + + var stage_order: std.ArrayList(u8) = .empty; + defer stage_order.deinit(gpa); + for (stages, 0..) |stage, k| try stage_order.print(gpa, "{s}{{\"stage\": \"{s}\", \"width\": {d}}}", .{ if (k == 0) "" else ", ", @tagName(stage), tower.stageWidth(stage) }); + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-context-trace\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"hidden_path\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.appendSlice(gpa, ",\n \"frames_path\": "); + try jsonString(&manifest, gpa, args[3]); + try manifest.print(gpa, ",\n \"input_hidden_sha256\": \"{s}\",\n \"input_frames_sha256\": \"{s}\",\n \"width\": {d},\n \"dtype\": \"bf16le\",\n \"layer_count\": {d}," ++ + "\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"prefix_rows\": {d},\n \"prefix_chunks\": [{d}, {d}],\n \"suffix_rows\": {d},\n \"total_rows\": {d}," ++ + "\n \"stage_order\": [{s}],\n \"captures_per_call\": {d}," ++ + "\n \"row_mapping\": \"stage row r is request position r = fixture row r; input frame frames[r], next-frame label frames[r+1]; batch stage files hold rows 0..187, streaming stage files rows 181..187; shared_input is layer 0 only (the layer-0 mixer extra input)\"," ++ + "\n \"column_mapping\": \"qkv in checkpoint order [query 16x256 | gate 16x256 | key 2x256 | value 2x256]; key / value are the layer's cache rows of the call\"," ++ + "\n \"repeat_control\": \"KV cache filled with 0xFF before each traced repeat; its captures are compared with the first traced run\"," ++ + "\n \"head\": {{\"weight\": \"audio_decoder_mtp.heads.{d}.weight\", \"plan\": \"plans[{d}] (rows 1, kind {d})\", \"input\": \"last suffix row of output_hidden\"}}," ++ + "\n \"schedules\": {{{s}\n }},", .{ + hidden_sha[0..], frames_sha[0..], width, layer_count, + context, max_rows, prefix_rows, prefix_chunks[0], + prefix_chunks[1], suffix, total_rows, stage_order.items, + captures_per_call, head_index, head_plan, head_kind, + schedule_json.items, + }); + try manifest.print(gpa, "\n \"streaming_prefix_vs_batch\": {{\"prefix_hidden\": {d}, \"prefix_kv\": {d}, \"stage_values\": {d}}}," ++ + "\n \"input_immutable\": {{\"device_hidden_differences\": {d}, \"host_hidden_unchanged\": {}, \"host_frames_unchanged\": {}}}," ++ + "\n \"weights\": {{\"sha256_before\": \"{s}\", \"sha256_after\": \"{s}\", \"unchanged\": {}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}}}," ++ + "\n \"bytes_written\": {d}," ++ + "\n \"binary_sha256\": {s},\n \"tower_source_sha256\": \"{s}\",\n \"driver_source_sha256\": \"{s}\",\n \"tower_kernel_image_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + prefix_finals[0], prefix_finals[1], prefix_stage_differences, + device_input_differences, host_hidden_unchanged, host_frames_unchanged, + weights_before[0..], weights_after[0..], weights_unchanged, + model_usage.device, used.device, used.peak, + used.host, written, binary_json.items, + tower_source_sha[0..], driver_source_sha[0..], kernel_image_sha[0..], + evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("bytes_written={d} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d}\n", .{ + written + manifest.items.len, evidence_valid, errors.count, used.device, used.peak, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_tower_head_replay.zig b/zig/tests/cuda/drama_tower_head_replay.zig new file mode 100644 index 00000000000..9b7a7dba7db --- /dev/null +++ b/zig/tests/cuda/drama_tower_head_replay.zig @@ -0,0 +1,81 @@ +//! Diagnostic: generate()'s one-row codebook-9 head on identical inputs, through the production tower's plan. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const max_rows = 128; +const width = 2048; +const vocab = 4096; +const projection_count = 6; // tower.zig `projections.len` +const head_kind = 5; // tower.zig `projections[5]` = { 4096, hidden }, the codebook head shape +const head_index = 8; // codebook 9: audio_decoder_mtp.heads.8, the oracle's `p.heads[8]` +const head_rows = 1; // generate() and the oracle project one row through the head +const row_counts = [_]usize{ 1, 7, max_rows }; +const origins = [_][]const u8{ "native", "reference" }; + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-head-replay CHECKPOINT INPUT_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var input = try std.Io.Dir.cwd().openDir(init.io, args[2], .{}); + defer input.close(init.io); + var out = try std.Io.Dir.cwd().openDir(init.io, args[3], .{}); + defer out.close(init.io); + var total_rows: usize = 0; + for (row_counts) |n| total_rows += n * origins.len; + const rows = try init.gpa.alloc(u16, total_rows * width); + defer init.gpa.free(rows); + var inputs: [row_counts.len][origins.len][]u16 = undefined; + var name_buffer: [128]u8 = undefined; + // Every input is read before any CUDA call, so a missing or short fixture never touches the device. + var offset: usize = 0; + for (row_counts, 0..) |n, i| for (origins, 0..) |origin, j| { + inputs[i][j] = rows[offset .. offset + n * width]; + offset += n * width; + const name = try std.fmt.bufPrint(&name_buffer, "input-{d}-{s}.bf16", .{ n, origin }); + try readExact(init.io, input, name, std.mem.sliceAsBytes(inputs[i][j])); + }; + var logits: [vocab]u16 = undefined; + var repeated: [vocab]u16 = undefined; + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + // Same options as drama_tower_oracle.zig, so the plan list, weights and buffers are the ones it ran. + var tower = try drama.tower.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .context = max_rows, .max_rows = max_rows }); + defer tower.deinit(); + const p = tower.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2) + return error.UnexpectedTowerLayout; + const plan = &p.plans.items[(head_rows - 1) * projection_count + head_kind]; + for (row_counts, 0..) |n, i| for (origins, 0..) |origin, j| { + // Full N rows at offset 0 of the production buffer: the head reads row N - 1 at the oracle's address. + try p.output_hidden.upload(0, std.mem.sliceAsBytes(inputs[i][j])); + for ([_]*[vocab]u16{ &logits, &repeated }) |destination| { + // 0xffff is a BF16 NaN: a head that writes nothing cannot pass the CPU-side self-control. + try p.head_logits.fill8(0xff, stream.handle); + try plan.run(p.output_hidden.ptr + (n - 1) * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(destination)); + } + if (!std.mem.eql(u16, &logits, &repeated)) return error.HeadReplayNotReproducible; + const name = try std.fmt.bufPrint(&name_buffer, "native-op-{d}-{s}.bf16", .{ n, origin }); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(&logits) }); + std.debug.print("head_rows={d} input={s} last_row={d} repeat_bit_exact=true\n", .{ n, origin, n - 1 }); + }; + const used = cuda.usage(false); + std.debug.print("cuda_bytes={d} pinned_bytes={d}\n", .{ used.device, used.host }); + return 0; +} diff --git a/zig/tests/cuda/drama_tower_linear_replay.zig b/zig/tests/cuda/drama_tower_linear_replay.zig new file mode 100644 index 00000000000..c12f5c255d5 --- /dev/null +++ b/zig/tests/cuda/drama_tower_linear_replay.zig @@ -0,0 +1,327 @@ +//! Diagnostic: the production tower's layer-0 eh_proj cuBLASLt plans replayed on frozen inputs. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); + +const Allocator = std.mem.Allocator; +const Sha256 = std.crypto.hash.sha2.Sha256; +const lt_api = cuda.cublaslt; + +const n_out = 2048; // tower.zig projections[0] = { hidden, 2 * hidden }: out 2048 +const k_in = 4096; // in 4096 +const workspace_bytes = 8 << 20; // tower.zig `workspace_bytes` +const batch_rows = 188; +const streaming_rows = 7; +const plan_rows = [_]usize{ 1, 7, 53, 128 }; +const repeats = 3; + +const Cell = struct { label: []const u8, streaming: bool, row0: usize, m: usize }; +const cells = [_]Cell{ + .{ .label = "batch-call0", .streaming = false, .row0 = 0, .m = 128 }, + .{ .label = "batch-call1", .streaming = false, .row0 = 128, .m = 53 }, + .{ .label = "batch-call2", .streaming = false, .row0 = 181, .m = 7 }, + .{ .label = "streaming-row-181", .streaming = true, .row0 = 0, .m = 1 }, + .{ .label = "streaming-row-182", .streaming = true, .row0 = 1, .m = 1 }, + .{ .label = "streaming-row-183", .streaming = true, .row0 = 2, .m = 1 }, + .{ .label = "streaming-row-184", .streaming = true, .row0 = 3, .m = 1 }, + .{ .label = "streaming-row-185", .streaming = true, .row0 = 4, .m = 1 }, + .{ .label = "streaming-row-186", .streaming = true, .row0 = 5, .m = 1 }, + .{ .label = "streaming-row-187", .streaming = true, .row0 = 6, .m = 1 }, +}; +// cublasLtMatmulAlgoConfigAttributes_t (cublasLt.h): id, name, exact storage size in bytes. +const AlgoAttribute = struct { id: c_int, name: []const u8, size: usize }; +const algo_attributes = [_]AlgoAttribute{ + .{ .id = 0, .name = "algo_id", .size = 4 }, .{ .id = 1, .name = "tile_id", .size = 4 }, + .{ .id = 2, .name = "splitk_num", .size = 4 }, .{ .id = 3, .name = "reduction_scheme", .size = 4 }, + .{ .id = 4, .name = "cta_swizzling", .size = 4 }, .{ .id = 5, .name = "custom_option", .size = 4 }, + .{ .id = 6, .name = "stages_id", .size = 4 }, .{ .id = 7, .name = "inner_shape_id", .size = 2 }, + .{ .id = 8, .name = "cluster_shape_id", .size = 2 }, +}; +const AlgoConfigGetAttribute = *const fn (*const lt_api.Algo, c_int, *anyopaque, usize, *usize) callconv(.c) lt_api.Status; + +comptime { + for (cells) |c| std.debug.assert(c.row0 + c.m <= (if (c.streaming) streaming_rows else batch_rows)); +} + +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, path: []const u8, bytes: []u8) !void { + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadInputLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// The path of the mapped libcublasLt, from /proc/self/maps (after the library was opened). +fn mappedCublasLt(gpa: Allocator, io: std.Io, out: *std.ArrayList(u8)) !void { + const file = try std.Io.Dir.cwd().openFile(io, "/proc/self/maps", .{}); + defer file.close(io); + var buffer: [4096]u8 = undefined; + var reader = file.readerStreaming(io, &buffer); + const maps = try reader.interface.allocRemaining(gpa, .limited(1 << 24)); + defer gpa.free(maps); + var lines = std.mem.splitScalar(u8, maps, '\n'); + while (lines.next()) |line| { + if (std.mem.indexOf(u8, line, "libcublasLt.so") == null) continue; + const slash = std.mem.indexOfScalar(u8, line, '/') orelse continue; + try out.appendSlice(gpa, line[slash..]); + return; + } +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 5) { + std.debug.print("usage: tf-drama-tower-linear-replay WEIGHT.bf16 BATCH_JOINED.bf16 STREAMING_JOINED.bf16 OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const out = try std.Io.Dir.cwd().openDir(io, args[4], .{}); + defer out.close(io); + + // Every input is read before any CUDA call. + const weight = try arena.alloc(u16, n_out * k_in); + const batch = try arena.alloc(u16, batch_rows * k_in); + const streaming = try arena.alloc(u16, streaming_rows * k_in); + try readExact(io, args[1], std.mem.sliceAsBytes(weight)); + try readExact(io, args[2], std.mem.sliceAsBytes(batch)); + try readExact(io, args[3], std.mem.sliceAsBytes(streaming)); + const weight_sha = sha256Hex(std.mem.sliceAsBytes(weight)); + const batch_sha = sha256Hex(std.mem.sliceAsBytes(batch)); + const streaming_sha = sha256Hex(std.mem.sliceAsBytes(streaming)); + for ([_][]const u16{ weight, batch, streaming }) |values| if (nonfiniteBf16(values) != 0) return error.NonfiniteInput; + + const max_m = 128; + const result = try arena.alloc(u16, (max_m + 1) * n_out); + const again = try arena.alloc(u16, (max_m + 1) * n_out); + const input_check = try arena.alloc(u16, max_m * k_in); + const weight_check = try arena.alloc(u16, n_out * k_in); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var lt = try lt_api.Library.open(); + defer lt.close(); + const get_attribute = lt.lib.lookup(AlgoConfigGetAttribute, "cublasLtMatmulAlgoConfigGetAttribute") orelse return error.MissingSymbol; + + var plans: [plan_rows.len]lt_api.Linear = undefined; + var plans_made: usize = 0; + defer for (plans[0..plans_made]) |*plan| plan.deinit(); + for (plan_rows, 0..) |m, i| { + plans[i] = try lt_api.Linear.init(<, m, n_out, k_in, .bf16, workspace_bytes); + plans_made += 1; + } + + var device_weight = try cuda.DeviceBuffer.alloc(&driver, n_out * k_in * 2); + defer device_weight.free(); + try device_weight.upload(0, std.mem.sliceAsBytes(weight)); + var device_x = try cuda.DeviceBuffer.alloc(&driver, max_m * k_in * 2); + defer device_x.free(); + var device_d = try cuda.DeviceBuffer.alloc(&driver, (max_m + 1) * n_out * 2); + defer device_d.free(); + var workspace = try cuda.DeviceBuffer.alloc(&driver, workspace_bytes); + defer workspace.free(); + + // Plans: the chosen algorithm, decoded. + var plans_json: std.ArrayList(u8) = .empty; + defer plans_json.deinit(gpa); + for (plan_rows, 0..) |m, i| { + const plan = &plans[i]; + try plans_json.print(gpa, "{s}\n {{\"m\": {d}, \"n\": {d}, \"k\": {d}, \"workspace_need\": {d}, \"workspace_limit\": {d}, \"algo_bytes\": \"", .{ + if (i == 0) "" else ",", m, n_out, k_in, plan.workspace_need, workspace_bytes, + }); + for (std.mem.asBytes(&plan.algo)) |byte| try plans_json.print(gpa, "{x:0>2}", .{byte}); + try plans_json.appendSlice(gpa, "\""); + for (algo_attributes) |attribute| { + var buffer: [8]u8 = @splat(0); + var written: usize = 0; + const status = get_attribute(&plan.algo, attribute.id, &buffer, attribute.size, &written); + if (status != 0 or written != attribute.size) { + try errors.add("m {d}: cublasLtMatmulAlgoConfigGetAttribute({s}) status {d} written {d}", .{ m, attribute.name, status, written }); + try plans_json.print(gpa, ", \"{s}\": null", .{attribute.name}); + } else { + const value: i64 = if (attribute.size == 4) std.mem.readInt(i32, buffer[0..4], .little) else std.mem.readInt(u16, buffer[0..2], .little); + try plans_json.print(gpa, ", \"{s}\": {d}", .{ attribute.name, value }); + } + } + try plans_json.appendSlice(gpa, "}"); + } + + var cells_json: std.ArrayList(u8) = .empty; + defer cells_json.deinit(gpa); + var name_buffer: [96]u8 = undefined; + for (cells, 0..) |cell, ci| { + const plan_index = std.mem.indexOfScalar(usize, &plan_rows, cell.m) orelse unreachable; + const plan = &plans[plan_index]; + const source = if (cell.streaming) streaming else batch; + const x = source[cell.row0 * k_in .. (cell.row0 + cell.m) * k_in]; + const out_len = cell.m * n_out; + var repeat_differences: usize = 0; + var guard_broken: usize = 0; + var input_changed: usize = 0; + var nonfinite: usize = 0; + for (0..repeats) |r| { + try device_x.upload(0, std.mem.sliceAsBytes(x)); + try device_d.fill8(0xff, stream.handle); + try workspace.fill8(0xff, stream.handle); + try plan.run(device_x.ptr, device_weight.ptr, device_d.ptr, workspace.ptr, workspace.len, stream.handle); + try stream.synchronize(); + const target = if (r == 0) result else again; + try device_d.download(0, std.mem.sliceAsBytes(target[0 .. out_len + n_out])); + for (target[out_len .. out_len + n_out]) |bits| { + if (bits != 0xffff) guard_broken += 1; + } + if (r == 0) nonfinite = nonfiniteBf16(result[0..out_len]) else repeat_differences += differences(result[0..out_len], again[0..out_len]); + try device_x.download(0, std.mem.sliceAsBytes(input_check[0 .. cell.m * k_in])); + input_changed += differences(input_check[0 .. cell.m * k_in], x); + } + if (repeat_differences != 0 or guard_broken != 0 or input_changed != 0 or nonfinite != 0) + try errors.add("{s}: repeat differences {d}, guard values changed {d}, device input changed {d}, nonfinite {d}", .{ + cell.label, repeat_differences, guard_broken, input_changed, nonfinite, + }); + const name = try std.fmt.bufPrint(&name_buffer, "native-replay-{s}.bf16", .{cell.label}); + const bytes = std.mem.sliceAsBytes(result[0..out_len]); + try out.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + const sha = sha256Hex(bytes); + try cells_json.print(gpa, "{s}\n {{\"label\": \"{s}\", \"source\": \"{s}\", \"source_row0\": {d}, \"m\": {d}, \"plan_m\": {d}, \"runs\": {d}," ++ + " \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}, \"repeat_differences\": {d}," ++ + " \"guard_values_changed\": {d}, \"device_input_changed\": {d}}}", .{ + if (ci == 0) "" else ",", cell.label, if (cell.streaming) "streaming" else "batch", cell.row0, cell.m, plan_rows[plan_index], repeats, + name, sha[0..], cell.m, n_out, nonfinite, repeat_differences, guard_broken, + input_changed, + }); + } + + try device_weight.download(0, std.mem.sliceAsBytes(weight_check)); + const device_weight_differences = differences(weight_check, weight); + if (device_weight_differences != 0) try errors.add("device weight changed in {d} values", .{device_weight_differences}); + const host_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(weight)), &weight_sha) and + std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(batch)), &batch_sha) and + std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(streaming)), &streaming_sha); + if (!host_unchanged) try errors.add("host inputs changed", .{}); + const used = cuda.usage(false); + + var library_path: std.ArrayList(u8) = .empty; + defer library_path.deinit(gpa); + try mappedCublasLt(gpa, io, &library_path); + var library_sha: [64]u8 = @splat('0'); + if (library_path.items.len == 0) { + try errors.add("libcublasLt mapping not found", .{}); + } else { + library_sha = fileSha256(gpa, io, library_path.items) catch |err| blk: { + try errors.add("libcublasLt hash failed: {s}", .{@errorName(err)}); + break :blk library_sha; + }; + } + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const driver_source_sha = sha256Hex(@embedFile("drama_tower_linear_replay.zig")); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-linear-replay\",\n \"weight_path\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"batch_joined_path\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.appendSlice(gpa, ",\n \"streaming_joined_path\": "); + try jsonString(&manifest, gpa, args[3]); + try manifest.appendSlice(gpa, ",\n \"cublaslt_path\": "); + try jsonString(&manifest, gpa, library_path.items); + try manifest.print(gpa, ",\n \"weight_sha256\": \"{s}\",\n \"batch_joined_sha256\": \"{s}\",\n \"streaming_joined_sha256\": \"{s}\"," ++ + "\n \"operation\": \"cuda.cublaslt.Linear: D[m,{d}] = X[m,{d}] . W[{d},{d}]^T, BF16 A/B/D, compute 32F, scale 32F, transa T, transb N, first heuristic, workspace limit {d}\"," ++ + "\n \"cublaslt_version\": {d},\n \"cublaslt_sha256\": \"{s}\",\n \"repeats\": {d}," ++ + "\n \"plans\": [{s}\n ],\n \"cells\": [{s}\n ]," ++ + "\n \"device_weight_differences\": {d},\n \"host_inputs_unchanged\": {}," ++ + "\n \"allocations\": {{\"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}}}," ++ + "\n \"binary_sha256\": {s},\n \"driver_source_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + weight_sha[0..], batch_sha[0..], streaming_sha[0..], n_out, + k_in, n_out, k_in, workspace_bytes, + lt.api.cublasLtGetVersion(), library_sha[0..], repeats, plans_json.items, + cells_json.items, device_weight_differences, host_unchanged, used.device, + used.peak, binary_json.items, driver_source_sha[0..], evidence_valid, + errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("cells={d} evidence_valid={} errors={d}\n", .{ cells.len, evidence_valid, errors.count }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_tower_mixer_trace.zig b/zig/tests/cuda/drama_tower_mixer_trace.zig new file mode 100644 index 00000000000..f5881ab7923 --- /dev/null +++ b/zig/tests/cuda/drama_tower_mixer_trace.zig @@ -0,0 +1,384 @@ +//! Diagnostic: the production tower's mixer operands and outputs on the full-context fixture. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const tower = drama.tower; +const Stage = tower.Stage; +const Frame = tower.Frame; +const Impl = @typeInfo(@FieldType(tower.Model, "impl")).pointer.child; + +const width = 2048; +const joined_width = 2 * width; +const kv_width = 512; +const vocab = 4096; +const max_rows = 128; +const context = 512; +const prefix_rows = 181; +const suffix_rows = 128; +const hidden_rows = prefix_rows + suffix_rows; +const frame_rows = hidden_rows + 1; +const prefix_chunks = [_]usize{ 128, 53 }; +const row_counts = [_]usize{ 1, 7, suffix_rows }; +const projection_count = 6; +const head_kind = 5; +const head_index = 8; +const head_plan = (1 - 1) * projection_count + head_kind; +const layer_count = @typeInfo(@FieldType(Impl, "layers")).array.len; + +comptime { + std.debug.assert(layer_count == 13); + std.debug.assert(tower.stageWidth(.joined) == joined_width and tower.stageWidth(.output) == width and tower.stageWidth(.shared_input) == width); + var sum: usize = 0; + for (prefix_chunks) |c| sum += c; + std.debug.assert(sum == prefix_rows and hidden_rows <= context); +} + +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +/// Copies shared_input, every joined and every output of one suffix call; ignores the other capture points. +const Tracer = struct { + n: usize, + staging: []align(16) u8, + shared: []u16, // [max_rows][width] + joined: []u16, // [layer][max_rows][joined_width] + output: []u16, // [layer][max_rows][width] + shared_seen: usize = 0, + joined_seen: [layer_count]usize = @splat(0), + output_seen: [layer_count]usize = @splat(0), + next_layer: usize = 0, // joined of layer L must come after output of layer L - 1 + out_of_order: usize = 0, + bad_row0: usize = 0, + + pub fn capture(t: *Tracer, stream: cuda.Stream, layer: usize, stage: Stage, src: cuda.DeviceBuffer, row0: usize) !void { + const dst: []u16 = switch (stage) { + .shared_input => blk: { + t.shared_seen += 1; + break :blk t.shared[0 .. t.n * width]; + }, + .joined => blk: { + if (layer != t.next_layer) t.out_of_order += 1; + t.joined_seen[layer] += 1; + break :blk t.joined[layer * max_rows * joined_width ..][0 .. t.n * joined_width]; + }, + .output => blk: { + if (layer != t.next_layer) t.out_of_order += 1; + t.output_seen[layer] += 1; + t.next_layer = layer + 1; + break :blk t.output[layer * max_rows * width ..][0 .. t.n * width]; + }, + else => return, + }; + if (row0 != prefix_rows) t.bad_row0 += 1; + const bytes = std.mem.sliceAsBytes(dst); + if (src.len != bytes.len or bytes.len > t.staging.len) return error.TraceCaptureShape; + try src.downloadAsync(0, t.staging[0..bytes.len], stream.handle); + try stream.synchronize(); + @memcpy(bytes, t.staging[0..bytes.len]); + } +}; + +const Finals = struct { + hidden: []u16, + head: []u16, + kv: []u16, // [layer][keys, values][n][kv_width] + + fn alloc(arena: Allocator) !Finals { + return .{ .hidden = try arena.alloc(u16, max_rows * width), .head = try arena.alloc(u16, vocab), .kv = try arena.alloc(u16, layer_count * 2 * max_rows * kv_width) }; + } + + fn kvRows(f: Finals, n: usize, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * n * kv_width; + return f.kv[at .. at + n * kv_width]; + } +}; + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +fn cacheOffset(layer: usize, which: usize, row: usize) usize { + return ((layer * 2 + which) * context + row) * kv_width * 2; +} + +/// The context oracle's batch schedule; the suffix call is traced when `trace` is not void. +fn runBatch(model: *tower.Model, stream: cuda.Stream, dev: cuda.DeviceBuffer, frames: []const Frame, n: usize, trace: anytype, f: Finals) !void { + const p = model.impl; + try model.reset(stream, &.{}, 0); + var row: usize = 0; + for (prefix_chunks) |c| { + _ = try model.setInput(stream, frames[row .. row + c]); + try model.prefill(stream, view(dev, row * width * 2, c * width * 2), frames[row + 1 .. row + c + 1]); + row += c; + } + const a = prefix_rows; + _ = try model.setInput(stream, frames[a .. a + n]); + if (@TypeOf(trace) == void) + try model.prefill(stream, view(dev, a * width * 2, n * width * 2), frames[a + 1 .. a + n + 1]) + else + try model.prefillTraced(stream, view(dev, a * width * 2, n * width * 2), frames[a + 1 .. a + n + 1], trace); + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.hidden[0 .. n * width])); + try p.head_logits.fill8(0xff, stream.handle); + try p.plans.items[head_plan].run(p.output_hidden.ptr + (n - 1) * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(f.head)); + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, prefix_rows), std.mem.sliceAsBytes(f.kvRows(n, layer, which))); + }; +} + +fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// Writes one BF16 array as a new file; appends `{"file", "sha256", "shape", "nonfinite"}` (with a leading key). +fn emit(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), key: []const u8, name: []const u8, data: []const u16, rows: usize, cols: usize, errors: *Errors) !usize { + const bytes = std.mem.sliceAsBytes(data); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + const bad = nonfiniteBf16(data); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "\"{s}\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}}}", .{ key, name, sha[0..], rows, cols, bad }); + return bytes.len; +} + +fn emitFinals(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), n: usize, label: []const u8, f: Finals, errors: *Errors) !usize { + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + try json.print(gpa, "\"{s}\": {{", .{label}); + var name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-hidden.bf16", .{ n, label }); + written += try emit(gpa, io, dir, json, "hidden", name, f.hidden[0 .. n * width], n, width, errors); + try json.appendSlice(gpa, ", "); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-head9.bf16", .{ n, label }); + written += try emit(gpa, io, dir, json, "head9", name, f.head, 1, vocab, errors); + try json.appendSlice(gpa, ", \"kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-layer-{d:0>2}-{s}.bf16", .{ n, label, layer, kind }); + if (layer != 0 or which != 0) try json.appendSlice(gpa, ", "); + written += try emit(gpa, io, dir, json, key, name, f.kvRows(n, layer, which), n, kv_width, errors); + }; + try json.appendSlice(gpa, "}}"); + return written; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-mixer-trace CHECKPOINT FIXTURE_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const fixture = try std.Io.Dir.cwd().openDir(io, args[2], .{}); + defer fixture.close(io); + const out = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer out.close(io); + + const hidden = try arena.alloc(u16, hidden_rows * width); + var frames: [frame_rows]Frame = undefined; + try readExact(io, fixture, "hidden.bf16", std.mem.sliceAsBytes(hidden)); + try readExact(io, fixture, "frames.u32le", std.mem.sliceAsBytes(&frames)); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha = sha256Hex(std.mem.sliceAsBytes(&frames)); + for (hidden) |bits| if ((bits & 0x7f80) == 0x7f80) return error.NonfiniteFixtureHidden; + + const traced = try Finals.alloc(arena); + const untraced = try Finals.alloc(arena); + const shared = try arena.alloc(u16, max_rows * width); + const joined = try arena.alloc(u16, layer_count * max_rows * joined_width); + const output = try arena.alloc(u16, layer_count * max_rows * width); + const device_check = try arena.alloc(u16, hidden_rows * width); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try tower.Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + const p = model.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2 or + p.joined.len != max_rows * joined_width * 2 or p.cache.len != layer_count * 2 * context * kv_width * 2) return error.UnexpectedTowerLayout; + const model_usage = cuda.usage(false); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, hidden_rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + var staging = try cuda.HostBuffer.alloc(&driver, max_rows * joined_width * 2); + defer staging.free(); + + var cases: std.ArrayList(u8) = .empty; + defer cases.deinit(gpa); + var written: usize = 0; + var name_buffer: [96]u8 = undefined; + for (row_counts, 0..) |n, case_index| { + var tracer: Tracer = .{ .n = n, .staging = staging.bytes, .shared = shared, .joined = joined, .output = output }; + try runBatch(&model, stream, device_hidden, &frames, n, &tracer, traced); + try runBatch(&model, stream, device_hidden, &frames, n, {}, untraced); + + if (tracer.shared_seen != 1 or tracer.out_of_order != 0 or tracer.bad_row0 != 0) + try errors.add("rows {d}: shared_input captures {d}, out of order {d}, bad row0 {d}", .{ n, tracer.shared_seen, tracer.out_of_order, tracer.bad_row0 }); + for (0..layer_count) |layer| { + if (tracer.joined_seen[layer] != 1 or tracer.output_seen[layer] != 1) + try errors.add("rows {d} layer {d}: joined captures {d}, output captures {d}", .{ n, layer, tracer.joined_seen[layer], tracer.output_seen[layer] }); + } + const last_output = output[(layer_count - 1) * max_rows * width ..][0 .. n * width]; + const output_vs_hidden = differences(last_output, traced.hidden[0 .. n * width]); + if (output_vs_hidden != 0) try errors.add("rows {d}: layer 12 output capture differs from the final hidden in {d} values", .{ n, output_vs_hidden }); + const d_hidden = differences(traced.hidden[0 .. n * width], untraced.hidden[0 .. n * width]); + const d_head = differences(traced.head, untraced.head); + const d_kv = differences(traced.kv[0 .. layer_count * 2 * n * kv_width], untraced.kv[0 .. layer_count * 2 * n * kv_width]); + if (d_hidden != 0 or d_head != 0 or d_kv != 0) try errors.add("rows {d}: traced vs untraced bit differences hidden {d} head9 {d} kv {d}", .{ n, d_hidden, d_head, d_kv }); + + try cases.print(gpa, "{s}\n {{\"rows\": {d}, \"suffix_positions\": [{d}, {d}], \"traced_vs_untraced_bit_differences\": {{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}}}," ++ + " \"layer12_output_vs_final_hidden_differences\": {d}, \"captures\": {{", .{ + if (case_index == 0) "" else ",", n, prefix_rows, prefix_rows + n - 1, d_hidden, d_head, d_kv, output_vs_hidden, + }); + var name = try std.fmt.bufPrint(&name_buffer, "native-{d}-shared_input.bf16", .{n}); + written += try emit(gpa, io, out, &cases, "shared_input", name, shared[0 .. n * width], n, width, &errors); + try cases.appendSlice(gpa, ", \"layers\": ["); + for (0..layer_count) |layer| { + try cases.print(gpa, "{s}{{\"layer\": {d}, \"code_index\": {d}, ", .{ if (layer == 0) "" else ", ", layer, if (layer < 4) 0 else layer - 4 }); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-layer-{d:0>2}-joined.bf16", .{ n, layer }); + written += try emit(gpa, io, out, &cases, "joined", name, joined[layer * max_rows * joined_width ..][0 .. n * joined_width], n, joined_width, &errors); + try cases.appendSlice(gpa, ", "); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-layer-{d:0>2}-output.bf16", .{ n, layer }); + written += try emit(gpa, io, out, &cases, "output", name, output[layer * max_rows * width ..][0 .. n * width], n, width, &errors); + try cases.appendSlice(gpa, "}"); + } + try cases.appendSlice(gpa, "]}, \"finals\": {"); + written += try emitFinals(gpa, io, out, &cases, n, "traced", traced, &errors); + try cases.appendSlice(gpa, ", "); + written += try emitFinals(gpa, io, out, &cases, n, "untraced", untraced, &errors); + try cases.appendSlice(gpa, "}}"); + std.debug.print("suffix_rows={d} traced_untraced_hidden_diff={d} head9_diff={d} kv_diff={d} layer12_output_diff={d}\n", .{ n, d_hidden, d_head, d_kv, output_vs_hidden }); + } + + try device_hidden.download(0, std.mem.sliceAsBytes(device_check)); + const device_input_differences = differences(device_check, hidden); + if (device_input_differences != 0) try errors.add("device input hidden changed in {d} values", .{device_input_differences}); + const host_hidden_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(hidden)), &hidden_sha); + const host_frames_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(&frames)), &frames_sha); + if (!host_hidden_unchanged or !host_frames_unchanged) try errors.add("host fixture changed: hidden unchanged {} frames unchanged {}", .{ host_hidden_unchanged, host_frames_unchanged }); + const used = cuda.usage(false); + + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const tower_source_sha = sha256Hex(tower.trace_source); + const driver_source_sha = sha256Hex(@embedFile("drama_tower_mixer_trace.zig")); + const kernel_image_sha = sha256Hex(cuda.kernels.drama_tower); + if (cuda.kernels.drama_tower.len == 0) try errors.add("embedded drama_tower kernel image is empty", .{}); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-mixer-trace\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"fixture_directory\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"input_hidden_sha256\": \"{s}\",\n \"input_frames_sha256\": \"{s}\",\n \"layer_count\": {d}," ++ + "\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"prefix_rows\": {d},\n \"prefix_chunks\": [{d}, {d}],\n \"suffix_rows\": [{d}, {d}, {d}]," ++ + "\n \"captured_stages\": [\"shared_input\", \"joined\", \"output\"]," ++ + "\n \"row_mapping\": \"capture row j is fixture row 181 + j at position 181 + j; labels frames[182 + j]; layer L mixer hidden input is layer L - 1 output (layer 0: fixture hidden)\"," ++ + "\n \"cases\": [{s}\n ]," ++ + "\n \"input_immutable\": {{\"device_hidden_differences\": {d}, \"host_hidden_unchanged\": {}, \"host_frames_unchanged\": {}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}}}," ++ + "\n \"bytes_written\": {d}," ++ + "\n \"binary_sha256\": {s},\n \"tower_source_sha256\": \"{s}\",\n \"driver_source_sha256\": \"{s}\",\n \"tower_kernel_image_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + hidden_sha[0..], frames_sha[0..], layer_count, context, + max_rows, prefix_rows, prefix_chunks[0], prefix_chunks[1], + row_counts[0], row_counts[1], row_counts[2], cases.items, + device_input_differences, host_hidden_unchanged, host_frames_unchanged, model_usage.device, + used.device, used.peak, used.host, written, + binary_json.items, tower_source_sha[0..], driver_source_sha[0..], kernel_image_sha[0..], + evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("cases={d} bytes_written={d} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d}\n", .{ + row_counts.len, written + manifest.items.len, evidence_valid, errors.count, used.device, used.peak, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_tower_oracle.zig b/zig/tests/cuda/drama_tower_oracle.zig new file mode 100644 index 00000000000..c9142c79b94 --- /dev/null +++ b/zig/tests/cuda/drama_tower_oracle.zig @@ -0,0 +1,96 @@ +//! Teacher-forces fixed rows through the production tower; exports final hidden, last codebook head and KV cache. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); +const rows = 128; +const width = 2048; +const kv_width = 512; +const Frame = drama.tower.Frame; + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +pub fn main(init: std.process.Init) !u8 { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-oracle CHECKPOINT FIXTURE_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + var fixture = try std.Io.Dir.cwd().openDir(init.io, args[2], .{}); + defer fixture.close(init.io); + var out = try std.Io.Dir.cwd().openDir(init.io, args[3], .{}); + defer out.close(init.io); + const hidden = try init.gpa.alloc(u16, rows * width); + defer init.gpa.free(hidden); + var frames: [rows + 1]Frame = undefined; + try readExact(init.io, fixture, "hidden.bf16", std.mem.sliceAsBytes(hidden)); + try readExact(init.io, fixture, "frames.u32le", std.mem.sliceAsBytes(&frames)); + const result = try init.gpa.alloc(u16, rows * width); + defer init.gpa.free(result); + const repeated = try init.gpa.alloc(u16, rows * width); + defer init.gpa.free(repeated); + const cache_row = try init.gpa.alloc(u16, rows * kv_width); + defer init.gpa.free(cache_row); + var logits: [4096]u16 = undefined; + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var tower = try drama.tower.Model.init(init.gpa, init.io, &ctx, args[1], "", .{ .context = rows, .max_rows = rows }); + defer tower.deinit(); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + const p = tower.impl; + var name_buffer: [128]u8 = undefined; + for ([_]usize{ 1, 7, rows }) |n| { + try tower.reset(stream, &.{}, 0); + _ = try tower.setInput(stream, frames[0..n]); + try tower.prefill(stream, view(device_hidden, 0, n * width * 2), frames[1 .. n + 1]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(result[0 .. n * width])); + var name = try std.fmt.bufPrint(&name_buffer, "native-{d}-hidden.bf16", .{n}); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(result[0 .. n * width]) }); + // The one-row final head uses generate()'s cuBLASLt plan and weights; no sampling. + try p.plans.items[5].run(p.output_hidden.ptr + (n - 1) * width * 2, p.heads[8].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(&logits)); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-head9.bf16", .{n}); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(&logits) }); + for (0..13) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + const offset = (layer * 2 + which) * rows * kv_width * 2; + try p.cache.download(offset, std.mem.sliceAsBytes(cache_row[0 .. n * kv_width])); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-layer-{d}-{s}.bf16", .{ n, layer, kind }); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(cache_row[0 .. n * kv_width]) }); + }; + try tower.reset(stream, &.{}, 0); + _ = try tower.setInput(stream, frames[0..n]); + try tower.prefill(stream, view(device_hidden, 0, n * width * 2), frames[1 .. n + 1]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(repeated[0 .. n * width])); + if (!std.mem.eql(u16, result[0 .. n * width], repeated[0 .. n * width])) return error.TowerResetNotReproducible; + // GEMM row counts may change low BF16 bits: chunked output is exported for comparison, not gated bitwise. + try tower.reset(stream, &.{}, 0); + for (0..n) |r| { + _ = try tower.setInput(stream, frames[r .. r + 1]); + try tower.prefill(stream, view(device_hidden, r * width * 2, width * 2), frames[r + 1 .. r + 2]); + try p.output_hidden.download(0, std.mem.sliceAsBytes(repeated[r * width .. (r + 1) * width])); + } + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-chunked-hidden.bf16", .{n}); + try out.writeFile(init.io, .{ .sub_path = name, .data = std.mem.sliceAsBytes(repeated[0 .. n * width]) }); + const used = cuda.usage(false); + std.debug.print("tower_rows={d} reset_bit_exact=true cuda_bytes={d} pinned_bytes={d}\n", .{ n, used.device, used.host }); + } + return 0; +} diff --git a/zig/tests/cuda/drama_tower_qk_trace.zig b/zig/tests/cuda/drama_tower_qk_trace.zig new file mode 100644 index 00000000000..4b4f3b93e2b --- /dev/null +++ b/zig/tests/cuda/drama_tower_qk_trace.zig @@ -0,0 +1,414 @@ +//! Diagnostic: the production tower's Q/K norm and RoPE operands and outputs on the full-context fixture. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const tower = drama.tower; +const Stage = tower.Stage; +const Frame = tower.Frame; +const Impl = @typeInfo(@FieldType(tower.Model, "impl")).pointer.child; + +const width = 2048; +const qkv_width = 9216; +const query_width = 4096; +const kv_width = 512; +const vocab = 4096; +const max_rows = 128; +const context = 512; +const prefix_rows = 181; +const suffix_rows = 128; +const hidden_rows = prefix_rows + suffix_rows; +const frame_rows = hidden_rows + 1; +const prefix_chunks = [_]usize{ 128, 53 }; +const row_counts = [_]usize{ 1, 7, suffix_rows }; +const projection_count = 6; +const head_kind = 5; +const head_index = 8; +const head_plan = (1 - 1) * projection_count + head_kind; +const layer_count = @typeInfo(@FieldType(Impl, "layers")).array.len; +const captured = [_]Stage{ .qkv, .query, .key, .value }; + +comptime { + std.debug.assert(layer_count == 13); + std.debug.assert(tower.stageWidth(.qkv) == qkv_width and tower.stageWidth(.query) == query_width); + std.debug.assert(tower.stageWidth(.key) == kv_width and tower.stageWidth(.value) == kv_width); + var sum: usize = 0; + for (prefix_chunks) |c| sum += c; + std.debug.assert(sum == prefix_rows and hidden_rows <= context); +} + +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +fn stageIndex(stage: Stage) ?usize { + for (captured, 0..) |s, i| if (s == stage) return i; + return null; +} + +/// Per layer and captured stage, [max_rows][stageWidth] BF16. +const Captures = struct { + data: [layer_count][captured.len][]u16, + + fn alloc(arena: Allocator) !Captures { + var c: Captures = undefined; + for (&c.data) |*layer| for (layer, captured) |*slot, stage| { + slot.* = try arena.alloc(u16, max_rows * tower.stageWidth(stage)); + }; + return c; + } + + fn rows(c: *const Captures, layer: usize, which: usize, n: usize) []u16 { + return c.data[layer][which][0 .. n * tower.stageWidth(captured[which])]; + } +}; + +const Tracer = struct { + n: usize, + staging: []align(16) u8, + out: *Captures, + seen: [layer_count][captured.len]usize = std.mem.zeroes([layer_count][captured.len]usize), + expected: usize = 0, // next capture in (layer, stage) order + out_of_order: usize = 0, + bad_row0: usize = 0, + + pub fn capture(t: *Tracer, stream: cuda.Stream, layer: usize, stage: Stage, src: cuda.DeviceBuffer, row0: usize) !void { + const which = stageIndex(stage) orelse return; + if (layer * captured.len + which != t.expected) t.out_of_order += 1; + t.expected = layer * captured.len + which + 1; + if (row0 != prefix_rows) t.bad_row0 += 1; + t.seen[layer][which] += 1; + const dst = t.out.rows(layer, which, t.n); + const bytes = std.mem.sliceAsBytes(dst); + if (src.len != bytes.len or bytes.len > t.staging.len) return error.TraceCaptureShape; + try src.downloadAsync(0, t.staging[0..bytes.len], stream.handle); + try stream.synchronize(); + @memcpy(bytes, t.staging[0..bytes.len]); + } +}; + +const Finals = struct { + hidden: []u16, + head: []u16, + kv: []u16, + + fn alloc(arena: Allocator) !Finals { + return .{ .hidden = try arena.alloc(u16, max_rows * width), .head = try arena.alloc(u16, vocab), .kv = try arena.alloc(u16, layer_count * 2 * max_rows * kv_width) }; + } + + fn kvRows(f: Finals, n: usize, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * n * kv_width; + return f.kv[at .. at + n * kv_width]; + } +}; + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +fn cacheOffset(layer: usize, which: usize, row: usize) usize { + return ((layer * 2 + which) * context + row) * kv_width * 2; +} + +fn runBatch(model: *tower.Model, stream: cuda.Stream, dev: cuda.DeviceBuffer, frames: []const Frame, n: usize, trace: anytype, f: Finals) !void { + const p = model.impl; + try model.reset(stream, &.{}, 0); + var row: usize = 0; + for (prefix_chunks) |c| { + _ = try model.setInput(stream, frames[row .. row + c]); + try model.prefill(stream, view(dev, row * width * 2, c * width * 2), frames[row + 1 .. row + c + 1]); + row += c; + } + const a = prefix_rows; + _ = try model.setInput(stream, frames[a .. a + n]); + if (@TypeOf(trace) == void) + try model.prefill(stream, view(dev, a * width * 2, n * width * 2), frames[a + 1 .. a + n + 1]) + else + try model.prefillTraced(stream, view(dev, a * width * 2, n * width * 2), frames[a + 1 .. a + n + 1], trace); + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.hidden[0 .. n * width])); + try p.head_logits.fill8(0xff, stream.handle); + try p.plans.items[head_plan].run(p.output_hidden.ptr + (n - 1) * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(f.head)); + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download(cacheOffset(layer, which, prefix_rows), std.mem.sliceAsBytes(f.kvRows(n, layer, which))); + }; +} + +fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +fn emit(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), key: []const u8, name: []const u8, data: []const u16, rows: usize, cols: usize, errors: *Errors) !usize { + const bytes = std.mem.sliceAsBytes(data); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + const bad = nonfiniteBf16(data); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "\"{s}\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}}}", .{ key, name, sha[0..], rows, cols, bad }); + return bytes.len; +} + +fn emitFinals(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), n: usize, label: []const u8, f: Finals, errors: *Errors) !usize { + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + try json.print(gpa, "\"{s}\": {{", .{label}); + var name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-hidden.bf16", .{ n, label }); + written += try emit(gpa, io, dir, json, "hidden", name, f.hidden[0 .. n * width], n, width, errors); + try json.appendSlice(gpa, ", "); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-head9.bf16", .{ n, label }); + written += try emit(gpa, io, dir, json, "head9", name, f.head, 1, vocab, errors); + try json.appendSlice(gpa, ", \"kv\": {"); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + var key_buffer: [32]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buffer, "layer-{d:0>2}-{s}", .{ layer, kind }); + name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-layer-{d:0>2}-{s}.bf16", .{ n, label, layer, kind }); + if (layer != 0 or which != 0) try json.appendSlice(gpa, ", "); + written += try emit(gpa, io, dir, json, key, name, f.kvRows(n, layer, which), n, kv_width, errors); + }; + try json.appendSlice(gpa, "}}"); + return written; +} + +fn compareFinals(n: usize, a: Finals, b: Finals) [3]usize { + return .{ + differences(a.hidden[0 .. n * width], b.hidden[0 .. n * width]), + differences(a.head, b.head), + differences(a.kv[0 .. layer_count * 2 * n * kv_width], b.kv[0 .. layer_count * 2 * n * kv_width]), + }; +} + +fn checkTracer(t: *const Tracer, n: usize, label: []const u8, errors: *Errors) !void { + if (t.out_of_order != 0 or t.bad_row0 != 0) try errors.add("rows {d} {s}: {d} captures out of order, {d} with a bad row0", .{ n, label, t.out_of_order, t.bad_row0 }); + for (0..layer_count) |layer| for (0..captured.len) |which| { + if (t.seen[layer][which] != 1) try errors.add("rows {d} {s}: layer {d} stage {s} captured {d} times", .{ n, label, layer, @tagName(captured[which]), t.seen[layer][which] }); + }; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-qk-trace CHECKPOINT FIXTURE_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const fixture = try std.Io.Dir.cwd().openDir(io, args[2], .{}); + defer fixture.close(io); + const out = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer out.close(io); + + const hidden = try arena.alloc(u16, hidden_rows * width); + var frames: [frame_rows]Frame = undefined; + try readExact(io, fixture, "hidden.bf16", std.mem.sliceAsBytes(hidden)); + try readExact(io, fixture, "frames.u32le", std.mem.sliceAsBytes(&frames)); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha = sha256Hex(std.mem.sliceAsBytes(&frames)); + for (hidden) |bits| if ((bits & 0x7f80) == 0x7f80) return error.NonfiniteFixtureHidden; + + var first = try Captures.alloc(arena); + var again = try Captures.alloc(arena); + const traced = try Finals.alloc(arena); + const untraced = try Finals.alloc(arena); + const repeat = try Finals.alloc(arena); + const device_check = try arena.alloc(u16, hidden_rows * width); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + var model = try tower.Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + const p = model.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2 or + p.qkv.len != max_rows * qkv_width * 2 or p.queries.len != max_rows * query_width * 2 or + p.cache.len != layer_count * 2 * context * kv_width * 2) return error.UnexpectedTowerLayout; + const model_usage = cuda.usage(false); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, hidden_rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + var staging = try cuda.HostBuffer.alloc(&driver, max_rows * qkv_width * 2); + defer staging.free(); + + var cases: std.ArrayList(u8) = .empty; + defer cases.deinit(gpa); + var written: usize = 0; + var name_buffer: [96]u8 = undefined; + for (row_counts, 0..) |n, case_index| { + var t1: Tracer = .{ .n = n, .staging = staging.bytes, .out = &first }; + try runBatch(&model, stream, device_hidden, &frames, n, &t1, traced); + try runBatch(&model, stream, device_hidden, &frames, n, {}, untraced); + var t2: Tracer = .{ .n = n, .staging = staging.bytes, .out = &again }; + try runBatch(&model, stream, device_hidden, &frames, n, &t2, repeat); + try checkTracer(&t1, n, "traced", &errors); + try checkTracer(&t2, n, "repeat", &errors); + + var capture_repeat_differences: usize = 0; + var cache_vs_capture: usize = 0; + for (0..layer_count) |layer| { + for (0..captured.len) |which| capture_repeat_differences += differences(first.rows(layer, which, n), again.rows(layer, which, n)); + cache_vs_capture += differences(first.rows(layer, 2, n), traced.kvRows(n, layer, 0)); + cache_vs_capture += differences(first.rows(layer, 3, n), traced.kvRows(n, layer, 1)); + } + if (capture_repeat_differences != 0) try errors.add("rows {d}: {d} captured values differ between traced runs", .{ n, capture_repeat_differences }); + if (cache_vs_capture != 0) try errors.add("rows {d}: key/value captures differ from the exported cache rows in {d} values", .{ n, cache_vs_capture }); + const du = compareFinals(n, traced, untraced); + const dr = compareFinals(n, traced, repeat); + if (du[0] != 0 or du[1] != 0 or du[2] != 0) try errors.add("rows {d}: traced vs untraced bit differences hidden {d} head9 {d} kv {d}", .{ n, du[0], du[1], du[2] }); + if (dr[0] != 0 or dr[1] != 0 or dr[2] != 0) try errors.add("rows {d}: traced vs repeat bit differences hidden {d} head9 {d} kv {d}", .{ n, dr[0], dr[1], dr[2] }); + + try cases.print(gpa, "{s}\n {{\"rows\": {d}, \"suffix_positions\": [{d}, {d}]," ++ + " \"traced_vs_untraced_bit_differences\": {{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}}}," ++ + " \"traced_vs_repeat_bit_differences\": {{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}}}," ++ + " \"capture_repeat_differences\": {d}, \"key_value_capture_vs_cache_differences\": {d}, \"captures\": [", .{ + if (case_index == 0) "" else ",", n, prefix_rows, prefix_rows + n - 1, du[0], du[1], du[2], dr[0], dr[1], dr[2], + capture_repeat_differences, cache_vs_capture, + }); + for (0..layer_count) |layer| { + try cases.print(gpa, "{s}{{\"layer\": {d}", .{ if (layer == 0) "" else ", ", layer }); + for (captured, 0..) |stage, which| { + try cases.appendSlice(gpa, ", "); + const name = try std.fmt.bufPrint(&name_buffer, "native-{d}-layer-{d:0>2}-{s}.bf16", .{ n, layer, @tagName(stage) }); + written += try emit(gpa, io, out, &cases, @tagName(stage), name, first.rows(layer, which, n), n, tower.stageWidth(stage), &errors); + } + try cases.appendSlice(gpa, "}"); + } + try cases.appendSlice(gpa, "], \"finals\": {"); + written += try emitFinals(gpa, io, out, &cases, n, "traced", traced, &errors); + try cases.appendSlice(gpa, ", "); + written += try emitFinals(gpa, io, out, &cases, n, "untraced", untraced, &errors); + try cases.appendSlice(gpa, ", "); + written += try emitFinals(gpa, io, out, &cases, n, "repeat", repeat, &errors); + try cases.appendSlice(gpa, "}}"); + std.debug.print("suffix_rows={d} untraced_diff={d}/{d}/{d} repeat_diff={d}/{d}/{d} capture_repeat_diff={d}\n", .{ + n, du[0], du[1], du[2], dr[0], dr[1], dr[2], capture_repeat_differences, + }); + } + + try device_hidden.download(0, std.mem.sliceAsBytes(device_check)); + const device_input_differences = differences(device_check, hidden); + if (device_input_differences != 0) try errors.add("device input hidden changed in {d} values", .{device_input_differences}); + const host_hidden_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(hidden)), &hidden_sha); + const host_frames_unchanged = std.mem.eql(u8, &sha256Hex(std.mem.sliceAsBytes(&frames)), &frames_sha); + if (!host_hidden_unchanged or !host_frames_unchanged) try errors.add("host fixture changed: hidden unchanged {} frames unchanged {}", .{ host_hidden_unchanged, host_frames_unchanged }); + const used = cuda.usage(false); + + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const tower_source_sha = sha256Hex(tower.trace_source); + const driver_source_sha = sha256Hex(@embedFile("drama_tower_qk_trace.zig")); + const kernel_image_sha = sha256Hex(cuda.kernels.drama_tower); + if (cuda.kernels.drama_tower.len == 0) try errors.add("embedded drama_tower kernel image is empty", .{}); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-qk-trace\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"fixture_directory\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"input_hidden_sha256\": \"{s}\",\n \"input_frames_sha256\": \"{s}\",\n \"layer_count\": {d}," ++ + "\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"prefix_rows\": {d},\n \"prefix_chunks\": [{d}, {d}],\n \"suffix_rows\": [{d}, {d}, {d}]," ++ + "\n \"captured_stages\": [\"qkv\", \"query\", \"key\", \"value\"]," ++ + "\n \"rope_launch\": \"drama_rope_cache(qkv, qnorm, knorm, queries, keys, values, start = position, 16, 2, 256, 64, rope_base, eps), grid rows * 18, block 256\"," ++ + "\n \"row_mapping\": \"capture row j is fixture row 181 + j at position 181 + j; qkv in checkpoint order [query 16x256 | gate 16x256 | key 2x256 | value 2x256]\"," ++ + "\n \"cases\": [{s}\n ]," ++ + "\n \"input_immutable\": {{\"device_hidden_differences\": {d}, \"host_hidden_unchanged\": {}, \"host_frames_unchanged\": {}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}}}," ++ + "\n \"bytes_written\": {d}," ++ + "\n \"binary_sha256\": {s},\n \"tower_source_sha256\": \"{s}\",\n \"driver_source_sha256\": \"{s}\",\n \"tower_kernel_image_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + hidden_sha[0..], frames_sha[0..], layer_count, context, + max_rows, prefix_rows, prefix_chunks[0], prefix_chunks[1], + row_counts[0], row_counts[1], row_counts[2], cases.items, + device_input_differences, host_hidden_unchanged, host_frames_unchanged, model_usage.device, + used.device, used.peak, used.host, written, + binary_json.items, tower_source_sha[0..], driver_source_sha[0..], kernel_image_sha[0..], + evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("cases={d} bytes_written={d} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d}\n", .{ + row_counts.len, written + manifest.items.len, evidence_valid, errors.count, used.device, used.peak, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/drama_tower_trace.zig b/zig/tests/cuda/drama_tower_trace.zig new file mode 100644 index 00000000000..d031c6d9490 --- /dev/null +++ b/zig/tests/cuda/drama_tower_trace.zig @@ -0,0 +1,477 @@ +//! Diagnostic: captures every stage of every production tower layer on the real-input fixture. +const std = @import("std"); +const builtin = @import("builtin"); +const cuda = @import("cuda"); +const drama = @import("drama"); + +const Allocator = std.mem.Allocator; +const tower = drama.tower; +const Stage = tower.Stage; +const Frame = tower.Frame; +const Impl = @typeInfo(@FieldType(tower.Model, "impl")).pointer.child; + +const width = 2048; +const kv_width = 512; +const vocab = 4096; +const max_rows = 128; +/// tf-drama-tower-oracle's options: the same cuBLASLt plan list and KV cache layout. +const context = 128; +const fixture_frames = max_rows + 1; +const row_counts = [_]usize{ 1, 7, max_rows }; +const variants = [_][]const u8{ "traced", "untraced", "repeat" }; +const projection_count = 6; // tower.zig `projections.len` +const head_kind = 5; // tower.zig `projections[5]` = { 4096, hidden }, the codebook head shape +const head_index = 8; // codebook 9: audio_decoder_mtp.heads.8, the oracle's `p.heads[8]` +const head_plan = (1 - 1) * projection_count + head_kind; // rows = 1, as generate() and the oracle +/// The prefill's own layer array: every layer it iterates is captured. +const layer_count = @typeInfo(@FieldType(Impl, "layers")).array.len; +const stages = std.meta.tags(Stage); +const stage_count = stages.len; +const slots = layer_count * stage_count; +/// shared_input once, then every other stage once per layer. +const capture_count = 1 + layer_count * (stage_count - 1); +const max_stage_width = blk: { + var m: usize = 0; + for (stages) |s| m = @max(m, tower.stageWidth(s)); + break :blk m; +}; + +comptime { + std.debug.assert(layer_count == 13); + std.debug.assert(stages[0] == .shared_input); + std.debug.assert(tower.stageWidth(.output) == width and tower.stageWidth(.key) == kv_width); +} + +/// What each stage file holds, in `tower.zig` terms. +const stage_sources = + \\{"shared_input": "Impl.shared after setInput: drama_frame_embeddings sum of codes 2..9 (layer 0 mix extra input), BF16 [N, 2048]", + \\ "joined": "Impl.joined after drama_mix: [enorm(code embedding (+ shared_input)), hnorm(layer input)], BF16 [N, 4096]", + \\ "mixed": "Impl.mixed after eh_proj (projection 0), BF16 [N, 2048]", + \\ "attention_input": "Impl.normalized after drama_norm(mixed, input_norm), BF16 [N, 2048]", + \\ "qkv": "Impl.qkv after wqkv (projection 1), checkpoint column order [query 16x256 | gate 16x256 | key 2x256 | value 2x256], BF16 [N, 9216]", + \\ "query": "Impl.queries after drama_rope_cache: q_norm then interleaved rope on the first 64 dims, BF16 [N, 4096]", + \\ "key": "layer key cache rows position..position+N after drama_rope_cache: k_norm then rope, BF16 [N, 512]", + \\ "value": "layer value cache rows position..position+N after drama_rope_cache: raw qkv value, BF16 [N, 512]", + \\ "attended": "Impl.attended after drama_attention: causal attention times sigmoid(gate), the wo input, BF16 [N, 4096]", + \\ "attention_output": "Impl.branch after wo (projection 2), BF16 [N, 2048]", + \\ "mlp_input": "Impl.normalized after drama_norm(attention_output + mixed, post_norm), BF16 [N, 2048]", + \\ "mlp_residual": "Impl.residual after the same drama_norm: BF16 attention_output + mixed, BF16 [N, 2048]", + \\ "gate_up": "Impl.gate_up after projection 3: [w1 gate | w3 up], BF16 [N, 12288]", + \\ "activated": "Impl.activated after drama_silu_mul: silu(gate) * up, BF16 [N, 6144]", + \\ "mlp_output": "Impl.branch after w2 (projection 4), BF16 [N, 2048]", + \\ "output": "Impl.output_hidden after drama_norm(mlp_output + mlp_residual, final_norm): layer output, BF16 [N, 2048]"} +; + +/// Recorded failures that leave the files written but the evidence invalid. Messages hold no quote or backslash. +const Errors = struct { + gpa: Allocator, + json: std.ArrayList(u8) = .empty, + count: usize = 0, + + fn add(e: *Errors, comptime f: []const u8, args: anytype) !void { + std.debug.print("error: " ++ f ++ "\n", args); + try e.json.appendSlice(e.gpa, if (e.count == 0) "\n \"" else ",\n \""); + try e.json.print(e.gpa, f, args); + try e.json.append(e.gpa, '"'); + e.count += 1; + } +}; + +const Slot = struct { layer: usize, stage: Stage }; + +/// The k-th capture of one prefill, in execution order. +fn expectedSlot(k: usize) Slot { + if (k == 0) return .{ .layer = 0, .stage = .shared_input }; + return .{ .layer = (k - 1) / (stage_count - 1), .stage = stages[1 + (k - 1) % (stage_count - 1)] }; +} + +fn slotOf(layer: usize, stage: Stage) usize { + return layer * stage_count + @backingInt(stage); +} + +fn stageFile(buffer: []u8, n: usize, layer: usize, stage: Stage) ![]u8 { + return std.fmt.bufPrint(buffer, "native-{d}-layer-{d:0>2}-{s}.bf16", .{ n, layer, @tagName(stage) }); +} + +/// The `drama.tower.Model.prefillTraced` tracer for one run of N rows. +const Tracer = struct { + io: std.Io, + dir: std.Io.Dir, + n: usize, + /// Pinned, max_rows * max_stage_width * 2 bytes: the target of the stream-ordered copy. + staging: []align(16) u8, + /// null: the first traced run, which writes every capture. Otherwise that run's hashes, compared instead. + first: ?*const [slots][32]u8, + hashes: [slots][32]u8 = undefined, + nonfinite: [slots]usize = @splat(0), + captures: usize = 0, + repeat_mismatches: usize = 0, + written: usize = 0, + + pub fn capture(t: *Tracer, stream: cuda.Stream, layer: usize, stage: Stage, src: cuda.DeviceBuffer, row0: usize) !void { + if (t.captures >= capture_count) return error.TraceTooManyCaptures; + const want = expectedSlot(t.captures); + if (layer != want.layer or stage != want.stage) return error.TraceCaptureOutOfOrder; + if (row0 != 0) return error.TraceRowsOutOfRange; + const len = t.n * tower.stageWidth(stage) * 2; + if (src.len != len or len > t.staging.len) return error.TraceCaptureShape; + // Queued behind the stage's kernel and ahead of the next one, then drained before the prefill continues. + const bytes = t.staging[0..len]; + try src.downloadAsync(0, bytes, stream.handle); + try stream.synchronize(); + const at = slotOf(layer, stage); + std.crypto.hash.sha2.Sha256.hash(bytes, &t.hashes[at], .{}); + t.nonfinite[at] = nonfiniteBf16(std.mem.bytesAsSlice(u16, bytes)); + if (t.first) |first| { + if (!std.mem.eql(u8, &first[at], &t.hashes[at])) t.repeat_mismatches += 1; + } else { + var name_buffer: [80]u8 = undefined; + const name = try stageFile(&name_buffer, t.n, layer, stage); + try t.dir.writeFile(t.io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + t.written += bytes.len; + } + t.captures += 1; + } +}; + +/// One run's outputs, sized for max_rows; a case uses the first n rows. +const Finals = struct { + hidden: []u16, + head: []u16, + /// [layer][keys, values][n][kv_width] + kv: []u16, + + fn alloc(gpa: Allocator) !Finals { + const hidden = try gpa.alloc(u16, max_rows * width); + errdefer gpa.free(hidden); + const head = try gpa.alloc(u16, vocab); + errdefer gpa.free(head); + return .{ .hidden = hidden, .head = head, .kv = try gpa.alloc(u16, layer_count * 2 * max_rows * kv_width) }; + } + + fn free(f: Finals, gpa: Allocator) void { + gpa.free(f.hidden); + gpa.free(f.head); + gpa.free(f.kv); + } + + fn kvRows(f: Finals, n: usize, layer: usize, which: usize) []u16 { + const at = (layer * 2 + which) * n * kv_width; + return f.kv[at .. at + n * kv_width]; + } +}; + +fn view(buffer: cuda.DeviceBuffer, offset: usize, len: usize) cuda.DeviceBuffer { + std.debug.assert(offset <= buffer.len and len <= buffer.len - offset); + return .{ .d = buffer.d, .ptr = buffer.ptr + offset, .len = len, .borrowed = true }; +} + +/// The oracle's teacher-forced call, then its final hidden, head and KV exports. `trace` void: production prefill. +fn runCase(model: *tower.Model, stream: cuda.Stream, n: usize, hidden: cuda.DeviceBuffer, frames: []const Frame, trace: anytype, f: Finals) !void { + try model.reset(stream, &.{}, 0); + _ = try model.setInput(stream, frames[0..n]); + if (@TypeOf(trace) == void) + try model.prefill(stream, view(hidden, 0, n * width * 2), frames[1 .. n + 1]) + else + try model.prefillTraced(stream, view(hidden, 0, n * width * 2), frames[1 .. n + 1], trace); + const p = model.impl; + try p.output_hidden.download(0, std.mem.sliceAsBytes(f.hidden[0 .. n * width])); + // 0xffff is a BF16 NaN: a head that writes nothing cannot pass. Same plan, weights and row as the oracle. + try p.head_logits.fill8(0xff, stream.handle); + try p.plans.items[head_plan].run(p.output_hidden.ptr + (n - 1) * width * 2, p.heads[head_index].ptr, p.head_logits.ptr, p.workspace.ptr, p.workspace.len, stream.handle); + try stream.synchronize(); + try p.head_logits.download(0, std.mem.sliceAsBytes(f.head)); + for (0..layer_count) |layer| for (0..2) |which| { + try p.cache.download((layer * 2 + which) * context * kv_width * 2, std.mem.sliceAsBytes(f.kvRows(n, layer, which))); + }; +} + +fn differences(a: []const u16, b: []const u16) usize { + var count: usize = 0; + for (a, b) |x, y| { + if (x != y) count += 1; + } + return count; +} + +const Diff = struct { hidden: usize, head9: usize, kv: usize }; + +fn compareFinals(n: usize, a: Finals, b: Finals) Diff { + return .{ + .hidden = differences(a.hidden[0 .. n * width], b.hidden[0 .. n * width]), + .head9 = differences(a.head, b.head), + .kv = differences(a.kv[0 .. layer_count * 2 * n * kv_width], b.kv[0 .. layer_count * 2 * n * kv_width]), + }; +} + +fn nonfiniteBf16(values: []const u16) usize { + var count: usize = 0; + for (values) |bits| { + if ((bits & 0x7f80) == 0x7f80) count += 1; + } + return count; +} + +fn sha256Hex(bytes: []const u8) [64]u8 { + var out: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &out, .{}); + return std.fmt.bytesToHex(out, .lower); +} + +fn fileSha256(gpa: Allocator, io: std.Io, path: []const u8) ![64]u8 { + const file = try std.Io.Dir.openFileAbsolute(io, path, .{}); + defer file.close(io); + const buffer = try gpa.alloc(u8, 1 << 20); + defer gpa.free(buffer); + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + var offset: u64 = 0; + while (true) { + const got = try file.readPositionalAll(io, buffer, offset); + hash.update(buffer[0..got]); + offset += got; + if (got < buffer.len) break; + } + return std.fmt.bytesToHex(hash.finalResult(), .lower); +} + +fn readExact(io: std.Io, dir: std.Io.Dir, name: []const u8, bytes: []u8) !void { + const file = try dir.openFile(io, name, .{}); + defer file.close(io); + if (try file.length(io) != bytes.len or try file.readPositionalAll(io, bytes, 0) != bytes.len) return error.BadFixtureLength; +} + +fn jsonString(list: *std.ArrayList(u8), gpa: Allocator, s: []const u8) !void { + try list.append(gpa, '"'); + for (s) |c| switch (c) { + '"', '\\' => { + try list.append(gpa, '\\'); + try list.append(gpa, c); + }, + 0...0x1f => try list.print(gpa, "\\u{x:0>4}", .{c}), + else => try list.append(gpa, c), + }; + try list.append(gpa, '"'); +} + +/// Writes one run's final outputs as new files and appends their manifest entries. +fn emitFinals(gpa: Allocator, io: std.Io, dir: std.Io.Dir, json: *std.ArrayList(u8), n: usize, variant: []const u8, f: Finals, errors: *Errors) !usize { + var name_buffer: [96]u8 = undefined; + var written: usize = 0; + try json.print(gpa, "\"{s}\": {{", .{variant}); + const singles = [_]struct { kind: []const u8, data: []const u16, cols: usize, rows: usize }{ + .{ .kind = "hidden", .data = f.hidden[0 .. n * width], .cols = width, .rows = n }, + .{ .kind = "head9", .data = f.head, .cols = vocab, .rows = 1 }, + }; + for (singles) |s| { + const name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-{s}.bf16", .{ n, variant, s.kind }); + const bytes = std.mem.sliceAsBytes(s.data); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + written += bytes.len; + const bad = nonfiniteBf16(s.data); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "\"{s}\": {{\"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}}}, ", .{ s.kind, name, sha[0..], s.rows, s.cols, bad }); + } + try json.appendSlice(gpa, "\"kv\": ["); + for (0..layer_count) |layer| for ([_][]const u8{ "keys", "values" }, 0..) |kind, which| { + const rows = f.kvRows(n, layer, which); + const name = try std.fmt.bufPrint(&name_buffer, "native-{d}-{s}-layer-{d:0>2}-{s}.bf16", .{ n, variant, layer, kind }); + const bytes = std.mem.sliceAsBytes(rows); + try dir.writeFile(io, .{ .sub_path = name, .data = bytes, .flags = .{ .exclusive = true } }); + written += bytes.len; + const bad = nonfiniteBf16(rows); + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const sha = sha256Hex(bytes); + try json.print(gpa, "{s}{{\"layer\": {d}, \"kind\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"nonfinite\": {d}}}", .{ + if (layer == 0 and which == 0) "" else ", ", layer, kind, name, sha[0..], n, kv_width, bad, + }); + }; + try json.appendSlice(gpa, "]}"); + return written; +} + +fn seconds(ns: anytype) f64 { + return @as(f64, @floatFromInt(ns)) / 1e9; +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 4) { + std.debug.print("usage: tf-drama-tower-trace CHECKPOINT INPUT_DIRECTORY OUTPUT_DIRECTORY\n", .{}); + return 2; + } + if (builtin.cpu.arch.endian() != .little) return error.UnsupportedHostEndian; + const input = try std.Io.Dir.cwd().openDir(io, args[2], .{}); + defer input.close(io); + const out = try std.Io.Dir.cwd().openDir(io, args[3], .{}); + defer out.close(io); + + // Every input is read before any CUDA call, so a missing or short fixture never touches the device. + const hidden = try gpa.alloc(u16, max_rows * width); + defer gpa.free(hidden); + var frames: [fixture_frames]Frame = undefined; + try readExact(io, input, "hidden.bf16", std.mem.sliceAsBytes(hidden)); + try readExact(io, input, "frames.u32le", std.mem.sliceAsBytes(&frames)); + const hidden_sha = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha = sha256Hex(std.mem.sliceAsBytes(&frames)); + for (hidden) |bits| if ((bits & 0x7f80) == 0x7f80) return error.NonfiniteFixtureHidden; + + var finals: [variants.len]Finals = undefined; + var allocated: usize = 0; + defer { + for (finals[0..allocated]) |f| f.free(gpa); + } + for (&finals) |*f| { + f.* = try Finals.alloc(gpa); + allocated += 1; + } + const device_check = try gpa.alloc(u16, max_rows * width); + defer gpa.free(device_check); + + var errors: Errors = .{ .gpa = gpa }; + defer errors.json.deinit(gpa); + + _ = try cuda.setAllocationLimit(54 * (1 << 30)); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + // Same options as drama_tower_oracle.zig, so the plan list, weights, cache layout and buffers are the ones it ran. + var model = try tower.Model.init(gpa, io, &ctx, args[1], "", .{ .context = context, .max_rows = max_rows }); + defer model.deinit(); + const p = model.impl; + if (p.plans.items.len != max_rows * projection_count or p.head_logits.len != vocab * 2 or p.output_hidden.len != max_rows * width * 2 or + p.cache.len != layer_count * 2 * context * kv_width * 2) return error.UnexpectedTowerLayout; + const model_usage = cuda.usage(false); + var device_hidden = try cuda.DeviceBuffer.alloc(&driver, max_rows * width * 2); + defer device_hidden.free(); + try device_hidden.upload(0, std.mem.sliceAsBytes(hidden)); + var staging = try cuda.HostBuffer.alloc(&driver, max_rows * max_stage_width * 2); + defer staging.free(); + + var captures: std.ArrayList(u8) = .empty; + defer captures.deinit(gpa); + var cases: std.ArrayList(u8) = .empty; + defer cases.deinit(gpa); + var written: usize = 0; + var total_captures: usize = 0; + var name_buffer: [80]u8 = undefined; + for (row_counts, 0..) |n, case_index| { + var traced: Tracer = .{ .io = io, .dir = out, .n = n, .staging = staging.bytes, .first = null }; + const traced_start = std.Io.Clock.awake.now(io).toNanoseconds(); + try runCase(&model, stream, n, device_hidden, &frames, &traced, finals[0]); + const traced_ns = std.Io.Clock.awake.now(io).toNanoseconds() - traced_start; + const untraced_start = std.Io.Clock.awake.now(io).toNanoseconds(); + try runCase(&model, stream, n, device_hidden, &frames, {}, finals[1]); + const untraced_ns = std.Io.Clock.awake.now(io).toNanoseconds() - untraced_start; + var repeat: Tracer = .{ .io = io, .dir = out, .n = n, .staging = staging.bytes, .first = &traced.hashes }; + try runCase(&model, stream, n, device_hidden, &frames, &repeat, finals[2]); + total_captures += traced.captures + repeat.captures; + written += traced.written; + + for ([_]*const Tracer{ &traced, &repeat }, [_][]const u8{ "traced", "repeat" }) |t, label| { + if (t.captures != capture_count) try errors.add("rows {d} {s}: {d} captures, expected {d}", .{ n, label, t.captures, capture_count }); + } + if (repeat.repeat_mismatches != 0) try errors.add("rows {d}: {d} stage captures differ between traced runs", .{ n, repeat.repeat_mismatches }); + const untraced_diff = compareFinals(n, finals[0], finals[1]); + const repeat_diff = compareFinals(n, finals[0], finals[2]); + for ([_]Diff{ untraced_diff, repeat_diff }, [_][]const u8{ "untraced", "repeat" }) |d, label| { + if (d.hidden != 0 or d.head9 != 0 or d.kv != 0) + try errors.add("rows {d}: traced vs {s} bit differences hidden {d} head9 {d} kv {d}", .{ n, label, d.hidden, d.head9, d.kv }); + } + + for (0..capture_count) |k| { + const slot = expectedSlot(k); + const at = slotOf(slot.layer, slot.stage); + const name = try stageFile(&name_buffer, n, slot.layer, slot.stage); + const bad = traced.nonfinite[at]; + if (bad != 0) try errors.add("{s}: {d} nonfinite values", .{ name, bad }); + const repeat_equal = std.mem.eql(u8, &traced.hashes[at], &repeat.hashes[at]); + const sha = std.fmt.bytesToHex(traced.hashes[at], .lower); + try captures.print(gpa, "{s}\n {{\"rows\": {d}, \"order\": {d}, \"layer\": {d}, \"stage\": \"{s}\", \"file\": \"{s}\", \"sha256\": \"{s}\", \"shape\": [{d}, {d}], \"dtype\": \"bf16le\", \"row0\": 0, \"nonfinite\": {d}, \"repeat_bit_equal\": {}}}", .{ + if (captures.items.len == 0) "" else ",", n, k, slot.layer, @tagName(slot.stage), name, sha[0..], n, tower.stageWidth(slot.stage), bad, repeat_equal, + }); + } + + try cases.print(gpa, "{s}\n {{\"rows\": {d}, \"head_row\": {d}, \"captures_per_run\": {d}, \"stage_repeat_mismatches\": {d}," ++ + " \"traced_vs_untraced_bit_differences\": {{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}}}," ++ + " \"traced_vs_repeat_bit_differences\": {{\"hidden\": {d}, \"head9\": {d}, \"kv\": {d}}}," ++ + " \"timing_s\": {{\"traced\": {d:.6}, \"untraced\": {d:.6}}}, \"finals\": {{", .{ + if (case_index == 0) "" else ",", n, n - 1, capture_count, repeat.repeat_mismatches, + untraced_diff.hidden, untraced_diff.head9, untraced_diff.kv, repeat_diff.hidden, repeat_diff.head9, + repeat_diff.kv, seconds(traced_ns), seconds(untraced_ns), + }); + for (variants, finals, 0..) |variant, f, i| { + if (i != 0) try cases.appendSlice(gpa, ", "); + written += try emitFinals(gpa, io, out, &cases, n, variant, f, &errors); + } + try cases.appendSlice(gpa, "}}"); + std.debug.print("tower_rows={d} captures={d} traced_untraced_hidden_diff={d} head9_diff={d} kv_diff={d} repeat_hidden_diff={d} stage_repeat_mismatches={d}\n", .{ + n, traced.captures, untraced_diff.hidden, untraced_diff.head9, untraced_diff.kv, repeat_diff.hidden, repeat.repeat_mismatches, + }); + } + + // Input immutability: the device rows every case read, and the host fixture bytes, are what was loaded. + try device_hidden.download(0, std.mem.sliceAsBytes(device_check)); + const device_input_differences = differences(device_check, hidden); + if (device_input_differences != 0) try errors.add("device input hidden changed in {d} values", .{device_input_differences}); + const hidden_sha_after = sha256Hex(std.mem.sliceAsBytes(hidden)); + const frames_sha_after = sha256Hex(std.mem.sliceAsBytes(&frames)); + const host_hidden_unchanged = std.mem.eql(u8, &hidden_sha_after, &hidden_sha); + const host_frames_unchanged = std.mem.eql(u8, &frames_sha_after, &frames_sha); + if (!host_hidden_unchanged or !host_frames_unchanged) try errors.add("host fixture changed: hidden unchanged {} frames unchanged {}", .{ host_hidden_unchanged, host_frames_unchanged }); + const used = cuda.usage(false); + + var binary_json: std.ArrayList(u8) = .empty; + defer binary_json.deinit(gpa); + if (fileSha256(gpa, io, "/proc/self/exe")) |sha| { + try binary_json.print(gpa, "\"{s}\"", .{sha[0..]}); + } else |err| { + std.debug.print("binary hash unavailable: {s}\n", .{@errorName(err)}); + try binary_json.appendSlice(gpa, "null"); + } + const tower_source_sha = sha256Hex(tower.trace_source); + const trace_source_sha = sha256Hex(@embedFile("drama_tower_trace.zig")); + const kernel_image_sha = sha256Hex(cuda.kernels.drama_tower); + if (cuda.kernels.drama_tower.len == 0) try errors.add("embedded drama_tower kernel image is empty", .{}); + const evidence_valid = errors.count == 0; + + var manifest: std.ArrayList(u8) = .empty; + defer manifest.deinit(gpa); + try manifest.appendSlice(gpa, "{\n \"schema_version\": 1,\n \"producer\": \"tf-drama-tower-trace\",\n \"checkpoint\": "); + try jsonString(&manifest, gpa, args[1]); + try manifest.appendSlice(gpa, ",\n \"input_directory\": "); + try jsonString(&manifest, gpa, args[2]); + try manifest.print(gpa, ",\n \"input_hidden_sha256\": \"{s}\",\n \"input_frames_sha256\": \"{s}\",\n \"width\": {d},\n \"dtype\": \"bf16le\",\n \"layer_count\": {d}," ++ + "\n \"rows\": [{d}, {d}, {d}],\n \"model_options\": {{\"context\": {d}, \"max_rows\": {d}}},\n \"stage_order\": [", .{ + hidden_sha[0..], frames_sha[0..], width, layer_count, row_counts[0], row_counts[1], row_counts[2], context, max_rows, + }); + for (stages, 0..) |stage, i| try manifest.print(gpa, "{s}\"{s}\"", .{ if (i == 0) "" else ", ", @tagName(stage) }); + try manifest.appendSlice(gpa, "],\n \"stage_widths\": {"); + for (stages, 0..) |stage, i| try manifest.print(gpa, "{s}\"{s}\": {d}", .{ if (i == 0) "" else ", ", @tagName(stage), tower.stageWidth(stage) }); + try manifest.print(gpa, "}},\n \"stage_sources\": {s},\n \"capture_order\": \"shared_input (layer 0) once, then the remaining stages in stage_order for layers 0..12; enforced\"," ++ + "\n \"row_mapping\": \"row r of every capture and final is request position r (reset position 0; prefill rows 0..N-1, labels frames[r+1]); KV rows are cache positions 0..N-1\"," ++ + "\n \"head\": {{\"weight\": \"audio_decoder_mtp.heads.{d}.weight\", \"plan\": \"plans[{d}] (rows 1, kind {d})\", \"input\": \"layer 12 output row N-1\"}}," ++ + "\n \"captures\": [{s}\n ],\n \"cases\": [{s}\n ]," ++ + "\n \"input_immutable\": {{\"device_hidden_differences\": {d}, \"host_hidden_unchanged\": {}, \"host_frames_unchanged\": {}}}," ++ + "\n \"allocations\": {{\"cuda_device_bytes_after_init\": {d}, \"cuda_device_bytes\": {d}, \"cuda_device_peak_bytes\": {d}, \"pinned_host_bytes\": {d}, \"trace_staging_pinned_bytes\": {d}}}," ++ + "\n \"bytes_written\": {d},\n \"total_captures\": {d}," ++ + "\n \"binary_sha256\": {s},\n \"tower_source_sha256\": \"{s}\",\n \"trace_source_sha256\": \"{s}\",\n \"tower_kernel_image_sha256\": \"{s}\"," ++ + "\n \"evidence_valid\": {},\n \"errors\": [{s}\n ]\n}}\n", .{ + stage_sources, head_index, head_plan, head_kind, + captures.items, cases.items, device_input_differences, host_hidden_unchanged, + host_frames_unchanged, model_usage.device, used.device, used.peak, + used.host, staging.bytes.len, written, total_captures, + binary_json.items, tower_source_sha[0..], trace_source_sha[0..], kernel_image_sha[0..], + evidence_valid, errors.json.items, + }); + try out.writeFile(io, .{ .sub_path = "manifest.json", .data = manifest.items, .flags = .{ .exclusive = true } }); + std.debug.print("cases={d} captures={d} bytes_written={d} evidence_valid={} errors={d} cuda_bytes={d} cuda_peak={d} pinned_bytes={d}\n", .{ + row_counts.len, total_captures, written + manifest.items.len, evidence_valid, errors.count, used.device, used.peak, used.host, + }); + return if (evidence_valid) 0 else 3; +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index fe98682c867..d6b8c4e1260 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -31,6 +31,8 @@ const norms_tests = @import("norms_tests.zig"); const norm_rows_tests = @import("norm_rows_tests.zig"); const pocket_tests = @import("pocket_tests.zig"); const recapture_tests = @import("recapture_tests.zig"); +const drama_conv_tests = @import("drama_conv_tests.zig"); +const drama_qk_tests = @import("drama_qk_tests.zig"); const contract_tests = @import("contract_tests.zig"); const lfm2_attention_tests = @import("lfm2_attention_tests.zig"); const lfm2_kernel_tests = @import("lfm2_kernel_tests.zig"); @@ -59,6 +61,8 @@ const usage = \\ triton a Triton cubin's bits against the Python oracle's fixture \\ norms RMS norm and the residual step against float64 references (synthetic) \\ norm-rows bf16-residual and gated norms, token rows against float64 (synthetic) + \\ drama-conv phase-specific causal convolution, history and chunk boundaries (synthetic) + \\ drama-qk Q/K norm and rotary precision, positions and cache bounds (synthetic) \\ sample sample.cu's keyed draws against the Metal rule's host references (synthetic rows) \\ glue Nemotron's glue kernels against their host references at its shapes (synthetic rows) \\ lfm2-kernels LFM2's glue kernels against their host references at d1's shapes (synthetic rows) @@ -164,6 +168,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "sample")) return sample_tests.draws(gpu); if (std.mem.eql(u8, cmd, "norms")) return norms_tests.run(gpu); if (std.mem.eql(u8, cmd, "norm-rows")) return norm_rows_tests.run(gpu); + if (std.mem.eql(u8, cmd, "drama-conv")) return drama_conv_tests.run(gpu); + if (std.mem.eql(u8, cmd, "drama-qk")) return drama_qk_tests.run(gpu); if (std.mem.eql(u8, cmd, "glue")) return glue_tests.run(gpu); if (std.mem.eql(u8, cmd, "lfm2-kernels")) return lfm2_kernel_tests.run(gpu); if (std.mem.eql(u8, cmd, "pocket")) diff --git a/zig/tests/qwen27/dflash_served.zig b/zig/tests/qwen27/dflash_served.zig index ca9b3c2bfba..b1e836a01e9 100644 --- a/zig/tests/qwen27/dflash_served.zig +++ b/zig/tests/qwen27/dflash_served.zig @@ -48,7 +48,7 @@ const Box = struct { defer b.mutex.unlock(b.io); switch (value.*) { .prefilled => {}, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |ids| { b.tokens.appendSlice(b.a, ids) catch {}; if (b.cancel_after) |count| if (b.tokens.items.len >= count) if (b.engine) |engine| engine.cancel(b.id); diff --git a/zig/tests/qwen27/reuse.zig b/zig/tests/qwen27/reuse.zig index 46ce1ed90d3..f8aeee22fb1 100644 --- a/zig/tests/qwen27/reuse.zig +++ b/zig/tests/qwen27/reuse.zig @@ -20,7 +20,7 @@ const Box = struct { defer b.mutex.unlock(b.io); switch (value.*) { .prefilled => |n| b.cached = n, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |got| b.tokens.appendSlice(b.a, got) catch {}, .finished => |f| { b.done = f.reason; diff --git a/zig/tests/qwen27/served.zig b/zig/tests/qwen27/served.zig index 10f984398ab..858dabf5a3c 100644 --- a/zig/tests/qwen27/served.zig +++ b/zig/tests/qwen27/served.zig @@ -18,7 +18,7 @@ const Box = struct { defer b.mutex.unlock(b.io); switch (value.*) { .prefilled => {}, - .logprobs, .prompt_logprobs => {}, + .logprobs, .prompt_logprobs, .audio => {}, .tokens => |ids| b.tokens.appendSlice(b.a, ids) catch {}, .finished => |f| { b.done = f.reason;