diff --git a/build.zig b/build.zig index 380a38b3ded..2dc88bb8a03 100644 --- a/build.zig +++ b/build.zig @@ -18,6 +18,7 @@ const server_build = @import("zig/build/server.zig"); const golden_build = @import("zig/build/golden.zig"); const contract_build = @import("zig/build/kernel_contract.zig"); const video_build = @import("zig/build/video.zig"); +const music3_metal_build = @import("zig/build/music3_metal.zig"); comptime { const required = std.mem.trim(u8, @embedFile(".zig-version"), "\r\n"); @@ -341,6 +342,9 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b b.step(p.name, p.about).dependOn(&b.addInstallArtifact(exe, .{}).step); } + // MiniMax Music 3: its metallib, the family over Metal and music3-generate + music3_metal_build.targets(b, target, optimize, metal, metal_std, test_step); + // Kimi's tiktoken tokenizer and its parity program (tools/zig/k3_tokenizer_parity.py). const tiktoken = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tiktoken.zig"), .target = target, .optimize = optimize }); const tok_mod = b.createModule(.{ diff --git a/docs/recipes/README.md b/docs/recipes/README.md index a635ce96027..9d8eeee004a 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -17,6 +17,8 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Gemma 4 26B-A4B | [MLX, fused one-row decode](gemma-4.md) | | DeepSeek-V4-Flash | [MLX on a 256 GB Mac, DSpark and MTP drafts](deepseek-v4-flash.md) | | Qwen3.6-35B-A3B | [MLX with MTP drafts, one-GPU CUDA](qwen3.6-moe.md) | +| MiniMax Music 3 (MiniMax-Music3) | [Lyrics and a caption to a song on one CUDA GPU (GB10)](minimax-music3-cuda.md) | +| MiniMax Music 3 (MiniMax-Music3) | [Lyrics and a caption to a song on Metal (Apple M5)](minimax-music3-metal.md) | ## Capability floor diff --git a/docs/recipes/minimax-music3-cuda.md b/docs/recipes/minimax-music3-cuda.md new file mode 100644 index 00000000000..78ba0c59298 --- /dev/null +++ b/docs/recipes/minimax-music3-cuda.md @@ -0,0 +1,225 @@ +# MiniMax Music 3 on one CUDA GPU (DGX Spark GB10) + +`music3-generate` runs MiniMax Music 3 (MiniMax-Music3, Comfy-Org's single-file checkpoints) on one CUDA GPU: the +autoregressive LM with its depth decoder, the flow-matching DiT and the DAV decoder, in Zig over the CUDA runtime with +kernels of its own (`zig/kernels/cuda/music3.cu`). It speaks the `--serve` protocol of our Mac MLX engine (branch +`music3-mlx` on the drowzeys fork, not part of this tree), so the Wasserman Slate AI Studio's `app/music.py` +([#941](https://github.com/ashhart/TensorFold/issues/941)) can drive either one. + +No weights are included. MiniMax-Music3 is released under the MiniMax-Music3 Community License: a commercial product +must display "MiniMax-Music3" in its interface, use by a business above $20M in yearly revenue needs MiniMax's +written authorization, and a hosted service must keep the license's safeguards in place. + +## Plan, written before building (ceilings and the odds of each lever) + +Baseline (ComfyUI 5a665890's native nodes driven by the Studio, on the same GB10): a 60 s song in 289 s = AR 176 s (about 9 +frames/s; a second of song is 25 frames) + DiT 96 s (30 Euler steps, CFG 1.7) + DAV 4 s, 29.3 GB. The Mac MLX engine (M5 Ultra) +does it in 75.8 s (AR 37.8 s at 40 frames/s, DiT 34.6 s). + +What a frame reads. The AR body is a Qwen3-8B (36 layers, width 4096, GQA 32/8, MLP 12288): 6.95 G params, 13.9 GB +in bf16, read once a frame for both CFG rows together (batched). The depth decoder (4 layers, width 4096, 16 heads of +256, MLP 6144, a 4096x4096 input projection, 7 heads of 1024) is 0.59 G params, 1.17 GB, read 7 times a frame (the +first pass holds two positions, the next six one each): 8.2 GB. lm_head (16385 x 4096) 0.13 GB. About 22.2 GB a +frame in bf16; the body's KV cache adds 0.3 MB a context position (both rows, 36 layers), 0.6 GB a frame at 2,000 +positions. + +Ceilings at GB10's ~273 GB/s (to be replaced by the measured GEMV bandwidth below): + +| AR weights | bytes a frame | ceiling frames/s | 60 s song (1,500 frames) | P(reach >= 80% of ceiling) | +| --- | --- | --- | --- | --- | +| bf16 | 22.2 GB | 12.3 | 122 s | 0.8 | +| int8 weight-only, per-output-channel scales | 11.1 GB | 24.6 | 61 s | 0.7 | +| fp8 e4m3 weight-only | 11.1 GB | 24.6 | 61 s | 0.5 (same bytes as int8, more quality risk, no gain over int8) | +| int4 / NVFP4 weight-only | 5.6 GB | 49 | 31 s | 0.3 for quality equal to bf16 | + +ComfyUI's 9 frames/s is already ~70% of the bf16 ceiling, so a bf16 port alone wins at most ~1.3x on AR. The lever is +bytes: int8 weight-only halves them, and per-channel symmetric int8 of an 8B transformer is close to lossless (P(quality +equal to bf16 by the checks) ~0.8). Plan: int8 GEMV with the scale applied once per output row (no dequant in the +inner loop: the sum of int8 x bf16 products in fp32, times the row's scale), CFG rows batched, then CUDA graphs. + +Launch overhead. A frame is 36 body layers + 7 x 4 depth layers + norms, attention, samplers: ~550 launches. At +~4 us each eager that is ~2 ms a frame (5% of a 40 ms frame); the frame step is captured once as a CUDA graph +(P(success) 0.9; it worked for Drama 3). Codes are drawn on the device (top-k CFG sampler), the stop code checked +every few frames on the host, so the GPU never waits for the host. + +DiT. 2.42 G params, 36 blocks of width 2048 (32 heads of 64, MLP 8192), windows of 689 latent frames (200 AR frames) +every 344, CFG cond + uncond batched. A 60 s song is 5,168 latent frames = 14 windows, so a step is 14 x 2 x 690 = +19,320 tokens: 2 x 2.42 G x 19,320 = 94 TFLOP of GEMMs + ~4 TFLOP of attention a step, 2.9 PFLOP for 30 steps. +GB10's dense fp16 tensor rate with fp32 accumulation is ~100 TFLOP/s nominal; at 70% of it the DiT is ~41 s, at the +Mac's pace 35 s. ComfyUI's 96 s is ~30 TFLOP/s achieved, so there is ~2x of headroom from cuBLASLt fp16 GEMMs (fp32 +accumulation) with fused epilogues and a proper attention (P(DiT <= 45 s) 0.6). flex_attention is wrong on sm_121 and +not used: attention here is cuBLAS batched GEMMs (QK^T in fp32, a softmax kernel, PV) or our own kernel. int8 tensor +cores (the H3 products) would double the GEMM rate again but are a quality risk; tried only if fp16 lands short. + +DAV. ~4 s in ComfyUI; fp32 convolutions as im2col + cuBLAS SGEMM (TF32 off), in chunks with halo. Not a lever. + +Target. 60 s song <= ~120 s on one GB10: AR int8 ~65-80 s + DiT ~40 s + DAV ~4 s + load. Reachable only with int8 +AR and a DiT near 70% of the fp16 tensor rate; with bf16 AR the AR alone is >= 122 s, so the target is out of reach +in bf16 by construction. + +Measured on an idle GB10 before building (`gemv_bench`, weights rotated through a 2 GB pool so L2 never holds +them): a plain read reaches 230 GB/s; a warp-a-row GEMV with two activation rows reaches 220 to 240 GB/s in bf16 and +in int8 alike; cuBLAS fp16 GEMMs with fp32 accumulation at the DiT's shapes (19,320 tokens) reach 96 to 104 +TFLOP/s. So the real ceilings are 10.4 frames/s in bf16 and 20.7 frames/s in int8 (60 s of song: 145 s and 73 s of +AR), and the DiT's GEMMs alone are about 29 s for 60 s of song. + +## What was built + +| Stage | How | Notes | +| --- | --- | --- | +| Prompt | `prompt.zig`: ComfyUI's `prompt.py` regular expressions by hand, the checkpoint's own `tokenizer_json` through the core tokenizer | 10 of 10 cases equal to ComfyUI's ids, markdown, `<\|tag\|>` markers, `^`, CRLF and non-ASCII among them | +| AR prompt | both CFG rows (conditional, unconditional) through the body in cuBLAS bf16 GEMMs; int8 weights are dequantized a layer at a time for it | split-key attention kernel | +| AR frame | one CUDA graph: lm_head GEMV, the CFG top-k draw on the device, the depth decoder's 7 passes (first pass M = 4), the frame's 8 x 4096 states written for the DiT, the frame fed back through 36 layers (M = 2) | GEMVs are warp-a-row with the weights' first loads in flight before `griddepcontrol.wait` (PDL); gate/up GEMVs write the SwiGLU directly (rows n and N/2 + n in one warp); the host reads the drawn tokens every 16 frames for the stop code | +| int8 | weight-only, symmetric, quantized on the GPU at load; body and lm_head one fp32 scale a row, depth decoder and its heads one scale a group of 128 inputs (`--int8-group 0` for a row) | no cache file needed: quantizing is part of the load | +| DiT | windows of 689 latent rows every 344 (as ComfyUI), up to 16 windows x both CFG branches in one forward; cuBLASLt fp16 GEMMs (fp32 compute) with each shape's algorithm timed once; our flash attention (mma.sync m16n8k16, rope applied as q and k load); biases folded into the GLU and the next LayerNorm, so no GEMM carries an epilogue (the bias + accumulate epilogue picked 14 TFLOP/s kernels at some shapes) | rope angles rounded to fp16 before cos / sin, as ComfyUI does (`--comfy-rope 0` for fp32 angles) | +| DAV | fp32, every conv as one SGEMM a tap over time-major rows with zero halos (no TF32), transposed convs as one SGEMM and an overlap-add; chunks of 512 latent rows with 32 rows of context; ComfyUI's level rule (divide by max(1, 5 std)) | `--dav-tf32 1`: 66.8 dB against ComfyUI, 14% faster | + +## Build and run + + zig build music3-generate -Doptimize=ReleaseFast -Dnvcc=/usr/local/cuda/bin/nvcc + ./zig-out/bin/music3-generate --caption-file style.txt --lyrics-file lyrics.txt --seconds 60 --seed 7 \ + --out song.wav --stats song.json # int8 (default); --weights bf16 for the checkpoint's own + ./zig-out/bin/music3-generate --serve 1 # the MLX port's protocol, below + ./zig-out/bin/music3-generate --ids --caption-file style.txt --lyrics-file lyrics.txt # prompt ids, no GPU + +`--model DIR` (or `$TF_MUSIC3_MODEL`) is required: the folder holding Comfy-Org's three MiniMax-Music3 files, read as +they are. Run it under a MemAvailable kill-guard on a Spark (`tools/music3` has none of its own; the Studio's +`voice.Served` client has one). + +### --serve + +The Mac engine's protocol, line for line: one JSON line on stderr when loaded, +`{"ready":true,"engine":"tensorfold-music3-cuda","load_s":..,"sample_rate":44100,"channels":2,"license_display":"MiniMax-Music3","weights":"int8"}`; +then one request a line on stdin, `{id, caption, lyrics | lyrics_file, wav, seconds, seed, ar_cfg, top_k, steps, +dit_cfg, stats, progress}`, and one answer a line on stderr, `{ok, id, wav, audio_s, frames, eos, ar_ms, dit_ms, dav_ms, +total_ms, rtf, first_audio_ms, stream, seed, peak_memory_gb}` (`{ok:false, error, id}` on a failure, `{"ok":false, +"error":"bad json"}` for a bad line). `"progress": true` adds `{"id":..,"progress":{"stage":"ar"|"dit"|"dav","done":n,"total":m}}` +lines, at most one a second a stage. `"stats"` names a JSON file of the request's timings. Log lines never start with +`{`. The engine ends at the end of stdin. + +Checked with the Studio's own client (`tools/music3/served_test.py`): app/music.py's `Mlx` route (Studio main +86ae680) with `argv()` pointed at `music3-generate --serve 1` loaded the engine (37.3 s), answered two songs in a row +(20 s and 15 s), passed progress lines through, wrote the stats files, and unloaded on `stop`. + +## Parity against ComfyUI (same GB10) + +The reference is ComfyUI 5a665890's native MiniMax Music 3 nodes on the same GB10 (`--disable-cuda-graphs` so +forward hooks see every frame): hiphop bench prompt, 30 s, seed 7. ComfyUI ran the text encoder in bf16, the DiT in +fp16 and the DAV in fp32 on cuda:0. The dumping harness is a ComfyUI custom node and is not part of this tree (ComfyUI +is GPL-3); see [Reproduce the receipts](#reproduce-the-receipts) for what it records. Then `music3-generate --parity-ar / --parity-probe / +--parity-dit / --parity-dav REF --out MINE` and `python tools/music3/parity.py REF MINE` (numpy only). The tables' +JSON is in [minimax-music3-cuda/](minimax-music3-cuda/), beside the Mac MLX engine's own (`parity_mlx_mac.json`, against +ComfyUI on MPS). + +| Check | CUDA bf16 | CUDA int8 (default) | int8, a scale a row everywhere | Mac MLX engine (bf16) | +| --- | --- | --- | --- | --- | +| prompt ids equal | yes (and 10/10 ids cases) | yes | yes | yes | +| frame states cos, mean / min | 0.999956 / 0.999556 | 0.999827 / 0.998345 | 0.999519 / 0.99816 | 0.999951 / 0.999821 | +| code-0 logits cos (cond), mean / min | 0.999977 / 0.999807 | 0.999897 / 0.997585 | 0.999897 | 0.999973 / 0.999724 | +| code-0 greedy agreement, cond / guided | 0.9747 / 0.9614 | 0.9667 / 0.9561 | 0.9667 / 0.9561 | 0.9774 / 0.964 | +| code-0 top-50 overlap | 0.9854 | 0.9799 | 0.9799 | 0.9872 | +| ComfyUI's drawn code, median rank in ours | 1 | 1 | 1 | 1 | +| depth logits cos, codebook 1..7 | 0.999957 to 0.999966 | 0.99978 to 0.99984 | 0.99913 to 0.99947 | 0.99993 to 0.99996 | +| depth greedy agreement, codebook 1..7 | 0.964 to 0.981 | 0.945 to 0.967 | 0.908 to 0.937 | 0.951 to 0.983 | +| DiT probe cos (cond / uncond), sigma 1.0 | 0.999991 / 0.999994 | (the DiT is fp16 in both) | | 0.99999 / 0.999998 | +| DiT probe cos, sigma 0.5 | 0.999958 / 0.999961 | | | 0.999971 / 0.999977 | +| DiT probe cos, sigma 0.1 | 0.999987 / 0.999987 | | | 0.999992 / 0.999993 | +| DiT final latent (ComfyUI's noise and states), cos / SNR | 0.999914 / 37.6 dB | | | 0.999838 / 34.9 dB | +| DAV probe (one pass), cos / SNR | 1.0000000 / 71.0 dB | | | 0.9999993 / 52.0 dB | +| DAV of ComfyUI's latent (chunked as served), cos / SNR | 1.0000000 / 71.0 dB | | | 0.9999994 / 50.5 dB | + +Teacher forcing makes the AR rows comparable; the draws themselves cannot match (torch's multinomial vs our Philox +inverse-CDF draw), so a song is not ComfyUI's song for the same seed, only the same model. + +## Lyric accuracy + +Three songs, the same lyrics in bf16 and int8 (45 s each: hiphop seed 7, pop seed 11, long-pop seed 5), plus +ComfyUI's own 60 s hiphop song from the baseline run. Whisper is faster-whisper large-v3-turbo on the CPU through the +Studio's `qa.transcribe`; `tools/music3/lyrics_check.py` runs the engine first and Whisper after it ends. +"Studio score" is app/music.py's `heard` (words heard up to the last lyric word heard); "span" counts only matched +runs of 3 or more words, so a stray word far down the lyrics does not stretch the span (the int8 long song's "down" +matched the bridge's "go down": score 31, span 100). + +| Song | bf16 Studio score / span | int8 Studio score / span | words heard bf16 / int8 | +| --- | --- | --- | --- | +| hiphop, seed 7 | 96 / 96 | 98 / 98 | 130 of 135 / 127 of 130 | +| pop, seed 11 | 100 / 100 | 100 / 100 | 78 of 78 / 59 of 59 | +| long-pop, seed 5 | 90 / 89 | 31 / 100 | 50 of 56 / 52 of 52 | +| ComfyUI hiphop 60 s (reference) | 96 / 96 | | 159 of 166 | + +## Speed and memory (an idle GB10) + +Hiphop bench prompt seed 7 (the 120 s request ended itself at 63.3 s: the model drew its stop code; the long-pop +prompt seed 5 is the 120 s row). AR GB/s is the weight bytes a frame reads (int8 11.15 GB, bf16 22.3 GB) times +frames a second. Peak is MemTotal - MemAvailable sampled twice a second, minus the idle machine's (about 5.1 GB); +device is the engine's own allocations. Load (37 s, cold page cache) is outside "total". + +| Song | Weights | AR s (frames/s, GB/s) | DiT s | DAV s | Total s | RTF | Peak machine GB | Device GB | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 30 s | int8 | 36.4 (20.9, 233) | 22.0 | 1.9 | 60.3 | 2.01 | 16.6 | 16.5 | +| 60 s | int8 | 73.9 (20.4, 228) | 46.4 | 3.6 | 123.9 | 2.07 | 17.9 | 18.1 | +| 63 s (asked 120, ended itself) | int8 | 78.0 (20.4, 228) | 46.3 | 3.9 | 128.2 | 2.03 | 18.9 | 18.5 | +| 120 s (long-pop) | int8 | 151.7 (19.9, 222) | 93.0 | 7.3 | 252.0 | 2.10 | 19.3 | 18.9 | +| 30 s | bf16 | 72.1 (10.5, 233) | 21.9 | 1.9 | 96.0 | 3.20 | 24.0 | 24.1 | +| 60 s | bf16 | 144.4 (10.4, 232) | 46.3 | 3.6 | 194.3 | 3.24 | 25.5 | 25.8 | +| 63 s (asked 120, ended itself) | bf16 | 147.9 (10.4, 232) | 46.3 | 3.7 | 198.0 | 3.23 | 25.7 | 26.1 | +| 120 s (long-pop) | bf16 | 292.7 (10.3, 229) | 93.1 | 7.3 | 393.1 | 3.28 | 26.6 | 26.5 | + +Against the baseline (ComfyUI through the Studio, 60 s: 289 s, AR 176 s at ~9 frames/s, DiT 96 s, DAV 4 s, 29.3 GB): +int8 is 2.3x faster in total (AR 2.4x, DiT 2.1x) in 18 GB; bf16 is 1.5x. The Mac M5 Ultra does it in 75.8 s. + +Where the 60 s target of ~120 s stands: 123.9 s. The AR is at the measured read ceiling (228 of 230 GB/s), so +only fewer bytes move it (int4 / NVFP4, not tried: the depth decoder is already the most sensitive part in int8). +The DiT is 46 s: its GEMMs run at 80 to 98 TFLOP/s (about 31 s of it, the hardware's fp16 rate); GLU, LayerNorm +and attention are the other 15 s. What is left is fp8 GEMMs for the DiT (GB10's fp8 rate is twice fp16; not tried, +a quality risk against the fp16 reference) or fusing the GLU into a hand-written ff_out GEMM. + +## Default: int8, and why + +int8 (body and lm_head a scale a row, depth decoder and heads a scale a group of 128) is the default: it halves the +bytes a frame reads (2x AR, 1.6x total) and 7.6 GB less memory, its parity numbers are within a few 1e-4 of bf16, the +ComfyUI-drawn code is rank 1 in our logits in both, and its lyric accuracy is not lower than bf16's on three songs. +Group scales for the depth decoder cost <1% of AR speed and lift its greedy agreement from 0.91-0.94 to 0.95-0.97. +`--weights bf16` reads the checkpoint's own numbers. + +## Kernel contract + +`zig/tests/cuda/contract_music3.zig`: m3_rmsnorm, m3_gemv_bf16_2, m3_gemv_i8_2 and m3_gemv_g8_2 through gates 1-4; +all 55 music3 launches in `registry.zig` with their records for sm_80, sm_86, sm_89, sm_120 and sm_121 (from +`tf-cuda-test kernel-contract-limits` over `-Dsm=80,86,89,120,121` fatbins). On a GB10 (sm_121), on main 6ee828c2: + + SUMMARY 16 kernels: 16 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed; + 0 limit problems + PASS kernel-contract-limits: every registered launch fits sm_80, sm_86, sm_89, sm_120 and sm_121, every control red + +`python3 tools/zig/lean_check.py`: 517 problems, the same 517 as main (no new findings); `zig build test` (450/456, +6 JPEG cases skipped without libjpeg-turbo) and `zig build test-cuda-host` (856/856, main 852/852) pass; +`zig fmt --check zig build.zig` clean. + +## Reproduce the receipts + +The reference run hooks ComfyUI's own loaders, nodes and sampler and only records tensors (numpy files in `REF`): + +| Stage | ComfyUI run | Files | +| --- | --- | --- | +| ids | the MiniMax text encoder's tokenizer on a list of [caption, lyrics] cases | `ids_cases.json` | +| ar | the AR on the caption and lyrics, teacher state recorded each frame | `hidden.npy` [T, 32768], `codes.npy` [F, 8], `tokens.npy`, `ids.json`, `c0_logits.npy` [F, 2, 16385] fp16, `depth_logits.npy` [F, 7, 2, 1024] | +| dit | KSampler (euler, simple) over `hidden.npy`, the zeroed condition as negative | `latent.npy`, `noise.npy` | +| dav | VAE decode of `latent.npy` with the level rule | `audio.npy` [2, N] | +| probe | the first 200 frame states, seeded noise and the latent's first 689 rows: the DiT's output at sigma 1.0 / 0.5 / 0.1 for both branches, the DAV of `probe_latent.npy` | `probe_dit.npz`, `probe_dav.npy` | + +Then, on the same machine: + + music3-generate --model DIR --weights bf16 --parity-ar REF --parity-probe REF --parity-dit REF --parity-dav REF \ + --out MINE --caption-file C --lyrics-file L + python tools/music3/parity.py REF MINE --report parity.json + +## Not tested + +- GPUs other than GB10 (sm_121): the kernels build and pass gate 5 for sm_80/86/89/120, nothing ran there. PDL is used + only on sm_90 and up. +- fp8 or int4 / NVFP4 weights, fp8 DiT GEMMs, an int8 weight cache file (quantizing at load costs nothing extra). +- Songs over 120 s (the cap is 360 s / 9000 frames; the caches and windows are sized for it, not run), prompts near + 5000 tokens, an instrumental-only song's lyric check, non-ASCII section tags (lower-cased as ASCII only). +- The Studio app itself driving this engine (only its `Served` client was run, from a test script). +- Two requests at once (the server answers one at a time, as the Mac engine does). diff --git a/docs/recipes/minimax-music3-cuda/lyrics.json b/docs/recipes/minimax-music3-cuda/lyrics.json new file mode 100644 index 00000000000..a12c6036a97 --- /dev/null +++ b/docs/recipes/minimax-music3-cuda/lyrics.json @@ -0,0 +1 @@ +[["hiphop", 7, "int8", 98, 98, 127, 130], ["pop", 11, "int8", 100, 100, 59, 59], ["long", 5, "int8", 31, 100, 52, 52], ["hiphop", 7, "bf16", 96, 96, 130, 135], ["pop", 11, "bf16", 100, 100, 78, 78], ["long", 5, "bf16", 90, 89, 50, 56], ["comfyui_hiphop60", 0, "comfyui", 96, 96, 159, 166]] \ No newline at end of file diff --git a/docs/recipes/minimax-music3-cuda/parity_cuda_bf16.json b/docs/recipes/minimax-music3-cuda/parity_cuda_bf16.json new file mode 100644 index 00000000000..0a47ac38900 --- /dev/null +++ b/docs/recipes/minimax-music3-cuda/parity_cuda_bf16.json @@ -0,0 +1,100 @@ +{ + "ref": "ref30", + "mine": "pmerge_bf16_0", + "label": "cuda bf16_0", + "prompt_ids_equal": true, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999956, + "min": 0.999556, + "p01": 0.999909 + }, + "cos_by_part": [ + 0.999953, + 0.999952, + 0.999957, + 0.99996, + 0.999963, + 0.999965, + 0.999965, + 0.999964 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999977, + "min": 0.999807, + "p01": 0.99992 + }, + "cos_uncond": { + "mean": 0.999977, + "min": 0.999757, + "p01": 0.999921 + }, + "greedy_agree_cond": 0.9747, + "greedy_agree_guided": 0.9614, + "top50_overlap": 0.9854, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999962, + 0.999962, + 0.999966, + 0.999961, + 0.999958, + 0.999957, + 0.999957 + ], + "greedy_agree_by_codebook": [ + 0.976, + 0.9707, + 0.9814, + 0.964, + 0.976, + 0.976, + 0.9814 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.999991, + "cos_uncond": 0.999994, + "rel_err_cond": 0.00447, + "cos_guided_1.7": 0.999986 + }, + "0.5": { + "cos_cond": 0.999958, + "cos_uncond": 0.999961, + "rel_err_cond": 0.00925, + "cos_guided_1.7": 0.999878 + }, + "0.1": { + "cos_cond": 0.999987, + "cos_uncond": 0.999987, + "rel_err_cond": 0.0051, + "cos_guided_1.7": 0.999962 + } + }, + "dit_final_latent": { + "cos": 0.999914, + "snr_db": 37.58 + }, + "dav_probe": { + "cos": 1.0, + "snr_db": 71.02 + }, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 1.0, + "snr_db": 70.95 + } +} diff --git a/docs/recipes/minimax-music3-cuda/parity_cuda_int8.json b/docs/recipes/minimax-music3-cuda/parity_cuda_int8.json new file mode 100644 index 00000000000..7c37f39f8e7 --- /dev/null +++ b/docs/recipes/minimax-music3-cuda/parity_cuda_int8.json @@ -0,0 +1,100 @@ +{ + "ref": "ref30", + "mine": "pmerge_int8_128", + "label": "cuda int8_128", + "prompt_ids_equal": true, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999827, + "min": 0.998345, + "p01": 0.999526 + }, + "cos_by_part": [ + 0.9998, + 0.999814, + 0.999833, + 0.999848, + 0.999859, + 0.999866, + 0.999868, + 0.999868 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999897, + "min": 0.997585, + "p01": 0.999507 + }, + "cos_uncond": { + "mean": 0.999902, + "min": 0.998932, + "p01": 0.999626 + }, + "greedy_agree_cond": 0.9667, + "greedy_agree_guided": 0.9561, + "top50_overlap": 0.9799, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999832, + 0.999828, + 0.999853, + 0.999821, + 0.999819, + 0.99982, + 0.999814 + ], + "greedy_agree_by_codebook": [ + 0.9667, + 0.9614, + 0.9587, + 0.9454, + 0.9507, + 0.9601, + 0.9587 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.999991, + "cos_uncond": 0.999994, + "rel_err_cond": 0.00447, + "cos_guided_1.7": 0.999986 + }, + "0.5": { + "cos_cond": 0.999958, + "cos_uncond": 0.999961, + "rel_err_cond": 0.00925, + "cos_guided_1.7": 0.999878 + }, + "0.1": { + "cos_cond": 0.999987, + "cos_uncond": 0.999987, + "rel_err_cond": 0.0051, + "cos_guided_1.7": 0.999962 + } + }, + "dit_final_latent": { + "cos": 0.999914, + "snr_db": 37.58 + }, + "dav_probe": { + "cos": 1.0, + "snr_db": 71.02 + }, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 1.0, + "snr_db": 70.95 + } +} diff --git a/docs/recipes/minimax-music3-cuda/parity_cuda_int8_rowscales.json b/docs/recipes/minimax-music3-cuda/parity_cuda_int8_rowscales.json new file mode 100644 index 00000000000..ea7b31cfd11 --- /dev/null +++ b/docs/recipes/minimax-music3-cuda/parity_cuda_int8_rowscales.json @@ -0,0 +1,100 @@ +{ + "ref": "ref30", + "mine": "pmerge_int8_0", + "label": "cuda int8_0", + "prompt_ids_equal": true, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999519, + "min": 0.99816, + "p01": 0.999156 + }, + "cos_by_part": [ + 0.9998, + 0.999043, + 0.999183, + 0.999256, + 0.99939, + 0.99938, + 0.999392, + 0.999344 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999897, + "min": 0.997585, + "p01": 0.999507 + }, + "cos_uncond": { + "mean": 0.999902, + "min": 0.998932, + "p01": 0.999626 + }, + "greedy_agree_cond": 0.9667, + "greedy_agree_guided": 0.9561, + "top50_overlap": 0.9799, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999472, + 0.999296, + 0.999341, + 0.999468, + 0.999325, + 0.999333, + 0.999129 + ], + "greedy_agree_by_codebook": [ + 0.9374, + 0.9095, + 0.9308, + 0.9268, + 0.9294, + 0.9081, + 0.9334 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.999991, + "cos_uncond": 0.999994, + "rel_err_cond": 0.00447, + "cos_guided_1.7": 0.999986 + }, + "0.5": { + "cos_cond": 0.999958, + "cos_uncond": 0.999961, + "rel_err_cond": 0.00925, + "cos_guided_1.7": 0.999878 + }, + "0.1": { + "cos_cond": 0.999987, + "cos_uncond": 0.999987, + "rel_err_cond": 0.0051, + "cos_guided_1.7": 0.999962 + } + }, + "dit_final_latent": { + "cos": 0.999914, + "snr_db": 37.58 + }, + "dav_probe": { + "cos": 1.0, + "snr_db": 71.02 + }, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 1.0, + "snr_db": 70.95 + } +} diff --git a/docs/recipes/minimax-music3-cuda/parity_mlx_mac.json b/docs/recipes/minimax-music3-cuda/parity_mlx_mac.json new file mode 100644 index 00000000000..ca192d66daa --- /dev/null +++ b/docs/recipes/minimax-music3-cuda/parity_mlx_mac.json @@ -0,0 +1,103 @@ +{ + "ref": "ref30", + "dit_dtype": "float16", + "comfy_rope": false, + "prompt_ids_equal": true, + "ar_forced_s": 16.5, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999951, + "min": 0.999821, + "p01": 0.999885 + }, + "cos_by_part": [ + 0.999948, + 0.999945, + 0.999951, + 0.999957, + 0.99996, + 0.999961, + 0.999962, + 0.999961 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999973, + "min": 0.999724, + "p01": 0.999889 + }, + "cos_uncond": { + "mean": 0.999973, + "min": 0.99967, + "p01": 0.999916 + }, + "greedy_agree_cond": 0.9774, + "greedy_agree_guided": 0.964, + "top50_overlap": 0.9872, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999955, + 0.999952, + 0.999953, + 0.999945, + 0.999942, + 0.999936, + 0.999934 + ], + "greedy_agree_by_codebook": [ + 0.976, + 0.9827, + 0.972, + 0.9734, + 0.9507, + 0.9774, + 0.9627 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.99999, + "cos_uncond": 0.999998, + "rel_err_cond": 0.00446, + "cos_guided_1.7": 0.999983 + }, + "0.5": { + "cos_cond": 0.999971, + "cos_uncond": 0.999977, + "rel_err_cond": 0.00762, + "cos_guided_1.7": 0.999936 + }, + "0.1": { + "cos_cond": 0.999992, + "cos_uncond": 0.999993, + "rel_err_cond": 0.00405, + "cos_guided_1.7": 0.999979 + } + }, + "dav_probe": { + "cos": 0.9999993, + "snr_db": 52.0 + }, + "dit_s": 16.04, + "dit_final_latent": { + "cos": 0.999838, + "snr_db": 34.86 + }, + "dav_s": 1.26, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 0.9999994, + "snr_db": 50.54 + } +} diff --git a/docs/recipes/minimax-music3-metal.md b/docs/recipes/minimax-music3-metal.md new file mode 100644 index 00000000000..bdbdaebf4f4 --- /dev/null +++ b/docs/recipes/minimax-music3-metal.md @@ -0,0 +1,140 @@ +# MiniMax Music 3 on Metal (Apple M5) + +`music3-generate` on macOS runs MiniMax Music 3 (MiniMax-Music3, Comfy-Org's single-file checkpoints) on TensorFold's +own Metal runtime: the autoregressive LM with its depth decoder, the flow-matching DiT and the DAV decoder, in Zig with +kernels of its own (`zig/kernels/metal/music3/`, one metallib built ahead of time). There is no Python, MLX or PyTorch +at run time. It is the Metal half of [the CUDA recipe](minimax-music3-cuda.md): the same config, prompt, checkpoint +loaders, request settings, WAV writer, `--serve` protocol and parity tools. + +No weights are included. MiniMax-Music3 is released under the MiniMax-Music3 Community License: a commercial product +must display "MiniMax-Music3" in its interface, use by a business above $20M in yearly revenue needs MiniMax's +written authorization, and a hosted service must keep the license's safeguards in place. + +## Build and run + + zig build music3-generate -Doptimize=ReleaseFast + ./zig-out/bin/music3-generate --model DIR --caption-file style.txt --lyrics-file lyrics.txt --seconds 60 --seed 7 \ + --out song.wav --stats song.json # int8 (default); --weights bf16 for the checkpoint's own + ./zig-out/bin/music3-generate --serve 1 --model DIR # the CUDA recipe's protocol, line for line + +`--model DIR` (or `$TF_MUSIC3_MODEL`) is the folder holding Comfy-Org's three MiniMax-Music3 files. The DiT, the +prompt rows and the DAV run on the tensor units, so an M5 or later is required; on an earlier GPU the engine stops at +load with a message. `--flash`, `--dav-tf32` and `--graphs` choose CUDA kernels and are accepted and ignored here. + +## What was built + +| Stage | How | +| --- | --- | +| Prompt | the shared `prompt.zig` and the checkpoint's own tokenizer: the ids equal ComfyUI's | +| AR prompt | both CFG rows through the body in bf16 GEMMs on the tensor units (`m3_linear_b`, MLX's `steel_gemm_fused_nax` blocks through `tfp::gemm_block`); int8 weights are dequantized a projection at a time for it | +| AR frame | lm_head, the CFG top-k draw on the device, the depth decoder's 7 passes and the frame fed back through 36 layers, encoded straight into a serial compute encoder and committed a frame at a time, so the next frame encodes while the GPU runs the last; position, step and count advance on the GPU and the host reads the drawn tokens every 16 frames for the stop code | +| AR GEMV | a simdgroup two weight rows (two outputs, or a gate and up row whose SwiGLU it writes), one 16-byte load a row a lane in flight, fp32 sums; bf16, int8 a scale a row (body, lm_head) or a scale a group of 128 (depth decoder and heads), as on CUDA | +| Attention | split-key decode attention, four keys a step under one `simd_sum`; the depth decoder's 8 positions in one group a head | +| DiT | windows of 689 latent rows every 344, all of a 60 s song's windows and both CFG branches in one forward; fp16 GEMMs on the tensor units with fp32 sums; q and k leave the qkv GEMM roped and ff_in's GEMM writes the GLU (its rows are paired at load), so neither has a pass of its own; attention on the tensor units (heads of 64, 64 queries a group, online softmax, fp16 probabilities for P V as on CUDA) | +| DAV | fp32, every conv as one GEMM a tap over time-major rows with zero halos; each GEMM runs on the tensor units from bf16 halves of both operands (x = xh + xl: xh wh + xh wl + xl wh, fp32 sums), chunks of 512 latent rows with 32 rows of context, ComfyUI's level rule | +| Sampling | the CUDA sampler's radix select and inverse-CDF draw on the same Philox counters; a song is not CUDA's song for the same seed, as the logits differ in the last bits | + +Precision is the reference's: bf16 activations in the AR with bf16 roundings where torch rounds, fp32 norms, softmax +and rope; fp16 in the DiT with the reference's fp16 roundings; fp32 in the DAV. `music3.metallib` is built with safe +math and precise fp32 functions. One exception: the fused GLU's sigmoid uses `fast::exp`, since `precise::exp` in that +epilogue made the ff_in GEMM 2.6 times slower (final latent 38.92 dB with `precise::exp`, 38.97 dB with `fast::exp`). + +## Parity against ComfyUI + +The reference is ComfyUI's native MiniMax Music 3 nodes on the same Mac (MPS): hiphop bench prompt, 30 s, seed 7, +teacher-forced so the rows are comparable (the dumps the CUDA recipe describes, `tools/music3/parity.py`). The MLX +engine (a separate Python port, not part of this tree) is against the same dumps; CUDA's columns are against ComfyUI +on its own GB10, so they show the same model's spread, not a shared reference. JSON: `minimax-music3-metal/`. + +| Check | Metal bf16 | Metal int8 (default) | MLX bf16 | MLX int8 | CUDA bf16 / int8 | +| --- | --- | --- | --- | --- | --- | +| prompt ids equal | yes | yes | yes | yes | yes / yes | +| frame states cos, mean / min | 0.999955 / 0.999748 | 0.999838 / 0.997195 | 0.999951 / 0.999821 | 0.999889 / 0.998982 | 0.999956 / 0.999827 | +| code-0 logits cos (cond), mean / min | 0.999975 / 0.999839 | 0.999906 / 0.99749 | 0.999973 / 0.999724 | 0.999938 / 0.99862 | 0.999977 / 0.999897 | +| code-0 greedy agreement, cond / guided | 0.9814 / 0.968 | 0.968 / 0.9694 | 0.9774 / 0.964 | 0.98 / 0.9507 | 0.9747 / 0.9667 (cond) | +| code-0 top-50 overlap | 0.9873 | 0.9821 | 0.9872 | 0.9842 | 0.9854 / 0.9799 | +| ComfyUI's drawn code, median rank in ours | 1 | 1 | 1 | 1 | 1 / 1 | +| depth logits cos, codebook 1..7 | 0.99994 to 0.999955 | 0.999807 to 0.999859 | 0.99993 to 0.99996 | 0.99986 to 0.99991 | 0.99996 / 0.9998 | +| depth greedy agreement, codebook 1..7 | 0.951 to 0.976 | 0.933 to 0.977 | 0.951 to 0.983 | 0.933 to 0.969 | 0.964-0.981 / 0.945-0.967 | +| DiT probe cos (cond / uncond), sigma 1.0 | 0.999995 / 0.999996 | (the DiT is fp16 in both) | 0.99999 / 0.999998 | | 0.999991 / 0.999994 | +| DiT probe cos, sigma 0.5 / 0.1 (cond) | 0.999982 / 0.999993 | | 0.999971 / 0.999992 | | 0.999958 / 0.999987 | +| DiT final latent (ComfyUI's noise and states), cos / SNR | 0.999939 / 38.97 dB | | 0.999838 / 34.9 dB | | 0.999914 / 37.6 dB | +| DAV probe (one pass), cos / SNR | 1.0000000 / 103.9 dB | | 0.9999993 / 52.0 dB | | 1.0000000 / 71.0 dB | +| DAV of ComfyUI's latent (chunked as served), cos / SNR | 1.0000000 / 103.9 dB | | 0.9999994 / 50.5 dB | | 1.0000000 / 71.0 dB | + +The tensor units' own fp32 GEMM path gave the DAV 42.3 dB here (it keeps fewer bits of each operand); plain fp32 +simdgroup matrices gave 118.5 dB at 8 times the time; the bf16 halves give 103.9 dB at 1.4 s for 30 s of song. + +## Speed and memory (one Mac Studio, M5 Ultra, 256 GB) + +Hiphop bench prompt, 60 s, seed 7. The MLX engine is the same Mac's Python port with `--quant int8` (8-bit in groups +of 64 everywhere); this port is int8 a scale a row in the body and lm_head, a scale a group of 128 in the depth +decoder and heads. The runs alternated (Metal, MLX, Metal, MLX, ...), three each, one model process at a time under a +lock shared with the machine's other GPU jobs. Peak is the process's own peak footprint (`/usr/bin/time -l`). + +| Run | Engine | AR frames/s | prefill s | AR s | DiT s | DAV s | **Total s** | Peak footprint | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | Metal int8 | 69.09 | 0.27 | 22.0 | 34.7 | 2.80 | **59.5** | 17.9 GB | +| 1 | MLX int8 | 64.66 | 0.18 | 23.4 | 35.3 | 2.06 | **62.3** | 28.1 GB | +| 2 | Metal int8 | 68.87 | 0.28 | 22.1 | 37.9 | 2.81 | **62.8** | 17.9 GB | +| 2 | MLX int8 | 64.66 | 0.18 | 23.4 | 37.2 | 2.02 | **63.9** | 28.1 GB | +| 3 | Metal int8 | 68.90 | 0.27 | 22.1 | 38.1 | 2.80 | **63.0** | 17.7 GB | +| 3 | MLX int8 | 64.76 | 0.19 | 23.3 | 37.3 | 2.02 | **63.8** | 28.1 GB | +| one | Metal bf16 | 41.36 | 0.27 | 36.6 | 37.9 | 2.80 | **77.2** | 25.3 GB | +| one, long-pop 120 s, seed 5 | Metal int8 | 66.95 | 0.43 | 45.3 | 72.5 | 5.90 | **123.7** | 18.4 GB | + +- **The AR reads 11.15 GB a frame in int8,** so 69 frames/s is 770 GB/s. The GEMVs alone run at 1,040 GB/s (body) + and 990 GB/s (depth decoder), measured on the same weights; the rest of a frame is attention, norms, the 8 draws + and the dispatches between them (about 3.6 ms of a 14.5 ms frame). +- **The DiT is GEMM-bound:** its 3.0 PFLOP of products for 60 s of song in 34.7 to 38.1 s is 79 to 86 TFLOP/s, on + the same kernel blocks as MLX's (35.3 to 37.3 s). Folding the rope and the GLU into the GEMMs took 4% off it. +- **Load** is 2.8 to 3.4 s from a warm page cache: the weights are copied into shared Metal buffers (14.2 GB in int8), + int8 quantized on the GPU as they load. + +**Other processes on the machine:** an Ollama server and another app were resident during the timed runs; I did not +measure whether they used the GPU. + +## Lyric accuracy + +Three 45 s songs in each format through `--serve`, transcribed by faster-whisper large-v3-turbo on the CPU and scored +by the Studio's `music.heard` (`tools/music3/lyrics_check.py`, `minimax-music3-metal/lyrics.json`). + +| Song | int8 score | int8 words heard | bf16 score | bf16 words heard | +| --- | --- | --- | --- | --- | +| hiphop, seed 7 | 99 | 143 of 145 | 98 | 121 of 124 | +| pop, seed 11 | 100 | 78 of 78 | 100 | 70 of 70 | +| long-pop, seed 5 | 97 | 56 of 58 | 100 | 46 of 46 | + +## Determinism + +- **Three processes** (pop prompt, 30 s, seed 11) wrote byte-identical WAVs: MD5 `e81021f8…`. +- **Three requests in one `--serve` process** wrote the same bytes as the fresh processes. +- Every kernel computes a row's outputs in a fixed order with no atomics in a sum (the sampler's histogram counts + are integers), so the bits do not depend on timing. + +## Kernel contract and checks + +On the M5 Ultra: + + SUMMARY 27 kernels: 27 pass gates 1-4, 0 fail, 2 known findings; 5 controls: 5 red as planted, 0 missed; + 0 limit problems + PASS limits: 134 registered Metal launches against M1-M5, 0 problems + +- **Gates 1-4:** `m3_rmsnorm` (plain gamma) against the rows family's float64 RMS norm, at the served shapes (2, 4 and + 600 rows of 4096): non-finite classes match, five runs byte-identical, the shapes within the bound, fp32 sums. +- **Gate 5:** all 57 music3 Metal launches in `registry.zig`. Each kernel reserves its threads in the source, so none + needs an M1/M2 compile record, and each passes the on-GPU check of its pipeline and threadgroup bytes. The two known + findings are affine_mm's, from before this change. +- `python3 tools/zig/lean_check.py`: 517 problems, the same 517 as the CUDA branch. Every file is at most 600 lines. + +## Next steps + +- **The DiT.** It is now 60% of a song. The GEMMs are at the rate of MLX's blocks; int8 or fp8 products for the DiT + would be the next lever, a quality risk against the fp16 reference, not tried. +- **The AR's frame overhead.** 3.6 ms a frame is outside the GEMVs: folding the RMS norms into the GEMVs that read + them and fewer, larger attention dispatches would take most of it. +- **The DAV.** 1.4 s for 30 s, against MLX's 1.0 s at 50 dB; one pass with the hi and lo products sharing loads is + done, the halves could also be written by the kernels before each GEMM instead of a pass of their own. +- **Before M5.** The tensor-unit kernels have a simdgroup-matrix form (nax.h's `TF_SIMD_FRAGS`) that gate 5 compiles + for M1-M4; a second metallib for those GPUs was not built or run. +- **Streaming.** The MLX engine can stream audio while the AR draws; this port answers when the song is done. diff --git a/docs/recipes/minimax-music3-metal/lyrics.json b/docs/recipes/minimax-music3-metal/lyrics.json new file mode 100644 index 00000000000..88057a9570f --- /dev/null +++ b/docs/recipes/minimax-music3-metal/lyrics.json @@ -0,0 +1 @@ +{"columns": ["song", "seed", "weights", "score", "found", "words"], "rows": [["hiphop", 7, "int8", 99, 143, 145], ["pop", 11, "int8", 100, 78, 78], ["long", 5, "int8", 97, 56, 58], ["hiphop", 7, "bf16", 98, 121, 124], ["pop", 11, "bf16", 100, 70, 70], ["long", 5, "bf16", 100, 46, 46]]} diff --git a/docs/recipes/minimax-music3-metal/parity_metal_bf16.json b/docs/recipes/minimax-music3-metal/parity_metal_bf16.json new file mode 100644 index 00000000000..d94d00aa86d --- /dev/null +++ b/docs/recipes/minimax-music3-metal/parity_metal_bf16.json @@ -0,0 +1,100 @@ +{ + "ref": "ref30", + "mine": "par_bf16", + "label": "metal bf16", + "prompt_ids_equal": true, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999955, + "min": 0.999748, + "p01": 0.999893 + }, + "cos_by_part": [ + 0.999952, + 0.999948, + 0.999955, + 0.99996, + 0.999963, + 0.999964, + 0.999965, + 0.999965 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999975, + "min": 0.999839, + "p01": 0.999893 + }, + "cos_uncond": { + "mean": 0.999975, + "min": 0.999779, + "p01": 0.999912 + }, + "greedy_agree_cond": 0.9814, + "greedy_agree_guided": 0.968, + "top50_overlap": 0.9873, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999955, + 0.999955, + 0.999955, + 0.999946, + 0.999943, + 0.999942, + 0.99994 + ], + "greedy_agree_by_codebook": [ + 0.968, + 0.9734, + 0.9694, + 0.9707, + 0.9507, + 0.976, + 0.964 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.999995, + "cos_uncond": 0.999996, + "rel_err_cond": 0.00315, + "cos_guided_1.7": 0.999992 + }, + "0.5": { + "cos_cond": 0.999982, + "cos_uncond": 0.99998, + "rel_err_cond": 0.00615, + "cos_guided_1.7": 0.999951 + }, + "0.1": { + "cos_cond": 0.999993, + "cos_uncond": 0.999994, + "rel_err_cond": 0.00372, + "cos_guided_1.7": 0.999979 + } + }, + "dit_final_latent": { + "cos": 0.999939, + "snr_db": 38.97 + }, + "dav_probe": { + "cos": 1.0, + "snr_db": 103.92 + }, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 1.0, + "snr_db": 103.89 + } +} diff --git a/docs/recipes/minimax-music3-metal/parity_metal_int8.json b/docs/recipes/minimax-music3-metal/parity_metal_int8.json new file mode 100644 index 00000000000..1a4e957acd4 --- /dev/null +++ b/docs/recipes/minimax-music3-metal/parity_metal_int8.json @@ -0,0 +1,100 @@ +{ + "ref": "ref30", + "mine": "par_int8", + "label": "metal int8", + "prompt_ids_equal": true, + "frame_states": { + "frames": [ + 750, + 750 + ], + "cos": { + "mean": 0.999838, + "min": 0.997195, + "p01": 0.99947 + }, + "cos_by_part": [ + 0.999807, + 0.999822, + 0.999844, + 0.99986, + 0.999873, + 0.999878, + 0.99988, + 0.999882 + ] + }, + "c0_logits": { + "frames": 751, + "cos_cond": { + "mean": 0.999906, + "min": 0.99749, + "p01": 0.99954 + }, + "cos_uncond": { + "mean": 0.99991, + "min": 0.998108, + "p01": 0.999598 + }, + "greedy_agree_cond": 0.968, + "greedy_agree_guided": 0.9694, + "top50_overlap": 0.9821, + "ref_drawn_code_rank_mine_median": 1 + }, + "depth_logits": { + "cos_cond_by_codebook": [ + 0.999859, + 0.999857, + 0.999852, + 0.999822, + 0.99982, + 0.999807, + 0.999808 + ], + "greedy_agree_by_codebook": [ + 0.9561, + 0.9774, + 0.9614, + 0.9521, + 0.9334, + 0.9654, + 0.9494 + ] + }, + "dit_probe": { + "1.0": { + "cos_cond": 0.999995, + "cos_uncond": 0.999996, + "rel_err_cond": 0.00315, + "cos_guided_1.7": 0.999992 + }, + "0.5": { + "cos_cond": 0.999982, + "cos_uncond": 0.99998, + "rel_err_cond": 0.00615, + "cos_guided_1.7": 0.999951 + }, + "0.1": { + "cos_cond": 0.999993, + "cos_uncond": 0.999994, + "rel_err_cond": 0.00372, + "cos_guided_1.7": 0.999979 + } + }, + "dit_final_latent": { + "cos": 0.999939, + "snr_db": 38.97 + }, + "dav_probe": { + "cos": 1.0, + "snr_db": 103.92 + }, + "dav_waveform": { + "samples": [ + 1322496, + 1322496 + ], + "cos": 1.0, + "snr_db": 103.89 + } +} diff --git a/tools/music3/lyrics_check.py b/tools/music3/lyrics_check.py new file mode 100644 index 00000000000..11c014404a8 --- /dev/null +++ b/tools/music3/lyrics_check.py @@ -0,0 +1,85 @@ +"""Lyric accuracy of music3-generate: songs through --serve, then Whisper (faster-whisper large-v3-turbo on the CPU, +the Studio's own qa.transcribe) against the lyrics with the Studio's music.heard score. + + python tools/music3/lyrics_check.py --bin music3-generate --studio-app APP --prompts DIR --out DIR + [--weights int8 bf16] [--seconds 45] [--songs hiphop:7 pop:11 long:5] + +The engine runs first and ends before Whisper loads (no two models at once). Writes DIR/lyrics.json. +""" +import argparse +import json +import subprocess +import sys +import time +from pathlib import Path + + +def serve_songs(binary: str, weights: str, songs: list, prompts: Path, out: Path, seconds: float) -> list: + proc = subprocess.Popen([binary, "--serve", "1", "--weights", weights], stdin=subprocess.PIPE, stderr=subprocess.PIPE, + stdout=subprocess.DEVNULL, text=True, bufsize=1) + answers = [] + + def read() -> dict: + for line in proc.stderr: + if line.startswith("{"): + msg = json.loads(line) + if "progress" not in msg: + return msg + raise RuntimeError("the engine stopped") + + ready = read() + assert ready.get("ready"), ready + for name, seed in songs: + wav = out / f"{name}_{seed}_{weights}.wav" + req = {"id": f"{name}-{seed}-{weights}", "caption": (prompts / f"{name}.caption").read_text(), + "lyrics": (prompts / f"{name}.lyrics").read_text(), "wav": str(wav), "seconds": seconds, "seed": seed} + proc.stdin.write(json.dumps(req) + "\n") + proc.stdin.flush() + ans = read() + ans["name"], ans["weights"], ans["seed"] = name, weights, seed + answers.append(ans) + print(json.dumps(ans), flush=True) + proc.stdin.close() + proc.wait(timeout=60) + return answers + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--bin", required=True) + p.add_argument("--studio-app", required=True, type=Path) + p.add_argument("--prompts", required=True, type=Path) + p.add_argument("--out", required=True, type=Path) + p.add_argument("--weights", nargs="+", default=["int8", "bf16"]) + p.add_argument("--seconds", type=float, default=45) + p.add_argument("--songs", nargs="+", default=["hiphop:7", "pop:11", "long:5"]) + p.add_argument("--extra", nargs="*", default=[], help="NAME=WAV:LYRICS more songs to score (a ComfyUI song)") + a = p.parse_args() + a.out.mkdir(parents=True, exist_ok=True) + songs = [(s.split(":")[0], int(s.split(":")[1])) for s in a.songs] + made = [] + for w in a.weights: + made += serve_songs(a.bin, w, songs, a.prompts, a.out, a.seconds) + sys.path.insert(0, str(a.studio_app)) + import music # noqa: E402 + import qa # noqa: E402 + rows = [] + todo = [(m["name"], m["weights"], m["seed"], Path(m["wav"]), a.prompts / f"{m['name']}.lyrics") for m in made if m.get("ok")] + for e in a.extra: + label, rest = e.split("=", 1) + wav, lyr = rest.split(":", 1) + todo.append((label, "comfyui", 0, Path(wav), Path(lyr))) + for name, weights, seed, wav, lyr in todo: + t0 = time.time() + heard = qa.transcribe(wav) + score = music.heard(lyr.read_text(), heard or "") + rows.append({"song": name, "seed": seed, "weights": weights, "wav": str(wav), "score": score["score"], "found": score["found"], + "words": score["words"], "reached": score["reached"], "total": score["total"], "whisper_s": round(time.time() - t0, 1), + "heard": heard}) + print(json.dumps(rows[-1]), flush=True) + (a.out / "lyrics.json").write_text(json.dumps({"songs": made, "scores": rows}, indent=1) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music3/parity.py b/tools/music3/parity.py new file mode 100644 index 00000000000..bca36dab4fc --- /dev/null +++ b/tools/music3/parity.py @@ -0,0 +1,121 @@ +"""MiniMax Music 3 on CUDA vs a ComfyUI reference run, stage by stage: the MLX port's parity.json table. + + python tools/music3/parity.py REF MINE [--report parity.json] [--ar-cfg 1.5] + +REF is a ComfyUI reference dump (see docs/recipes/minimax-music3-cuda.md); MINE is what +`music3-generate --parity-{ar,dit,probe,dav} REF --out MINE` wrote. numpy only (no GPU). +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import numpy as np + + +def cos(a, b) -> float: + a, b = np.asarray(a, np.float64).ravel(), np.asarray(b, np.float64).ravel() + return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30)) + + +def snr_db(ref, test) -> float: + ref, test = np.asarray(ref, np.float64), np.asarray(test, np.float64) + return float(10 * np.log10((ref ** 2).sum() / max(((ref - test) ** 2).sum(), 1e-30))) + + +def rows_cos(a, b): + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + a, b = a.reshape(a.shape[0], -1), b.reshape(b.shape[0], -1) + return (a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1) + 1e-30) + + +def summary(values) -> dict: + v = np.asarray(values, np.float64) + return {"mean": round(float(v.mean()), 6), "min": round(float(v.min()), 6), "p01": round(float(np.percentile(v, 1)), 6)} + + +def check_ar(ref: Path, mine: Path, report: dict, ar_cfg: float) -> None: + report["prompt_ids_equal"] = json.loads((mine / "ids.json").read_text())["ids"] == json.loads((ref / "ids.json").read_text())["ids"] + hidden = np.load(ref / "hidden.npy") + states = np.load(mine / "states.npy") + n = min(len(states), len(hidden)) + layer = np.stack([rows_cos(states[:n, i * 4096:(i + 1) * 4096], hidden[:n, i * 4096:(i + 1) * 4096]) for i in range(8)]) + report["frame_states"] = {"frames": [int(len(states)), int(len(hidden))], "cos": summary(rows_cos(states[:n], hidden[:n])), + "cos_by_part": [round(float(x), 6) for x in layer.mean(axis=1)]} + codes = np.load(ref / "codes.npy") + ref_c0 = np.load(ref / "c0_logits.npy").astype(np.float32) + my_c0 = np.load(mine / "c0_logits.npy") + m = min(len(ref_c0), len(my_c0)) + g_ref = ref_c0[:m, 1] + (ref_c0[:m, 0] - ref_c0[:m, 1]) * ar_cfg + g_my = my_c0[:m, 1] + (my_c0[:m, 0] - my_c0[:m, 1]) * ar_cfg + top50 = np.mean([len(set(np.argsort(-a)[:50]) & set(np.argsort(-b)[:50])) / 50 for a, b in zip(my_c0[:m, 0], ref_c0[:m, 0])]) + forced = codes[:m, 0] + 1 + report["c0_logits"] = {"frames": int(m), "cos_cond": summary(rows_cos(my_c0[:m, 0], ref_c0[:m, 0])), + "cos_uncond": summary(rows_cos(my_c0[:m, 1], ref_c0[:m, 1])), + "greedy_agree_cond": round(float((my_c0[:m, 0].argmax(-1) == ref_c0[:m, 0].argmax(-1)).mean()), 4), + "greedy_agree_guided": round(float((g_my.argmax(-1) == g_ref.argmax(-1)).mean()), 4), + "top50_overlap": round(float(top50), 4), + "ref_drawn_code_rank_mine_median": int(np.median([(row > row[f]).sum() for row, f in zip(g_my, forced)]))} + ref_d = np.load(ref / "depth_logits.npy").astype(np.float32) + my_d = np.load(mine / "depth_logits.npy") + m = min(len(ref_d), len(my_d)) + report["depth_logits"] = { + "cos_cond_by_codebook": [round(float(rows_cos(my_d[:m, i, 0], ref_d[:m, i, 0]).mean()), 6) for i in range(7)], + "greedy_agree_by_codebook": [round(float((my_d[:m, i, 0].argmax(-1) == ref_d[:m, i, 0].argmax(-1)).mean()), 4) for i in range(7)]} + + +def check_probe(ref: Path, mine: Path, report: dict) -> None: + outs = np.load(ref / "probe_dit.npz") + res = {} + for sigma in (1.0, 0.5, 0.1): + c, u = np.load(mine / f"probe_cond_{sigma:.1f}.npy"), np.load(mine / f"probe_uncond_{sigma:.1f}.npy") + rc, ru = outs[f"cond_{sigma}"], outs[f"uncond_{sigma}"] + res[str(sigma)] = {"cos_cond": round(cos(c, rc), 6), "cos_uncond": round(cos(u, ru), 6), + "rel_err_cond": round(float(np.linalg.norm(c - rc) / np.linalg.norm(rc)), 5), + "cos_guided_1.7": round(cos(u + (c - u) * 1.7, ru + (rc - ru) * 1.7), 6)} + report["dit_probe"] = res + + +def check_dit(ref: Path, mine: Path, report: dict) -> None: + r, m = np.load(ref / "latent.npy"), np.load(mine / "latent.npy") + report["dit_final_latent"] = {"cos": round(cos(m, r), 6), "snr_db": round(snr_db(r, m), 2)} + + +def check_dav(ref: Path, mine: Path, report: dict) -> None: + if (mine / "probe_dav.npy").exists(): + r, m = np.load(ref / "probe_dav.npy"), np.load(mine / "probe_dav.npy") + n = min(r.shape[-1], m.shape[-1]) + report["dav_probe"] = {"cos": round(cos(m[..., :n], r[..., :n]), 7), "snr_db": round(snr_db(r[..., :n], m[..., :n]), 2)} + if (mine / "audio.npy").exists(): + r, m = np.load(ref / "audio.npy"), np.load(mine / "audio.npy") + n = min(m.shape[1], r.shape[1]) + report["dav_waveform"] = {"samples": [int(m.shape[1]), int(r.shape[1])], "cos": round(cos(m[:, :n], r[:, :n]), 7), + "snr_db": round(snr_db(r[:, :n], m[:, :n]), 2)} + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("ref", type=Path) + p.add_argument("mine", type=Path) + p.add_argument("--report", type=Path) + p.add_argument("--ar-cfg", type=float, default=1.5) + p.add_argument("--label", default="") + a = p.parse_args() + report: dict = {"ref": str(a.ref), "mine": str(a.mine), "label": a.label} + for name, fn in (("states.npy", lambda: check_ar(a.ref, a.mine, report, a.ar_cfg)), + ("probe_cond_1.0.npy", lambda: check_probe(a.ref, a.mine, report)), + ("latent.npy", lambda: check_dit(a.ref, a.mine, report)), + ("audio.npy", lambda: check_dav(a.ref, a.mine, report))): + if (a.mine / name).exists() or name == "audio.npy": + fn() + text = json.dumps(report, indent=1) + print(text) + if a.report: + a.report.write_text(text + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/music3/served_test.py b/tools/music3/served_test.py new file mode 100644 index 00000000000..33235465b4a --- /dev/null +++ b/tools/music3/served_test.py @@ -0,0 +1,45 @@ +"""Drive music3-generate --serve 1 through the Studio's own client (app/music.py's Mlx route, voice.Served). + +Copy this file beside a Studio checkout's app/ folder (main 86ae680 or later) and run it with the Studio venv: + python served_test.py PROMPTS OUT_DIR (env MUSIC3_BIN, default music3-generate on PATH) +""" +import json, os, sys, time +from pathlib import Path +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE / "app")) +os.environ.setdefault("MUSIC3_GUARD_GB", "25") +import music # noqa: E402 + +BIN = os.path.expanduser(os.environ.get("MUSIC3_BIN", "music3-generate")) + + +class Cuda(music.Mlx): + name, label = "cuda", "TensorFold CUDA · DGX Spark" + def argv(self): + return [BIN, "--serve", "1"] + def check(self): + return "" + + +def main(): + P = Path(sys.argv[1]).expanduser() # hiphop.caption, hiphop.lyrics, pop.caption, pop.lyrics + out = Path(sys.argv[2]).expanduser() + out.mkdir(parents=True, exist_ok=True) + s = Cuda() + seen = [] + for i, (name, secs, seed) in enumerate((("hiphop", 20, 7), ("pop", 15, 11))): + job = {"id": f"served-{i}", "status": "running", "progress": None} + params = {"caption": (P / f"{name}.caption").read_text(), "lyrics": (P / f"{name}.lyrics").read_text(), "seconds": secs, + "seed": seed, "ar_cfg": 1.5, "top_k": 50, "steps": 30, "dit_cfg": 1.7} + t0 = time.time() + res = s.make(job, params, out / f"{name}.wav") + seen.append({"request": i, "result": res, "ready": s.ready, "wall_s": round(time.time() - t0, 1), + "last_progress": job.get("progress"), "stats_file": json.loads((out / f"{name}.stats.json").read_text()) if (out / f"{name}.stats.json").exists() else None}) + print(json.dumps(seen[-1]), flush=True) + s.stop("test done") + print("events", json.dumps(s.events)) + print("log tail", s.log[-6:]) + + +if __name__ == "__main__": + main() diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 684d6c3cc9d..2ac7958f0fe 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -52,6 +52,7 @@ const kernels = [_]Kernel{ .{ .name = "glm_glue", .flags = &.{"-O3"} }, // ours: the Python family's Triton glue by hand, its PTX op for op .{ .name = "glm_ops", .flags = &.{"-O3"} }, // ours: GLM's integer work the Python family did in torch (the DSA token lists) .{ .name = "glm_quant", .flags = torch_ops }, // ours: GLM's draft-only weight quantizers, torch at load in the Python family + .{ .name = "music3", .flags = &.{"-O3"} }, // ours: MiniMax Music 3's AR GEMVs, sampler and the DiT / DAV glue .{ .name = "torch_argmax", .src = "torch_ops/argmax", .flags = torch_ops }, .{ .name = "torch_topk", .src = "torch_ops/topk", .flags = torch_ops }, .{ .name = "torch_pointwise", .src = "torch_ops/pointwise", .flags = torch_ops }, @@ -159,6 +160,14 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu 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; + const m3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/music3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "music3", .module = music3Module(b, target, optimize, cuda, mods.core) } } }); + const m3_exe = b.addExecutable(.{ .name = "music3-generate", .root_module = m3_tool }); + b.step("music3-generate", "MiniMax Music 3 lyrics and a caption to a song on one CUDA GPU").dependOn(&b.addInstallArtifact(m3_exe, .{}).step); +} + +/// MiniMax Music 3 on CUDA: config, prompt ids, weights, the AR frame engine, the DiT and the DAV. +fn music3Module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/families/music3/music3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); } /// The GLM-5.3-Flash CUDA family over the runtime, the core, the lane core, canon's shares and core/heat.zig. @@ -268,7 +277,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), music3Module(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); // 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); diff --git a/zig/build/music3_metal.zig b/zig/build/music3_metal.zig new file mode 100644 index 00000000000..56cebbc7dd8 --- /dev/null +++ b/zig/build/music3_metal.zig @@ -0,0 +1,52 @@ +//! macOS: MiniMax Music 3's metallib, the family module over Metal, `zig build music3-generate` and its host tests. +const std = @import("std"); + +const dir = "zig/kernels/metal/music3"; +const sources = [_][]const u8{ "ar.metal", "attn.metal", "sample.metal", "gemm.metal", "dit.metal", "dit_attn.metal", "dav.metal" }; + +/// Each source compiled with `dir` on the include path (m3_common.h), safe math and precise fp32 functions. +fn metallib(b: *std.Build, metal_std: []const u8) std.Build.LazyPath { + const link = b.addSystemCommand(&.{ "xcrun", "-sdk", "macosx", "metallib", "-o" }); + const out = link.addOutputFileArg("music3.metallib"); + for (sources) |name| { + const cc = b.addSystemCommand(&.{ "xcrun", "-sdk", "macosx", "metal", b.fmt("-std={s}", .{metal_std}), "-fmetal-math-mode=safe", "-fmetal-math-fp32-functions=precise" }); + cc.addPrefixedDirectoryArg("-I", b.path(dir)); + cc.addFileInput(b.path(dir ++ "/m3_common.h")); + cc.addFileInput(b.path("zig/kernels/metal/nax.h")); + cc.addFileInput(b.path("zig/kernels/metal/prefill/gemm_nax.metal")); + cc.addArg("-c"); + cc.addFileArg(b.path(b.fmt("{s}/{s}", .{ dir, name }))); + cc.addArg("-o"); + link.addFileArg(cc.addOutputFileArg(b.fmt("m3_{s}.air", .{std.fs.path.stem(name)}))); + } + return out; +} + +pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, metal_std: []const u8, test_step: *std.Build.Step) void { + const lib = metallib(b, metal_std); + b.getInstallStep().dependOn(&b.addInstallFile(lib, "lib/music3.metallib").step); + const wf = b.addWriteFiles(); + _ = wf.addCopyFile(lib, "music3.metallib"); + const bytes = b.createModule(.{ .root_source_file = wf.add("metallib.zig", "pub const bytes = @embedFile(\"music3.metallib\");\n") }); + 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); + const family = b.createModule(.{ + .root_source_file = b.path("zig/src/families/music3/music3_metal.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "music3_metallib", .module = bytes } }, + }); + const tool = b.createModule(.{ + .root_source_file = b.path("zig/src/families/music3/generate.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "music3", .module = family } }, + }); + const exe = b.addExecutable(.{ .name = "music3-generate", .root_module = tool }); + b.installArtifact(exe); + b.step("music3-generate", "MiniMax Music 3 lyrics and a caption to a song on Metal").dependOn(&b.addInstallArtifact(exe, .{}).step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = family })).step); +} diff --git a/zig/kernels/cuda/music3.cu b/zig/kernels/cuda/music3.cu new file mode 100644 index 00000000000..dc2ba5affd2 --- /dev/null +++ b/zig/kernels/cuda/music3.cu @@ -0,0 +1,5 @@ +// ours: MiniMax Music 3 (families/music3) on one GPU, one fatbin; reductions are fixed trees, so the bytes repeat. +#include "music3_ar.cuh" +#include "music3_dav.cuh" +#include "music3_dit.cuh" +#include "music3_sample.cuh" diff --git a/zig/kernels/cuda/music3_ar.cuh b/zig/kernels/cuda/music3_ar.cuh new file mode 100644 index 00000000000..90f2c93d236 --- /dev/null +++ b/zig/kernels/cuda/music3_ar.cuh @@ -0,0 +1,374 @@ +// music3 AR kernels: rows, the decode GEMV (bf16 / int8), the body and depth decoder attention. +#pragma once +#include "music3_common.cuh" + +// ------------------------------------------------------------------------------------------------ AR: rows + +// out[r] = table[ids[r]] (bf16 rows of dim). +extern "C" __global__ void m3_embed(const int* __restrict__ ids, const bf16* __restrict__ table, bf16* __restrict__ out, int dim) { + const size_t r = blockIdx.x; + const uint4* src = reinterpret_cast(table + (size_t)ids[r] * dim); + uint4* dst = reinterpret_cast(out + r * dim); + for (int i = threadIdx.x; i < dim / 8; i += blockDim.x) dst[i] = src[i]; +} + +// out[b] = table[*code + offset] for rows b < rows (the same code for both CFG rows). +extern "C" __global__ void m3_embed_code(const int* __restrict__ code, int offset, const bf16* __restrict__ table, bf16* __restrict__ out, int rows, int dim) { + const uint4* src = reinterpret_cast(table + (size_t)(*code + offset) * dim); + for (int r = 0; r < rows; ++r) { + uint4* dst = reinterpret_cast(out + (size_t)r * dim); + for (int i = threadIdx.x; i < dim / 8; i += blockDim.x) dst[i] = src[i]; + } +} + +// A frame fed back: (audio[c0] + sum extra[c_i + (i - 1) 1024]) / sqrt(8), rounded as torch rounds it, both rows. +extern "C" __global__ void m3_frame_embed(const int* __restrict__ codes, const bf16* __restrict__ audio, const bf16* __restrict__ extra, bf16* __restrict__ out, int rows, int dim, float scale) { + for (int d = blockIdx.x * blockDim.x + threadIdx.x; d < dim; d += gridDim.x * blockDim.x) { + float s = 0.f; +#pragma unroll + for (int i = 1; i < 8; ++i) s += b2f(extra[(size_t)(codes[i] + (i - 1) * 1024) * dim + d]); + const float c0 = b2f(audio[(size_t)codes[0] * dim + d]); + const float v = rb(rb(c0 + rb(s)) * scale); + for (int r = 0; r < rows; ++r) out[(size_t)r * dim + d] = f2b(v); + } +} + +// RMS norm of rows (x rows xs apart, y rows ys apart): y = x rsqrt(mean(x^2) + eps) w, fp32 inside, one rounding. +extern "C" __global__ void m3_rmsnorm(const bf16* __restrict__ x, int xs, const bf16* __restrict__ w, bf16* __restrict__ y, int ys, int dim, float eps) { + __shared__ float sh[32]; + const bf16* xr = x + (size_t)blockIdx.x * xs; + float ss = 0.f; + for (int i = threadIdx.x; i < dim; i += blockDim.x) { + const float v = b2f(xr[i]); + ss = fmaf(v, v, ss); + } + ss = block_sum(ss, sh); + const float rs = 1.0f / sqrtf(ss / (float)dim + eps); + bf16* yr = y + (size_t)blockIdx.x * ys; + for (int i = threadIdx.x; i < dim; i += blockDim.x) yr[i] = f2b(b2f(xr[i]) * rs * b2f(w[i])); +} + +// x = round(x + a): prompt rows' residual adds after cuBLAS GEMMs. +extern "C" __global__ void m3_add(bf16* __restrict__ x, const bf16* __restrict__ a, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) x[i] = f2b(b2f(x[i]) + b2f(a[i])); +} + +// y[r, k] = round(round(silu(g)) u) of gate | up rows [rows, 2 width] (prompt rows). +extern "C" __global__ void m3_swiglu(const bf16* __restrict__ gu, bf16* __restrict__ y, int width, size_t rows) { + const size_t n = rows * width; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const size_t r = i / width, k = i % width; + const float g = b2f(gu[r * 2 * width + k]), u = b2f(gu[r * 2 * width + width + k]); + y[i] = f2b(rb(g / (1.f + expf(-g))) * u); + } +} + +// One bf16 weight row a block to int8 with a symmetric scale absmax / 127 a group of 128 inputs (fp32, [n, k / 128]). +extern "C" __global__ void m3_quant_groups(const bf16* __restrict__ w, int k, int8_t* __restrict__ q, float* __restrict__ sc) { + const bf16* wr = w + (size_t)blockIdx.x * k; + int8_t* qr = q + (size_t)blockIdx.x * k; + const int groups = k / 128, warp = threadIdx.x >> 5, lane = threadIdx.x & 31, nw = blockDim.x >> 5; + for (int gi = warp; gi < groups; gi += nw) { + float v[4], m = 0.f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + v[j] = b2f(wr[gi * 128 + lane + 32 * j]); + m = fmaxf(m, fabsf(v[j])); + } + m = warp_max(m); + const float s = m > 0.f ? m / 127.f : 1.f; + const float inv = 1.f / s; +#pragma unroll + for (int j = 0; j < 4; ++j) qr[gi * 128 + lane + 32 * j] = (int8_t)max(-127, min(127, __float2int_rn(v[j] * inv))); + if (lane == 0) sc[(size_t)blockIdx.x * groups + gi] = s; + } +} + +// int8 rows back to bf16 (round(q s)) for the prompt rows' cuBLAS GEMMs. +extern "C" __global__ void m3_dequant(const int8_t* __restrict__ q, const float* __restrict__ sc, bf16* __restrict__ w, int k, size_t n) { + const size_t total = n * k; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < total; i += (size_t)gridDim.x * blockDim.x) w[i] = f2b((float)q[i] * sc[i / k]); +} + +// One bf16 weight row a block to int8 with a symmetric scale absmax / 127 (fp32). +extern "C" __global__ void m3_quant_rows(const bf16* __restrict__ w, int k, int8_t* __restrict__ q, float* __restrict__ sc) { + __shared__ float sh[32]; + const bf16* wr = w + (size_t)blockIdx.x * k; + float m = 0.f; + for (int i = threadIdx.x; i < k; i += blockDim.x) m = fmaxf(m, fabsf(b2f(wr[i]))); + m = block_max(m, sh); + const float s = m > 0.f ? m / 127.f : 1.f; + const float inv = 1.f / s; + int8_t* qr = q + (size_t)blockIdx.x * k; + for (int i = threadIdx.x; i < k; i += blockDim.x) qr[i] = (int8_t)max(-127, min(127, __float2int_rn(b2f(wr[i]) * inv))); + if (threadIdx.x == 0) sc[blockIdx.x] = s; +} + +// ------------------------------------------------------------------------------------------------ AR: the GEMV + +template +__device__ __forceinline__ void wfloats(const uint4 w4, float* wf) { + const unsigned ws[4] = {w4.x, w4.y, w4.z, w4.w}; + if (I8) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const unsigned u = ws[j] ^ 0x80808080u; + wf[4 * j + 0] = __uint_as_float(__byte_perm(u, 0x4B000000u, 0x7650)) - 8388736.f; + wf[4 * j + 1] = __uint_as_float(__byte_perm(u, 0x4B000000u, 0x7651)) - 8388736.f; + wf[4 * j + 2] = __uint_as_float(__byte_perm(u, 0x4B000000u, 0x7652)) - 8388736.f; + wf[4 * j + 3] = __uint_as_float(__byte_perm(u, 0x4B000000u, 0x7653)) - 8388736.f; + } + } else { +#pragma unroll + for (int j = 0; j < 4; ++j) { + wf[2 * j] = bfu(ws[j] & 0xFFFF); + wf[2 * j + 1] = bfu(ws[j] >> 16); + } + } +} + +// A weight load that streams past L1 (each byte is read once a frame). +__device__ __forceinline__ uint4 ld_stream(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; +} + +// y = W x for M rows (bf16 / int8 W), residual or fp32 logits out, PAIR: SwiGLU of rows n, half + n; PDL prefetch. +template +__device__ __forceinline__ void gemv(const void* __restrict__ wv, const float* __restrict__ sc, const bf16* __restrict__ x, int xs, int K, int N, bf16* y, int ys, float* __restrict__ yf, const bf16* res, int res_div) { + const int n = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + constexpr int E = I8 ? 16 : 8; // weights a 16-byte load + constexpr int R = PAIR ? 2 : 1; + constexpr int U = PAIR ? 4 : 8; + const int rows = PAIR ? N / 2 : N; + const int chunks = K / E; + const int nn = min(n, rows - 1); + const char* wb = reinterpret_cast(wv); + const uint4* wr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) wr[r] = reinterpret_cast(wb + (size_t)(nn + r * rows) * K * (I8 ? 1 : 2)); + uint4 w[R][U]; + int c = lane; +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int r = 0; r < R; ++r) w[r][u] = c + u * 32 < chunks ? ld_stream(wr[r] + c + u * 32) : make_uint4(0, 0, 0, 0); +#if __CUDA_ARCH__ >= 900 + asm volatile("griddepcontrol.wait;\n" ::: "memory"); +#endif + float acc[R][M]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int m = 0; m < M; ++m) acc[r][m] = 0.f; + while (true) { +#pragma unroll + for (int u = 0; u < U; ++u) { + const int cc = c + u * 32; + if (cc >= chunks) break; + float wf[R][E]; + float gs[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + wfloats(w[r][u], wf[r]); + if (GRP) gs[r] = __ldg(sc + (size_t)(nn + r * rows) * (K / 128) + cc / 8); + } +#pragma unroll + for (int m = 0; m < M; ++m) { + const uint4* xp = reinterpret_cast(x + (size_t)m * xs + cc * E); + float xf[E]; +#pragma unroll + for (int hh = 0; hh < E / 8; ++hh) { + const uint4 v = __ldg(xp + hh); + const unsigned vs[4] = {v.x, v.y, v.z, v.w}; +#pragma unroll + for (int j = 0; j < 4; ++j) { + xf[8 * hh + 2 * j] = bfu(vs[j] & 0xFFFF); + xf[8 * hh + 2 * j + 1] = bfu(vs[j] >> 16); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + if (GRP) { // int8 groups of 128 inputs, a scale each: the chunk's partial sum, then times its scale + float part = 0.f; +#pragma unroll + for (int e = 0; e < E; ++e) part = fmaf(wf[r][e], xf[e], part); + acc[r][m] = fmaf(gs[r], part, acc[r][m]); + } else { +#pragma unroll + for (int e = 0; e < E; ++e) acc[r][m] = fmaf(wf[r][e], xf[e], acc[r][m]); + } + } + } + } + c += U * 32; + if (c >= chunks) break; +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int r = 0; r < R; ++r) w[r][u] = c + u * 32 < chunks ? ld_stream(wr[r] + c + u * 32) : make_uint4(0, 0, 0, 0); + } + if (n >= rows) return; +#pragma unroll + for (int m = 0; m < M; ++m) { + float v[R]; +#pragma unroll + for (int r = 0; r < R; ++r) v[r] = warp_sum(acc[r][m]) * (I8 && !GRP ? sc[n + r * rows] : 1.f); + if (lane == 0) { + if (PAIR) { + const float g = rb(v[0]), u = rb(v[1]); + y[(size_t)m * ys + n] = f2b(rb(g / (1.f + __expf(-g))) * u); + } else { + if (yf) yf[(size_t)m * N + n] = rb(v[0]); + if (y) { + float rr = rb(v[0]); + if (res) rr = rb(b2f(res[(size_t)(m / res_div) * N + n]) + rr); + y[(size_t)m * ys + n] = f2b(rr); + } + } + } + } +} + +#define GEMV(NAME, M, I8, PAIR, GRP) \ + extern "C" __global__ void __launch_bounds__(256) NAME(const void* __restrict__ w, const float* __restrict__ sc, const bf16* __restrict__ x, int xs, int K, int N, bf16* y, int ys, float* __restrict__ yf, const bf16* res, int res_div) { \ + gemv(w, sc, x, xs, K, N, y, ys, yf, res, res_div); \ + } +GEMV(m3_gemv_bf16_2, 2, false, false, false) +GEMV(m3_gemv_bf16_4, 4, false, false, false) +GEMV(m3_gemv_i8_2, 2, true, false, false) +GEMV(m3_gemv_i8_4, 4, true, false, false) +GEMV(m3_glu_bf16_2, 2, false, true, false) +GEMV(m3_glu_bf16_4, 4, false, true, false) +GEMV(m3_glu_i8_2, 2, true, true, false) +GEMV(m3_glu_i8_4, 4, true, true, false) +GEMV(m3_gemv_g8_2, 2, true, false, true) +GEMV(m3_gemv_g8_4, 4, true, false, true) +GEMV(m3_glu_g8_2, 2, true, true, true) +GEMV(m3_glu_g8_4, 4, true, true, true) + +// ------------------------------------------------------------------------------------------------ AR: body attention + +// Body q / k: a head's RMS norm, then rotate-half rope; q to q_out, k and v to the caches. grid (rows, 48). +extern "C" __global__ void m3_qk_rope(const bf16* __restrict__ qkv, const bf16* __restrict__ qn, const bf16* __restrict__ kn, const float* __restrict__ inv_freq, const int* __restrict__ pos, int t, bf16* __restrict__ q_out, bf16* __restrict__ kc, bf16* __restrict__ vc, int ctx, float eps) { + __shared__ float sh[32]; + __shared__ float v_sh[128]; + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + const int b = r / t, p = *pos + r % t; + const bf16* row = qkv + (size_t)r * 6144; + if (h >= 40) { // v + const int g = h - 40; + vc[(((size_t)b * 8 + g) * ctx + p) * 128 + d] = row[4096 + 1024 + g * 128 + d]; + return; + } + const bool isq = h < 32; + const bf16* src = isq ? row + h * 128 : row + 4096 + (h - 32) * 128; + const float x = b2f(src[d]); + const float ss = block_sum(x * x, sh); + const float rs = 1.0f / sqrtf(ss / 128.f + eps); + const float nx = rb(x * rs * b2f((isq ? qn : kn)[d])); + v_sh[d] = nx; + __syncthreads(); + const int i = d & 63; + const float ang = (float)p * inv_freq[i]; + const float c = cosf(ang), s = sinf(ang); + const float other = d < 64 ? -v_sh[d + 64] : v_sh[d - 64]; + const bf16 o = f2b(nx * c + other * s); + if (isq) + q_out[((size_t)r * 32 + h) * 128 + d] = o; + else + kc[(((size_t)b * 8 + (h - 32)) * ctx + p) * 128 + d] = o; +} + +// Split-key attention: a block a (kv head, row, split), warps the group's 4 q heads; partials ml / acc a split. +extern "C" __global__ void __launch_bounds__(128) m3_attn_part(const bf16* __restrict__ q, const bf16* __restrict__ kc, const bf16* __restrict__ vc, const int* __restrict__ pos, int t, int ctx, int S, float scale, float* __restrict__ ml, float* __restrict__ acc) { + const int g = blockIdx.x, r = blockIdx.y, sp = blockIdx.z; + const int w = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int h = g * 4 + w; + const int b = r / t; + const int L = *pos + r % t + 1; + const int chunk = (L + S - 1) / S; + const int k0 = sp * chunk, k1 = min(L, k0 + chunk); + const uint2 qv = *reinterpret_cast(q + ((size_t)r * 32 + h) * 128 + lane * 4); + const float q0 = bfu(qv.x & 0xFFFF) * scale, q1 = bfu(qv.x >> 16) * scale, q2 = bfu(qv.y & 0xFFFF) * scale, q3 = bfu(qv.y >> 16) * scale; + const bf16* kb = kc + ((size_t)b * 8 + g) * ctx * 128 + lane * 4; + const bf16* vb = vc + ((size_t)b * 8 + g) * ctx * 128 + lane * 4; + float m = -INFINITY, l = 0.f, a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + for (int j = k0; j < k1; ++j) { + const uint2 kv = __ldg(reinterpret_cast(kb + (size_t)j * 128)); + float s = q0 * bfu(kv.x & 0xFFFF) + q1 * bfu(kv.x >> 16) + q2 * bfu(kv.y & 0xFFFF) + q3 * bfu(kv.y >> 16); + s = warp_sum(s); + const uint2 vv = __ldg(reinterpret_cast(vb + (size_t)j * 128)); + const float mn = fmaxf(m, s); + const float cor = __expf(m - mn), e = __expf(s - mn); + l = l * cor + e; + a0 = a0 * cor + e * bfu(vv.x & 0xFFFF); + a1 = a1 * cor + e * bfu(vv.x >> 16); + a2 = a2 * cor + e * bfu(vv.y & 0xFFFF); + a3 = a3 * cor + e * bfu(vv.y >> 16); + m = mn; + } + const size_t o = ((size_t)r * 32 + h) * S + sp; + if (lane == 0) { + ml[o * 2] = m; + ml[o * 2 + 1] = l; + } + float4* ap = reinterpret_cast(acc + o * 128 + lane * 4); + *ap = make_float4(a0, a1, a2, a3); +} + +// The S partials of a (row, head) into out [rows, 32 * 128] bf16. grid (rows, 32), block 128. +extern "C" __global__ void m3_attn_merge(const float* __restrict__ ml, const float* __restrict__ acc, int S, bf16* __restrict__ out) { + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + const size_t base = ((size_t)r * 32 + h) * S; + float m = -INFINITY; + for (int s = 0; s < S; ++s) m = fmaxf(m, ml[(base + s) * 2]); + float l = 0.f, a = 0.f; + for (int s = 0; s < S; ++s) { + const float ms = ml[(base + s) * 2]; + if (ms == -INFINITY) continue; + const float c = __expf(ms - m); + l += ml[(base + s) * 2 + 1] * c; + a += acc[(base + s) * 128 + d] * c; + } + out[((size_t)r * 32 + h) * 128 + d] = f2b(a / l); +} + +// ------------------------------------------------------------------------------------------------ AR: depth decoder + +// Depth rows' k and v into the caches [b][16][8][256]: pass row r is (position p0 + r / B, batch r % B). +extern "C" __global__ void m3_depth_kv(const bf16* __restrict__ qkv, int p0, int B, bf16* __restrict__ kc, bf16* __restrict__ vc) { + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + const int p = p0 + r / B, b = r % B; + const bf16* row = qkv + (size_t)r * 12288; + const size_t o = (((size_t)b * 16 + h) * 8 + p) * 256 + d; + kc[o] = row[4096 + h * 256 + d]; + vc[o] = row[8192 + h * 256 + d]; +} + +// Causal attention of the depth rows over positions <= p (at most 8), out [rows, 4096]. grid (rows, 16), block 256. +extern "C" __global__ void m3_depth_attn(const bf16* __restrict__ qkv, int p0, int B, const bf16* __restrict__ kc, const bf16* __restrict__ vc, float scale, bf16* __restrict__ out) { + __shared__ float sh[32]; + __shared__ float pr[8]; + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + const int p = p0 + r / B, b = r % B; + const float qd = b2f(qkv[(size_t)r * 12288 + h * 256 + d]); + const bf16* kb = kc + ((size_t)b * 16 + h) * 8 * 256; + const bf16* vb = vc + ((size_t)b * 16 + h) * 8 * 256; + for (int j = 0; j <= p; ++j) { + const float s = block_sum(qd * b2f(kb[j * 256 + d]), sh); + if (d == 0) pr[j] = s * scale; + } + __syncthreads(); + float m = -INFINITY; + for (int j = 0; j <= p; ++j) m = fmaxf(m, pr[j]); + float l = 0.f, a = 0.f; + for (int j = 0; j <= p; ++j) { + const float e = __expf(pr[j] - m); + l += e; + a = fmaf(e, b2f(vb[j * 256 + d]), a); + } + out[(size_t)r * 4096 + h * 256 + d] = f2b(a / l); +} diff --git a/zig/kernels/cuda/music3_common.cuh b/zig/kernels/cuda/music3_common.cuh new file mode 100644 index 00000000000..5e8326ff1d8 --- /dev/null +++ b/zig/kernels/cuda/music3_common.cuh @@ -0,0 +1,87 @@ +// music3 kernels: the types, roundings and reductions every part uses, and the Philox counter draws. +#pragma once +#include +#include +#include + +#define FULL 0xffffffffu +typedef __nv_bfloat16 bf16; + +__device__ __forceinline__ float bfu(unsigned short h) { return __uint_as_float(((unsigned)h) << 16); } +__device__ __forceinline__ float b2f(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ bf16 f2b(float v) { return __float2bfloat16_rn(v); } +__device__ __forceinline__ float rb(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } +__device__ __forceinline__ float h2f(__half v) { return __half2float(v); } +__device__ __forceinline__ __half f2h(float v) { return __float2half_rn(v); } +__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(FULL, 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(FULL, v, o)); + return v; +} +// Block sum (blockDim a multiple of 32, <= 1024): warp trees, then the first warp's tree. All threads get the sum. +__device__ __forceinline__ float block_sum(float v, float* sh) { + v = warp_sum(v); + const int w = threadIdx.x >> 5, l = threadIdx.x & 31, nw = blockDim.x >> 5; + __syncthreads(); + if (l == 0) sh[w] = v; + __syncthreads(); + float t = l < nw ? sh[l] : 0.f; + t = warp_sum(t); + return t; +} +__device__ __forceinline__ float block_max(float v, float* sh) { + v = warp_max(v); + const int w = threadIdx.x >> 5, l = threadIdx.x & 31, nw = blockDim.x >> 5; + __syncthreads(); + if (l == 0) sh[w] = v; + __syncthreads(); + float t = l < nw ? sh[l] : -INFINITY; + return warp_max(t); +} + + +struct Philox { + __device__ static void round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3, uint32_t k0, uint32_t k1) { + const uint64_t p0 = (uint64_t)0xD2511F53u * c0, p1 = (uint64_t)0xCD9E8D57u * c2; + const uint32_t h0 = (uint32_t)(p0 >> 32), l0 = (uint32_t)p0, h1 = (uint32_t)(p1 >> 32), l1 = (uint32_t)p1; + const uint32_t n0 = h1 ^ c1 ^ k0, n2 = h0 ^ c3 ^ k1; + c0 = n0; + c1 = l1; + c2 = n2; + c3 = l0; + } + // Philox4x32-10 of counter (a, b) under key seed: the first word as a uniform in [0, 1) (24 bits). + __device__ static float uniform(unsigned long long seed, unsigned long long a, unsigned long long b) { + uint32_t c0 = (uint32_t)a, c1 = (uint32_t)(a >> 32), c2 = (uint32_t)b, c3 = (uint32_t)(b >> 32); + uint32_t k0 = (uint32_t)seed, k1 = (uint32_t)(seed >> 32); +#pragma unroll + for (int i = 0; i < 10; ++i) { + round(c0, c1, c2, c3, k0, k1); + k0 += 0x9E3779B9u; + k1 += 0xBB67AE85u; + } + return (float)(c0 >> 8) * (1.0f / 16777216.0f); + } + // Two normals (Box-Muller) of counter (a, b). + __device__ static float2 normal2(unsigned long long seed, unsigned long long a, unsigned long long b) { + uint32_t c0 = (uint32_t)a, c1 = (uint32_t)(a >> 32), c2 = (uint32_t)b, c3 = (uint32_t)(b >> 32); + uint32_t k0 = (uint32_t)seed, k1 = (uint32_t)(seed >> 32); +#pragma unroll + for (int i = 0; i < 10; ++i) { + round(c0, c1, c2, c3, k0, k1); + k0 += 0x9E3779B9u; + k1 += 0xBB67AE85u; + } + const float u1 = ((float)(c0 >> 8) + 1.0f) * (1.0f / 16777216.0f); + const float u2 = (float)(c1 >> 8) * (1.0f / 16777216.0f); + const float rr = sqrtf(-2.f * logf(u1)); + return make_float2(rr * cosf(6.2831853071795864f * u2), rr * sinf(6.2831853071795864f * u2)); + } +}; diff --git a/zig/kernels/cuda/music3_dav.cuh b/zig/kernels/cuda/music3_dav.cuh new file mode 100644 index 00000000000..93bedd8a4b7 --- /dev/null +++ b/zig/kernels/cuda/music3_dav.cuh @@ -0,0 +1,59 @@ +// music3 DAV kernels (fp32): snake, bias rows, the transposed convs' overlap-add, the halves and tanh. +#pragma once +#include "music3_common.cuh" + +// ------------------------------------------------------------------------------------------------ DAV (fp32) + +// Snake: y = x + sin^2(alpha x) / (alpha + 1e-9), x [T, C] time-major (C contiguous). y may be x. +extern "C" __global__ void m3_snake(const float* __restrict__ x, const float* __restrict__ alpha, float* __restrict__ y, int C, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const float a = alpha[i % C], v = x[i]; + const float s = sinf(a * v); + y[i] = v + (1.0f / (a + 1e-9f)) * (s * s); + } +} + +// y[t, c] = bias[c] for T rows (before the taps' GEMMs accumulate). +extern "C" __global__ void m3_bias_rows(float* __restrict__ y, const float* __restrict__ bias, int C, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) y[i] = bias[i % C]; +} + +// Transposed conv overlap-add: taps z [Tin, 2s, C] into y [Tout, C] + bias, each output its two sources in order. +extern "C" __global__ void m3_overlap_add(const float* __restrict__ z, const float* __restrict__ bias, int Tin, int stride, int pad, int C, int Tout, float* __restrict__ y) { + const size_t n = (size_t)Tout * C; + const int K = 2 * stride; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const int t = (int)(i / C), c = (int)(i % C); + float s = bias[c]; + const int u = t + pad; + // ti s + j = u, 0 <= j < 2s: ti in [ceil((u - 2s + 1) / s), u / s] + const int hi = u / stride; + for (int ti = hi; ti >= 0 && ti > hi - 2; --ti) { + const int j = u - ti * stride; + if (j < 0 || j >= K || ti >= Tin) continue; + s += z[((size_t)ti * K + j) * C + c]; + } + y[i] = s; + } +} + +// Zero the halo rows of a padded buffer [pad + T + pad, C] (T rows at offset pad). +extern "C" __global__ void m3_zero_rows(float* __restrict__ y, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) y[i] = 0.f; +} + +// y[t, c] += bias[c]. +extern "C" __global__ void m3_add_bias(float* __restrict__ y, const float* __restrict__ bias, int C, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) y[i] += bias[i % C]; +} + +// One stereo half of latent rows [a, a + T) of lat [L, 128] (fp32): out [T, 64] = lat[a + t, half 64 + c]. +extern "C" __global__ void m3_latent_half(const float* __restrict__ lat, int a, int T, int half, float* __restrict__ out) { + const size_t n = (size_t)T * 64; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) out[i] = lat[(size_t)(a + i / 64) * 128 + half * 64 + i % 64]; +} + +// The decoder's tanh, rows [T] of one channel. +extern "C" __global__ void m3_tanh(float* __restrict__ y, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) y[i] = tanhf(y[i]); +} diff --git a/zig/kernels/cuda/music3_dit.cuh b/zig/kernels/cuda/music3_dit.cuh new file mode 100644 index 00000000000..c56efa7fadf --- /dev/null +++ b/zig/kernels/cuda/music3_dit.cuh @@ -0,0 +1,410 @@ +// music3 DiT kernels: the condition, the windows, LayerNorm, flash attention, GLU and the Euler step. +#pragma once +#include "music3_common.cuh" + +// ------------------------------------------------------------------------------------------------ DiT + +// The condition mix of frame states [T, 8, 4096] (bf16) in fp16: sum_l w_l h_l (fp32 sum, fp16 out) times scale (fp16). +extern "C" __global__ void m3_cond_mix(const bf16* __restrict__ states, const float* __restrict__ w8, float scale, __half* __restrict__ out, int T) { + const size_t n = (size_t)T * 4096; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const size_t t = i / 4096, d = i % 4096; + float s = 0.f; +#pragma unroll + for (int l = 0; l < 8; ++l) s = fmaf(rh(b2f(states[(t * 8 + l) * 4096 + d])), w8[l], s); + out[i] = f2h(rh(rh(s) * scale)); + } +} + +// im2col for the k=3, pad 1 condition conv: col [T, 3, 4096] from x [T, 4096] (fp16; zero outside). +extern "C" __global__ void m3_im2col3(const __half* __restrict__ x, __half* __restrict__ col, int T, int C) { + const size_t n = (size_t)T * 3 * C; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const size_t t = i / (3 * C), rem = i % (3 * C); + const int k = (int)(rem / C), c = (int)(rem % C); + const long src = (long)t + k - 1; + col[i] = (src >= 0 && src < T) ? x[(size_t)src * C + c] : f2h(0.f); + } +} + +// Window inputs [S, Lw, 2304] = [x, 0, condition] (branch 1 reads the null condition, the bias); short rows 0. +extern "C" __global__ void m3_dit_input(const float* __restrict__ x, const __half* __restrict__ cond, const __half* __restrict__ null_row, const int* __restrict__ wins, int nwin, int Lw, __half* __restrict__ full) { + const int s = blockIdx.y, j = blockIdx.x; + const int w = s % nwin, branch = s / nwin; + const int start = wins[2 * w], len = wins[2 * w + 1]; + __half* row = full + ((size_t)s * Lw + j) * 2304; + for (int c = threadIdx.x; c < 2304; c += blockDim.x) { + float v = 0.f; + if (j < len) { + const int t = start + j; + if (c < 128) + v = x[(size_t)t * 128 + c]; + else if (c >= 256) + v = branch == 0 ? h2f(cond[(size_t)t * 2048 + c - 256]) : h2f(null_row[c - 256]); + } + row[c] = f2h(v); + } +} + +// a = round(a + b) in fp16. +extern "C" __global__ void m3_add_h(__half* __restrict__ a, const __half* __restrict__ b, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) a[i] = f2h(h2f(a[i]) + h2f(b[i])); +} + +// The timestep embedding input: [cos(2 pi t f), sin(2 pi t f)] (fp32, then fp16), f = features [128]. +extern "C" __global__ void m3_time_features(const __half* __restrict__ f, float t, __half* __restrict__ out) { + const int i = threadIdx.x; // 128 + const float a = 2.f * 3.14159265358979323846f * t * h2f(f[i]); + out[i] = f2h(cosf(a)); + out[128 + i] = f2h(sinf(a)); +} + +// y = silu(x) (fp16) for the timestep MLP. +extern "C" __global__ void m3_silu_h(const __half* __restrict__ x, __half* __restrict__ y, int n) { + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const float v = h2f(x[i]); + y[i] = f2h(v / (1.f + expf(-v))); + } +} + +// One fp16 row through a small Linear: y [N] = round(W [N, K] x + b) (fp32 sum), a warp an output. +extern "C" __global__ void m3_linear_h1(const __half* __restrict__ w, const __half* __restrict__ b, const __half* __restrict__ x, int K, int N, __half* __restrict__ y) { + const int n = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (n >= N) return; + float s = 0.f; + for (int k = lane; k < K; k += 32) s = fmaf(h2f(w[(size_t)n * K + k]), h2f(x[k]), s); + s = warp_sum(s); + if (lane == 0) y[n] = f2h(s + (b ? h2f(b[n]) : 0.f)); +} + +// dst [n, C] = src [idx[i], C] (fp16 rows: the condition's nearest-neighbour stretch to the latent timeline). +extern "C" __global__ void m3_gather_rows_h(const __half* __restrict__ src, const int* __restrict__ idx, __half* __restrict__ dst, int C) { + const size_t i = blockIdx.x; + for (int c = threadIdx.x; c < C; c += blockDim.x) dst[i * C + c] = src[(size_t)idx[i] * C + c]; +} + +// Row 0 of each sequence of h [S, Lseq, 2048] = the timestep embedding. +extern "C" __global__ void m3_put_time(const __half* __restrict__ te, __half* __restrict__ h, int Lseq) { + const int s = blockIdx.x; + for (int c = threadIdx.x; c < 2048; c += blockDim.x) h[(size_t)s * Lseq * 2048 + c] = te[c]; +} + +// LayerNorm (eps 1e-5) of fp16 rows of 2048 in fp32; `bias` first adds the previous block's ff_out bias into x. +extern "C" __global__ void m3_layernorm_h(__half* __restrict__ x, const __half* __restrict__ bias, const __half* __restrict__ g, const __half* __restrict__ b, __half* __restrict__ y) { + __shared__ float sh[32]; + __half* xr = x + (size_t)blockIdx.x * 2048; + float v[8]; + float s = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int c = threadIdx.x + 256 * j; + v[j] = h2f(xr[c]); + if (bias) { + v[j] = rh(v[j] + h2f(bias[c])); + xr[c] = f2h(v[j]); + } + s += v[j]; + } + const float mean = block_sum(s, sh) / 2048.f; + float q = 0.f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float d = v[j] - mean; + q = fmaf(d, d, q); + } + const float var = block_sum(q, sh) / 2048.f; + const float rs = 1.0f / sqrtf(var + 1e-5f); + __half* yr = y + (size_t)blockIdx.x * 2048; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int c = threadIdx.x + 256 * j; + yr[c] = f2h((v[j] - mean) * rs * h2f(g[c]) + h2f(b[c])); + } +} + +// h [rows, 2048] = round(h + bias) (the last block's ff_out bias). +extern "C" __global__ void m3_bias_h(__half* __restrict__ h, const __half* __restrict__ bias, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) h[i] = f2h(h2f(h[i]) + h2f(bias[i % 2048])); +} + +// q, k with rope on dims 0..31 and v, from qkv rows into head-major [S, 32, Lseq, 64] (the unfused path). +extern "C" __global__ void m3_dit_rope(const __half* __restrict__ qkv, const float* __restrict__ cs, int Lseq, __half* __restrict__ q, __half* __restrict__ k, __half* __restrict__ v) { + const int j = blockIdx.x, s = blockIdx.y; + const __half* row = qkv + ((size_t)s * Lseq + j) * 6144; + for (int e = threadIdx.x; e < 2048; e += blockDim.x) { + const int h = e >> 6, d = e & 63; + const size_t o = (((size_t)s * 32 + h) * Lseq + j) * 64 + d; + v[o] = row[4096 + e]; + float qv = h2f(row[e]), kv = h2f(row[2048 + e]); + if (d < 32) { + const int i = d & 15; + const float c = cs[(j * 16 + i) * 2], sn = cs[(j * 16 + i) * 2 + 1]; + const int pe = d < 16 ? e + 16 : e - 16; + const float qo = h2f(row[pe]), ko = h2f(row[2048 + pe]); + if (d < 16) { + qv = qv * c - qo * sn; + kv = kv * c - ko * sn; + } else { + qv = qv * c + qo * sn; + kv = kv * c + ko * sn; + } + } + q[o] = f2h(qv); + k[o] = f2h(kv); + } +} + +// Softmax of fp32 score rows over each sequence's key length, fp16 probabilities (the unfused attention path). +extern "C" __global__ void m3_softmax_rows(const float* __restrict__ sc, int ld, int Lseq, const int* __restrict__ lens, int s0, __half* __restrict__ p) { + __shared__ float sh[32]; + const int j = blockIdx.x, bh = blockIdx.y; + const int s = s0 + bh / 32; + const int L = lens[s]; + const float* row = sc + ((size_t)bh * Lseq + j) * ld; + __half* pr = p + ((size_t)bh * Lseq + j) * ld; + float m = -INFINITY; + for (int i = threadIdx.x; i < L; i += blockDim.x) m = fmaxf(m, row[i]); + m = block_max(m, sh); + float sum = 0.f; + for (int i = threadIdx.x; i < L; i += blockDim.x) sum += __expf(row[i] - m); + sum = block_sum(sum, sh); + const float inv = 1.f / sum; + for (int i = threadIdx.x; i < ld; i += blockDim.x) pr[i] = f2h(i < L ? __expf(row[i] - m) * inv : 0.f); +} + +// mma.sync m16n8k16 (fp16 in, fp32 accumulate) and ldmatrix for the flash attention below. +#define FA_PAD 72 +__device__ __forceinline__ void mma16816(float* c, const unsigned* a, unsigned b0, unsigned b1) { + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.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"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); +} +__device__ __forceinline__ void ldsm4(unsigned* r, const void* p) { + const unsigned a = (unsigned)__cvta_generic_to_shared(p); + 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"(a)); +} +__device__ __forceinline__ void ldsm4t(unsigned* r, const void* p) { + const unsigned a = (unsigned)__cvta_generic_to_shared(p); + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); +} +__device__ __forceinline__ unsigned pack_h2(float lo, float hi) { + const __half2 h = __floats2half2_rn(lo, hi); + return *reinterpret_cast(&h); +} + +// A qkv row's element d with rope on dims 0..31 (split halves, cs [Lseq, 16, 2]), rounded to fp16 as the reference. +__device__ __forceinline__ float rope_at(const __half* row, int d, const float* cs, int j) { + const float x = h2f(row[d]); + if ((d & 63) >= 32) return x; + const int i = d & 15; + const float c = cs[(j * 16 + i) * 2], sn = cs[(j * 16 + i) * 2 + 1]; + return (d & 63) < 16 ? rh(x * c - h2f(row[d + 16]) * sn) : rh(x * c + h2f(row[d - 16]) * sn); +} + +// rope on a k row segment (8 dims, seg 0..3) from it and its partner seg ^ 2 at position j, rounded to fp16. +__device__ __forceinline__ uint4 rope_seg(uint4 a, uint4 p, int seg, const float* cs, int j) { + const __half2* ah = reinterpret_cast(&a); + const __half2* ph = reinterpret_cast(&p); + uint4 o; + __half2* oh = reinterpret_cast<__half2*>(&o); + const float sign = seg < 2 ? -1.f : 1.f; + const int i0 = (seg & 1) * 8; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const float2 x = __half22float2(ah[e]), y = __half22float2(ph[e]); + const float* c0 = cs + (j * 16 + i0 + 2 * e) * 2; + oh[e] = __floats2half2_rn(x.x * c0[0] + sign * y.x * c0[1], x.y * c0[2] + sign * y.y * c0[3]); + } + return o; +} + +// Flash attention from qkv rows, rope as q and k load: 128 queries a CTA, keys 64 a block, mma.sync, online softmax. +#define FA_ROWS 128 +extern "C" __global__ void __launch_bounds__(256) m3_flash_attn(const __half* __restrict__ qkv, const float* __restrict__ cs, int Lseq, const int* __restrict__ lens, float scale, __half* __restrict__ out) { + __shared__ __align__(16) __half ks[64 * FA_PAD]; + __shared__ __align__(16) __half vs[64 * FA_PAD]; + const int bh = blockIdx.y, s = bh >> 5, h = bh & 31; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3; + const int L = lens[s]; + const __half* rows = qkv + (size_t)s * Lseq * 6144; + const int r0 = blockIdx.x * FA_ROWS + warp * 16; + unsigned qa[4][4]; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int row = r0 + g + (j & 1) * 8, col = kk * 16 + t * 2 + (j >> 1) * 8; + if (row < Lseq) { + const __half* rp = rows + (size_t)row * 6144 + h * 64; + qa[kk][j] = pack_h2(rope_at(rp, col, cs, row), rope_at(rp, col + 1, cs, row)); + } else + qa[kk][j] = 0u; + } + } + float o[8][4]; +#pragma unroll + for (int i = 0; i < 8; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.f; + float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.f, l1 = 0.f; + const float c = scale * 1.4426950408889634f; // exp2 domain + for (int kb = 0; kb < L; kb += 64) { + __syncthreads(); + for (int i = threadIdx.x; i < 64 * 8; i += 256) { + const int row = i >> 3, seg = i & 7; + uint4 kv = make_uint4(0, 0, 0, 0), vv = make_uint4(0, 0, 0, 0); + if (kb + row < Lseq) { + const __half* rp = rows + (size_t)(kb + row) * 6144 + h * 64; + vv = *reinterpret_cast(rp + 4096 + seg * 8); + kv = *reinterpret_cast(rp + 2048 + seg * 8); + if (seg < 4) kv = rope_seg(kv, *reinterpret_cast(rp + 2048 + (seg ^ 2) * 8), seg, cs, kb + row); + } + *reinterpret_cast(ks + row * FA_PAD + seg * 8) = kv; + *reinterpret_cast(vs + row * FA_PAD + seg * 8) = vv; + } + __syncthreads(); + float sc[8][4]; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + sc[nt][0] = sc[nt][1] = sc[nt][2] = sc[nt][3] = 0.f; +#pragma unroll + for (int half = 0; half < 2; ++half) { + unsigned b[4]; + ldsm4(b, ks + (nt * 8 + (lane & 7)) * FA_PAD + half * 32 + (lane >> 3) * 8); + mma16816(sc[nt], qa[half * 2], b[0], b[1]); + mma16816(sc[nt], qa[half * 2 + 1], b[2], b[3]); + } + } + // mask keys past the sequence's length, then the online softmax (rows g and g + 8) + float mx0 = m0, mx1 = m1; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int key = kb + nt * 8 + t * 2 + (j & 1); + sc[nt][j] = key < L ? sc[nt][j] * c : -INFINITY; + } + mx0 = fmaxf(mx0, fmaxf(sc[nt][0], sc[nt][1])); + mx1 = fmaxf(mx1, fmaxf(sc[nt][2], sc[nt][3])); + } + mx0 = fmaxf(mx0, __shfl_xor_sync(FULL, mx0, 1)); + mx0 = fmaxf(mx0, __shfl_xor_sync(FULL, mx0, 2)); + mx1 = fmaxf(mx1, __shfl_xor_sync(FULL, mx1, 1)); + mx1 = fmaxf(mx1, __shfl_xor_sync(FULL, mx1, 2)); + const float cr0 = exp2f(m0 - mx0), cr1 = exp2f(m1 - mx1); + m0 = mx0; + m1 = mx1; + l0 *= cr0; + l1 *= cr1; +#pragma unroll + for (int i = 0; i < 8; ++i) { + o[i][0] *= cr0; + o[i][1] *= cr0; + o[i][2] *= cr1; + o[i][3] *= cr1; + } + unsigned pa[4][4]; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + const float p0 = exp2f(sc[nt][0] - m0), p1 = exp2f(sc[nt][1] - m0), p2 = exp2f(sc[nt][2] - m1), p3 = exp2f(sc[nt][3] - m1); + l0 += p0 + p1; + l1 += p2 + p3; + pa[nt >> 1][(nt & 1) * 2] = pack_h2(p0, p1); + pa[nt >> 1][(nt & 1) * 2 + 1] = pack_h2(p2, p3); + } +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { +#pragma unroll + for (int np = 0; np < 4; ++np) { + unsigned b[4]; + ldsm4t(b, vs + (kk * 16 + (lane & 7) + ((lane >> 3) & 1) * 8) * FA_PAD + np * 16 + (lane >> 4) * 8); + mma16816(o[np * 2], pa[kk], b[0], b[1]); + mma16816(o[np * 2 + 1], pa[kk], b[2], b[3]); + } + } + } + l0 += __shfl_xor_sync(FULL, l0, 1); + l0 += __shfl_xor_sync(FULL, l0, 2); + l1 += __shfl_xor_sync(FULL, l1, 1); + l1 += __shfl_xor_sync(FULL, l1, 2); + const float i0 = 1.f / l0, i1 = 1.f / l1; + const int ra = r0 + g, rb = r0 + g + 8; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + const int d = h * 64 + nt * 8 + t * 2; + if (ra < Lseq) *reinterpret_cast<__half2*>(out + ((size_t)s * Lseq + ra) * 2048 + d) = __floats2half2_rn(o[nt][0] * i0, o[nt][1] * i0); + if (rb < Lseq) *reinterpret_cast<__half2*>(out + ((size_t)s * Lseq + rb) * 2048 + d) = __floats2half2_rn(o[nt][2] * i1, o[nt][3] * i1); + } +} + +// Head-major attention out [S, 32, Lseq, 64] back to token rows [S, Lseq, 2048]. grid (Lseq, S), block 256. +extern "C" __global__ void m3_heads_to_rows(const __half* __restrict__ o, int Lseq, __half* __restrict__ out) { + const int j = blockIdx.x, s = blockIdx.y; + for (int e = threadIdx.x; e < 2048; e += blockDim.x) { + const int h = e >> 6, d = e & 63; + out[((size_t)s * Lseq + j) * 2048 + e] = o[(((size_t)s * 32 + h) * Lseq + j) * 64 + d]; + } +} + +// GLU: round(value * round(silu(gate))) of the ff_in rows plus their bias (rounded to fp16 first), 8 a thread. +extern "C" __global__ void m3_glu_h(const __half* __restrict__ x, const __half* __restrict__ bias, __half* __restrict__ y, size_t rows) { + const size_t n = rows * 1024; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const size_t r = i / 1024, c = (i % 1024) * 8; + const uint4 va = *reinterpret_cast(x + r * 16384 + c); + const uint4 ga = *reinterpret_cast(x + r * 16384 + 8192 + c); + const uint4 vb = *reinterpret_cast(bias + c); + const uint4 gb = *reinterpret_cast(bias + 8192 + c); + const __half2* vh = reinterpret_cast(&va); + const __half2* gh = reinterpret_cast(&ga); + const __half2* vbh = reinterpret_cast(&vb); + const __half2* gbh = reinterpret_cast(&gb); + uint4 o; + __half2* oh = reinterpret_cast<__half2*>(&o); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 vf = __half22float2(vh[j]), gf = __half22float2(gh[j]), vbf = __half22float2(vbh[j]), gbf = __half22float2(gbh[j]); + const float v0 = rh(vf.x + vbf.x), v1 = rh(vf.y + vbf.y), g0 = rh(gf.x + gbf.x), g1 = rh(gf.y + gbf.y); + oh[j] = __floats2half2_rn(v0 * rh(g0 / (1.f + expf(-g0))), v1 * rh(g1 / (1.f + expf(-g1)))); + } + *reinterpret_cast(y + r * 8192 + c) = o; + } +} + +// A batch of windows' guided velocity -(o + post) summed into vsum / vcnt, windows in order (no atomics). +extern "C" __global__ void m3_dit_gather(const __half* __restrict__ o, const __half* __restrict__ post, const int* __restrict__ wins, int nwin, int Lw, float cfg, int L, float* __restrict__ vsum, float* __restrict__ vcnt) { + const size_t n = (size_t)L * 128; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + const int t = (int)(i / 128), c = (int)(i % 128); + float sum = vsum[i]; + float cnt = vcnt[i]; + for (int w = 0; w < nwin; ++w) { + const int start = wins[2 * w], len = wins[2 * w + 1]; + if (t < start || t >= start + len) continue; + const int j = t - start; + const size_t rc = ((size_t)w * Lw + j) * 128 + c, ru = ((size_t)(nwin + w) * Lw + j) * 128 + c; + const float vc = -rh(h2f(o[rc]) + h2f(post[rc])); + const float vu = -rh(h2f(o[ru]) + h2f(post[ru])); + sum += vu + (vc - vu) * cfg; + cnt += 1.f; + } + vsum[i] = sum; + vcnt[i] = cnt; + } +} + +// Euler: x += (vsum / vcnt) (sigma_next - sigma); the sums cleared for the next step. +extern "C" __global__ void m3_euler(float* __restrict__ x, float* __restrict__ vsum, float* __restrict__ vcnt, float dt, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) { + x[i] = fmaf(vsum[i] / vcnt[i], dt, x[i]); + vsum[i] = 0.f; + vcnt[i] = 0.f; + } +} + +// Gaussian noise [n] from (seed, i): Philox normals, two a counter. +extern "C" __global__ void m3_noise(float* __restrict__ x, unsigned long long seed, size_t n) { + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; 2 * i < n; i += (size_t)gridDim.x * blockDim.x) { + const float2 g = Philox::normal2(seed, i, 0x6e6f697365ull); + x[2 * i] = g.x; + if (2 * i + 1 < n) x[2 * i + 1] = g.y; + } +} diff --git a/zig/kernels/cuda/music3_sample.cuh b/zig/kernels/cuda/music3_sample.cuh new file mode 100644 index 00000000000..d1f7f5b39ec --- /dev/null +++ b/zig/kernels/cuda/music3_sample.cuh @@ -0,0 +1,174 @@ +// music3 AR sampling: the CFG top-k draw and the frame bookkeeping inside the frame graph. +#pragma once +#include "music3_common.cuh" + +// ------------------------------------------------------------------------------------------------ AR: sampling + + +__device__ __forceinline__ unsigned ord(float v) { // float -> unsigned with the same order + const unsigned u = __float_as_uint(v); + return (u & 0x80000000u) ? ~u : (u | 0x80000000u); +} + +#define SAMPLE_THREADS 1024 +#define SAMPLE_PER 17 // values a thread: 1024 x 17 >= 16385 +#define SAMPLE_CAP 1024 + +// A CFG top-k draw of logits [2, V] (cond, uncond) by inverse CDF in index order on a Philox uniform; code 0 also. +extern "C" __global__ void __launch_bounds__(SAMPLE_THREADS) m3_sample(const float* __restrict__ logits, int V, float cfg, int top_k, int rank_cond, unsigned long long seed, const unsigned long long* __restrict__ step, int slot, int* __restrict__ pick, int* __restrict__ code, int* __restrict__ tokens, const int* __restrict__ count, const int* __restrict__ force) { + __shared__ unsigned hist[256]; + __shared__ unsigned sel[2]; + __shared__ int cnt_sh[SAMPLE_THREADS / 32]; + __shared__ int cidx[SAMPLE_CAP]; + __shared__ float cval[SAMPLE_CAP]; + __shared__ int ncand; + const int t = threadIdx.x; + const int lo = t * SAMPLE_PER; + unsigned key[SAMPLE_PER]; + float gv[SAMPLE_PER]; +#pragma unroll + for (int j = 0; j < SAMPLE_PER; ++j) { + const int i = lo + j; + if (i < V) { + const float c = logits[i], u = logits[V + i]; + gv[j] = u + (c - u) * cfg; + key[j] = ord(rank_cond ? c : gv[j]); + } else { + gv[j] = -INFINITY; + key[j] = 0; + } + } + // radix select of the top_k-th largest key, 8 bits at a time from the top + unsigned prefix = 0, mask = 0; + int want = max(1, min(top_k, V)); + for (int shift = 24; shift >= 0; shift -= 8) { + if (t < 256) hist[t] = 0; + __syncthreads(); +#pragma unroll + for (int j = 0; j < SAMPLE_PER; ++j) + if (lo + j < V && (key[j] & mask) == prefix) atomicAdd(&hist[(key[j] >> shift) & 255], 1u); + __syncthreads(); + if (t == 0) { + int acc = 0, dgt = 0; + for (int dd = 255; dd >= 0; --dd) { + if (acc + (int)hist[dd] >= want) { + dgt = dd; + break; + } + acc += hist[dd]; + } + sel[0] = dgt; + sel[1] = (unsigned)(want - acc); + } + __syncthreads(); + prefix |= sel[0] << shift; + mask |= 255u << shift; + want = (int)sel[1]; + __syncthreads(); + } + const unsigned thr = prefix; // keys >= thr are the candidates + // compact candidates in index order + int mine = 0; +#pragma unroll + for (int j = 0; j < SAMPLE_PER; ++j) mine += (lo + j < V && key[j] >= thr); + int incl = mine; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int v = __shfl_up_sync(FULL, incl, o); + if ((t & 31) >= o) incl += v; + } + if ((t & 31) == 31) cnt_sh[t >> 5] = incl; + __syncthreads(); + if (t == 0) { + int a = 0; + for (int w = 0; w < SAMPLE_THREADS / 32; ++w) { + const int v = cnt_sh[w]; + cnt_sh[w] = a; + a += v; + } + ncand = min(a, SAMPLE_CAP); + } + __syncthreads(); + int at = cnt_sh[t >> 5] + incl - mine; +#pragma unroll + for (int j = 0; j < SAMPLE_PER; ++j) + if (lo + j < V && key[j] >= thr) { + if (at < SAMPLE_CAP) { + cidx[at] = lo + j; + cval[at] = gv[j]; + } + ++at; + } + __syncthreads(); + if (t != 0) return; + int n = ncand; + int chosen; + if (force) { + chosen = *force; + } else { + if (rank_cond && n > top_k) { + // ComfyUI's second sample_topk: keep values with fewer than top_k strictly greater ones (the top_k with ties) + float kth = INFINITY; + for (int i = 0; i < n; ++i) { + int greater = 0; + for (int j = 0; j < n; ++j) greater += cval[j] > cval[i]; + if (greater < top_k) kth = fminf(kth, cval[i]); + } + int w = 0; + for (int i = 0; i < n; ++i) + if (cval[i] >= kth) { + cidx[w] = cidx[i]; + cval[w] = cval[i]; + ++w; + } + n = w; + } + float m = -INFINITY; + for (int i = 0; i < n; ++i) m = fmaxf(m, cval[i]); + if (top_k <= 1) { + chosen = cidx[0]; + for (int i = 0; i < n; ++i) + if (cval[i] == m) { + chosen = cidx[i]; + break; + } + } else { + float sum = 0.f; + for (int i = 0; i < n; ++i) sum += __expf(cval[i] - m); + const float u = Philox::uniform(seed, *step, (unsigned long long)slot) * sum; + float run = 0.f; + chosen = cidx[n - 1]; + for (int i = 0; i < n; ++i) { + run += __expf(cval[i] - m); + if (u < run) { + chosen = cidx[i]; + break; + } + } + } + } + *pick = chosen; + if (code) *code = max(chosen - 1, 0); + if (tokens) tokens[*count] = chosen; +} + +// After a frame: the next position and step, one frame more. +extern "C" __global__ void m3_frame_done(int* __restrict__ pos, unsigned long long* __restrict__ step, int* __restrict__ count) { + if (threadIdx.x == 0) { + *pos += 1; + *step += 1; + *count += 1; + } +} + +// A frame state's part: states[*count, part] = src (bf16 4096). +extern "C" __global__ void m3_state_part(const bf16* __restrict__ src, bf16* __restrict__ states, const int* __restrict__ count, int part) { + const size_t base = ((size_t)*count * 8 + part) * 4096; + for (int i = threadIdx.x; i < 512; i += blockDim.x) reinterpret_cast(states + base)[i] = reinterpret_cast(src)[i]; +} + +// A forced frame's codes (teacher forcing): codes[0..8) = forced[*count, 0..8). +extern "C" __global__ void m3_force_codes(const int* __restrict__ forced, const int* __restrict__ count, int* __restrict__ codes, int* __restrict__ token) { + if (threadIdx.x < 8) codes[threadIdx.x] = forced[*count * 8 + threadIdx.x]; + if (threadIdx.x == 0) *token = forced[*count * 8] + 1; +} diff --git a/zig/kernels/metal/music3/ar.metal b/zig/kernels/metal/music3/ar.metal new file mode 100644 index 00000000000..c9d9f9253e6 --- /dev/null +++ b/zig/kernels/metal/music3/ar.metal @@ -0,0 +1,238 @@ +// music3 AR rows: embeddings, RMS norm, the decode GEMV (bf16 / int8), int8 quantizing, body and depth attention. +#include "m3_common.h" + +// ------------------------------------------------------------------------------------------------ rows + +// out[r] = table[ids[r]] (bf16 rows of dim). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_embed(device const int* ids [[buffer(0)]], device const uint4* table [[buffer(1)]], + device uint4* out [[buffer(2)]], constant uint& dim [[buffer(3)]], + uint r [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + const uint n = dim / 8; + for (uint i = t; i < n; i += 256) out[(ulong)r * n + i] = table[(ulong)ids[r] * n + i]; +} + +struct CodeArgs { + int offset; + uint rows, dim; +}; + +// out[b] = table[*code + offset] for rows b < rows (the same code for both CFG rows). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_embed_code(device const int* code [[buffer(0)]], device const uint4* table [[buffer(1)]], + device uint4* out [[buffer(2)]], constant CodeArgs& a [[buffer(3)]], + uint t [[thread_index_in_threadgroup]]) { + const uint n = a.dim / 8; + device const uint4* src = table + (ulong)(*code + a.offset) * n; + for (uint r = 0; r < a.rows; ++r) + for (uint i = t; i < n; i += 256) out[(ulong)r * n + i] = src[i]; +} + +struct FrameArgs { + uint rows, dim; + float scale; +}; + +// A frame fed back: (audio[c0] + sum extra[c_i + (i - 1) 1024]) / sqrt(8), rounded as torch rounds it, both rows. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_frame_embed(device const int* codes [[buffer(0)]], device const bf16* audio [[buffer(1)]], + device const bf16* extra [[buffer(2)]], device bf16* out [[buffer(3)]], + constant FrameArgs& a [[buffer(4)]], uint gid [[thread_position_in_grid]], + uint gn [[threads_per_grid]]) { + for (uint d = gid; d < a.dim; d += gn) { + float s = 0.0f; + for (int i = 1; i < 8; ++i) s += b2f(extra[(ulong)(codes[i] + (i - 1) * 1024) * a.dim + d]); + const float c0 = b2f(audio[(ulong)codes[0] * a.dim + d]); + const bf16 v = f2b(rb(c0 + rb(s)) * a.scale); + for (uint r = 0; r < a.rows; ++r) out[(ulong)r * a.dim + d] = v; + } +} + +struct NormArgs { + uint xs, ys, dim; + float eps; +}; + +// RMS norm of rows (x rows xs apart, y rows ys apart): y = x rsqrt(mean(x^2) + eps) w, fp32 inside, one rounding. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_rmsnorm(device const bf16* x [[buffer(0)]], device const bf16* w [[buffer(1)]], + device bf16* y [[buffer(2)]], constant NormArgs& a [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float sh[32]; + device const bf16* xr = x + (ulong)row * a.xs; + float ss = 0.0f; + for (uint i = t; i < a.dim; i += 256) { + const float v = b2f(xr[i]); + ss = fma(v, v, ss); + } + ss = group_sum(ss, sh, sg, lane, 8); + const float rs = 1.0f / precise::sqrt(ss / float(a.dim) + a.eps); + device bf16* yr = y + (ulong)row * a.ys; + for (uint i = t; i < a.dim; i += 256) yr[i] = f2b(b2f(xr[i]) * rs * b2f(w[i])); +} + +// x = round(x + b): prompt rows' residual adds after the GEMMs. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_add(device bf16* x [[buffer(0)]], device const bf16* b [[buffer(1)]], + constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < n) x[i] = f2b(b2f(x[i]) + b2f(b[i])); +} + +struct SwigluArgs { + uint width, rows; +}; + +// y[r, k] = round(round(silu(g)) u) of gate | up rows [rows, 2 width] (prompt rows). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_swiglu(device const bf16* gu [[buffer(0)]], device bf16* y [[buffer(1)]], + constant SwigluArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.width * a.rows) return; + const uint r = i / a.width, k = i % a.width; + const float g = b2f(gu[(ulong)r * 2 * a.width + k]), u = b2f(gu[(ulong)r * 2 * a.width + a.width + k]); + y[i] = f2b(rb(m3_silu(g)) * u); +} + +// ------------------------------------------------------------------------------------------------ int8 + +// One bf16 weight row a group to int8 with a symmetric scale absmax / 127 (fp32): a scale the row, or a group of 128. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_quant(device const bf16* w [[buffer(0)]], device char* q [[buffer(1)]], + device float* sc [[buffer(2)]], constant uint2& a [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float sh[32]; + const uint k = a.x, group = a.y == 0 ? k : a.y, groups = k / group; + device const bf16* wr = w + (ulong)row * k; + device char* qr = q + (ulong)row * k; + for (uint gi = 0; gi < groups; ++gi) { + float m = 0.0f; + for (uint i = t; i < group; i += 256) m = max(m, fabs(b2f(wr[gi * group + i]))); + m = group_max(m, sh, sg, lane, 8); + const float s = m > 0.0f ? m / 127.0f : 1.0f; + const float inv = 1.0f / s; + for (uint i = t; i < group; i += 256) qr[gi * group + i] = char(clamp(int(rint(b2f(wr[gi * group + i]) * inv)), -127, 127)); + if (t == 0) sc[(ulong)row * groups + gi] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +// int8 rows back to bf16 (round(q s)) for the prompt rows' GEMMs; a.y is the group (0: a scale a row). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_dequant(device const char* q [[buffer(0)]], device const float* sc [[buffer(1)]], + device bf16* w [[buffer(2)]], constant uint2& a [[buffer(3)]], + uint2 g [[thread_position_in_grid]]) { + const uint k = a.x, group = a.y == 0 ? k : a.y; + if (g.x >= k) return; + const ulong i = (ulong)g.y * k + g.x; + w[i] = f2b(float(q[i]) * sc[(ulong)g.y * (k / group) + g.x / group]); +} + +// ------------------------------------------------------------------------------------------------ the decode GEMV + +#ifndef M3_GEMV_U +#define M3_GEMV_U 1 +#endif +#ifndef M3_GEMV_SG +#define M3_GEMV_SG 2 +#endif + +struct GemvArgs { + uint xs, K, N, ys, res_div, has_y, has_yf, has_res; +}; + +inline void wfloats(uint4 w, thread float* f, bool i8) { + if (i8) { + const char4 c[4] = {as_type(w.x), as_type(w.y), as_type(w.z), as_type(w.w)}; + for (int j = 0; j < 4; ++j) { + const float4 v = float4(c[j]); + f[4 * j] = v.x; + f[4 * j + 1] = v.y; + f[4 * j + 2] = v.z; + f[4 * j + 3] = v.w; + } + } else { + const float4 a = bf4(w.xy), b = bf4(w.zw); + f[0] = a.x, f[1] = a.y, f[2] = a.z, f[3] = a.w, f[4] = b.x, f[5] = b.y, f[6] = b.z, f[7] = b.w; + } +} + +// y = W x for M rows; a simdgroup two weight rows (two outputs, or a SwiGLU pair n, N / 2 + n), U loads in flight. +template +inline void gemv(device const uchar* W, device const float* sc, device const bf16* x, device bf16* y, device float* yf, + device const bf16* res, constant GemvArgs& a, uint tg, uint sg, uint lane) { + constexpr int E = I8 ? 16 : 8; + constexpr int U = M3_GEMV_U; + const uint outs = PAIR ? a.N / 2 : a.N; + const uint o0 = PAIR ? tg * M3_GEMV_SG + sg : (tg * M3_GEMV_SG + sg) * 2; + if (o0 >= outs) return; + const uint row[2] = {o0, PAIR ? o0 + outs : min(o0 + 1, outs - 1)}; + const uint chunks = a.K / E; + device const uint4* wr[2]; + for (int r = 0; r < 2; ++r) wr[r] = (device const uint4*)(W + (ulong)row[r] * a.K * (I8 ? 1 : 2)); + float acc[2][M]; + for (int r = 0; r < 2; ++r) + for (int m = 0; m < M; ++m) acc[r][m] = 0.0f; + for (uint c0 = lane; c0 < chunks; c0 += 32 * U) { + uint4 wv[U][2]; + for (int u = 0; u < U; ++u) + for (int r = 0; r < 2; ++r) wv[u][r] = c0 + 32 * u < chunks ? wr[r][c0 + 32 * u] : uint4(0); + for (int u = 0; u < U; ++u) { + const uint c = c0 + 32 * u; + if (c >= chunks) break; + float wf[2][E], gs[2] = {1.0f, 1.0f}; + for (int r = 0; r < 2; ++r) { + wfloats(wv[u][r], wf[r], I8); + if (GRP) gs[r] = sc[(ulong)row[r] * (a.K / 128) + c / 8]; + } + for (int m = 0; m < M; ++m) { + device const uint4* xp = (device const uint4*)(x + (ulong)m * a.xs + c * E); + float xf[E]; + for (int h = 0; h < E / 8; ++h) { + const uint4 v = xp[h]; + const float4 p = bf4(v.xy), q = bf4(v.zw); + xf[8 * h] = p.x, xf[8 * h + 1] = p.y, xf[8 * h + 2] = p.z, xf[8 * h + 3] = p.w; + xf[8 * h + 4] = q.x, xf[8 * h + 5] = q.y, xf[8 * h + 6] = q.z, xf[8 * h + 7] = q.w; + } + for (int r = 0; r < 2; ++r) { + float part = 0.0f; + for (int e = 0; e < E; ++e) part = fma(wf[r][e], xf[e], part); + acc[r][m] = GRP ? fma(gs[r], part, acc[r][m]) : acc[r][m] + part; + } + } + } + } + for (int m = 0; m < M; ++m) { + float v[2]; + for (int r = 0; r < 2; ++r) v[r] = simd_sum(acc[r][m]) * (I8 && !GRP ? sc[row[r]] : 1.0f); + if (lane != 0) continue; + if (PAIR) { + const float g = rb(v[0]), u = rb(v[1]); + y[(ulong)m * a.ys + o0] = f2b(rb(m3_silu(g)) * u); + continue; + } + for (int r = 0; r < 2; ++r) { + const uint o = o0 + r; + if (o >= outs) break; + if (a.has_yf) yf[(ulong)m * a.N + o] = rb(v[r]); + if (a.has_y) { + float rr = rb(v[r]); + if (a.has_res) rr = rb(b2f(res[(ulong)(m / a.res_div) * a.N + o]) + rr); + y[(ulong)m * a.ys + o] = f2b(rr); + } + } + } +} + +#define GEMV(NAME, M, I8, PAIR, GRP) \ + [[max_total_threads_per_threadgroup(32 * M3_GEMV_SG)]] kernel void NAME( \ + device const uchar* w [[buffer(0)]], device const float* sc [[buffer(1)]], device const bf16* x [[buffer(2)]], \ + device bf16* y [[buffer(3)]], device float* yf [[buffer(4)]], device const bf16* res [[buffer(5)]], \ + constant GemvArgs& a [[buffer(6)]], uint tg [[threadgroup_position_in_grid]], \ + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { \ + gemv(w, sc, x, y, yf, res, a, tg, sg, lane); \ + } +GEMV(m3_gemv_bf16_2, 2, false, false, false) +GEMV(m3_gemv_bf16_4, 4, false, false, false) +GEMV(m3_gemv_i8_2, 2, true, false, false) +GEMV(m3_gemv_i8_4, 4, true, false, false) +GEMV(m3_gemv_g8_2, 2, true, false, true) +GEMV(m3_gemv_g8_4, 4, true, false, true) +GEMV(m3_glu_bf16_2, 2, false, true, false) +GEMV(m3_glu_bf16_4, 4, false, true, false) +GEMV(m3_glu_i8_2, 2, true, true, false) +GEMV(m3_glu_i8_4, 4, true, true, false) +GEMV(m3_glu_g8_2, 2, true, true, true) +GEMV(m3_glu_g8_4, 4, true, true, true) diff --git a/zig/kernels/metal/music3/attn.metal b/zig/kernels/metal/music3/attn.metal new file mode 100644 index 00000000000..14d37d58443 --- /dev/null +++ b/zig/kernels/metal/music3/attn.metal @@ -0,0 +1,155 @@ +// music3 AR attention: the body's q / k norm and rope, split-key attention and its merge, the depth decoder's. +#include "m3_common.h" + +struct RopeArgs { + uint t, ctx; + float eps; +}; + +// Body q / k: a head's RMS norm, then rotate-half rope; q to q_out, k and v to the caches. grid (rows, 48). +[[max_total_threads_per_threadgroup(128)]] kernel void m3_qk_rope(device const bf16* qkv [[buffer(0)]], device const bf16* qn [[buffer(1)]], + device const bf16* kn [[buffer(2)]], device const float* inv_freq [[buffer(3)]], + device const int* pos [[buffer(4)]], device bf16* q_out [[buffer(5)]], device bf16* kc [[buffer(6)]], + device bf16* vc [[buffer(7)]], constant RopeArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint d [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float sh[32]; + threadgroup float v_sh[128]; + const uint r = tg.x, h = tg.y; + const uint b = r / a.t, p = uint(*pos) + r % a.t; + device const bf16* row = qkv + (ulong)r * 6144; + if (h >= 40) { // v + const uint g = h - 40; + vc[(((ulong)b * 8 + g) * a.ctx + p) * 128 + d] = row[4096 + 1024 + g * 128 + d]; + return; + } + const bool isq = h < 32; + device const bf16* src = isq ? row + h * 128 : row + 4096 + (h - 32) * 128; + const float x = b2f(src[d]); + const float ss = group_sum(x * x, sh, sg, lane, 4); + const float rs = 1.0f / precise::sqrt(ss / 128.0f + a.eps); + const float nx = rb(x * rs * b2f((isq ? qn : kn)[d])); + v_sh[d] = nx; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float ang = float(p) * inv_freq[d & 63]; + const float c = precise::cos(ang), s = precise::sin(ang); + const float other = d < 64 ? -v_sh[d + 64] : v_sh[d - 64]; + const bf16 o = f2b(nx * c + other * s); + if (isq) + q_out[((ulong)r * 32 + h) * 128 + d] = o; + else + kc[(((ulong)b * 8 + (h - 32)) * a.ctx + p) * 128 + d] = o; +} + +struct AttnArgs { + uint t, ctx, splits; + float scale; +}; + +// Split-key attention: a group a (kv head, row, split), simdgroups the 4 q heads; partials ml / acc a split. +[[max_total_threads_per_threadgroup(128)]] kernel void m3_attn_part(device const bf16* q [[buffer(0)]], device const bf16* kc [[buffer(1)]], + device const bf16* vc [[buffer(2)]], device const int* pos [[buffer(3)]], + device float* ml [[buffer(4)]], device float* acc [[buffer(5)]], + constant AttnArgs& a [[buffer(6)]], uint3 tg [[threadgroup_position_in_grid]], + uint w [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint g = tg.x, r = tg.y, sp = tg.z; + const uint h = g * 4 + w, b = r / a.t; + const uint L = uint(*pos) + r % a.t + 1; + const uint chunk = (L + a.splits - 1) / a.splits; + const uint k0 = sp * chunk, k1 = min(L, k0 + chunk); + const float4 qv = bf4(*(device const uint2*)(q + ((ulong)r * 32 + h) * 128 + lane * 4)) * a.scale; + device const bf16* kb = kc + ((ulong)b * 8 + g) * a.ctx * 128 + lane * 4; + device const bf16* vb = vc + ((ulong)b * 8 + g) * a.ctx * 128 + lane * 4; + float m = -INFINITY, l = 0.0f; + float4 o = 0.0f; + uint j = k0; + for (; j + 4 <= k1; j += 4) { // four keys a step: one reduction of their four partial dots + float4 kd; + for (int e = 0; e < 4; ++e) kd[e] = dot(qv, bf4(*(device const uint2*)(kb + (ulong)(j + e) * 128))); + const float4 s = simd_sum(kd); + const float mn = max(m, max(max(s.x, s.y), max(s.z, s.w))); + const float cor = precise::exp(m - mn); + const float4 p = precise::exp(s - mn); + l = l * cor + ((p.x + p.y) + (p.z + p.w)); + o = o * cor; + for (int e = 0; e < 4; ++e) o += p[e] * bf4(*(device const uint2*)(vb + (ulong)(j + e) * 128)); + m = mn; + } + for (; j < k1; ++j) { + const float s = simd_sum(dot(qv, bf4(*(device const uint2*)(kb + (ulong)j * 128)))); + const float4 vv = bf4(*(device const uint2*)(vb + (ulong)j * 128)); + const float mn = max(m, s); + const float cor = precise::exp(m - mn), e = precise::exp(s - mn); + l = l * cor + e; + o = o * cor + e * vv; + m = mn; + } + const ulong at = ((ulong)r * 32 + h) * a.splits + sp; + if (lane == 0) { + ml[at * 2] = m; + ml[at * 2 + 1] = l; + } + *(device float4*)(acc + at * 128 + lane * 4) = o; +} + +// The S partials of a (row, head) into out [rows, 32 * 128] bf16. grid (rows, 32), 128 threads. +[[max_total_threads_per_threadgroup(128)]] kernel void m3_attn_merge(device const float* ml [[buffer(0)]], device const float* acc [[buffer(1)]], + device bf16* out [[buffer(2)]], constant uint& S [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint d [[thread_index_in_threadgroup]]) { + const ulong base = ((ulong)tg.x * 32 + tg.y) * S; + float m = -INFINITY; + for (uint s = 0; s < S; ++s) m = max(m, ml[(base + s) * 2]); + float l = 0.0f, o = 0.0f; + for (uint s = 0; s < S; ++s) { + const float ms = ml[(base + s) * 2]; + if (ms == -INFINITY) continue; + const float c = precise::exp(ms - m); + l += ml[(base + s) * 2 + 1] * c; + o += acc[(base + s) * 128 + d] * c; + } + out[((ulong)tg.x * 32 + tg.y) * 128 + d] = f2b(o / l); +} + +struct DepthArgs { + uint p0, B; + float scale; +}; + +// Depth rows' k and v into the caches [b][16][8][256]: pass row r is (position p0 + r / B, batch r % B). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_depth_kv(device const bf16* qkv [[buffer(0)]], device bf16* kc [[buffer(1)]], + device bf16* vc [[buffer(2)]], constant DepthArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint d [[thread_index_in_threadgroup]]) { + const uint r = tg.x, h = tg.y; + const uint p = a.p0 + r / a.B, b = r % a.B; + device const bf16* row = qkv + (ulong)r * 12288; + const ulong o = (((ulong)b * 16 + h) * 8 + p) * 256 + d; + kc[o] = row[4096 + h * 256 + d]; + vc[o] = row[8192 + h * 256 + d]; +} + +// Causal attention of the depth rows over positions <= p (at most 8), out [rows, 4096]. grid (rows, 16), 256 threads. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_depth_attn(device const bf16* qkv [[buffer(0)]], device const bf16* kc [[buffer(1)]], + device const bf16* vc [[buffer(2)]], device bf16* out [[buffer(3)]], + constant DepthArgs& a [[buffer(4)]], uint2 tg [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float sh[32]; + float pr[8]; + const uint r = tg.x, h = tg.y; + const uint p = a.p0 + r / a.B, b = r % a.B; + const float qd = b2f(qkv[(ulong)r * 12288 + h * 256 + d]); + device const bf16* kb = kc + ((ulong)b * 16 + h) * 8 * 256; + device const bf16* vb = vc + ((ulong)b * 16 + h) * 8 * 256; + float m = -INFINITY; + for (uint j = 0; j <= p; ++j) { + pr[j] = group_sum(qd * b2f(kb[j * 256 + d]), sh, sg, lane, 8) * a.scale; + m = max(m, pr[j]); + } + float l = 0.0f, o = 0.0f; + for (uint j = 0; j <= p; ++j) { + const float e = precise::exp(pr[j] - m); + l += e; + o = fma(e, b2f(vb[j * 256 + d]), o); + } + out[(ulong)r * 4096 + h * 256 + d] = f2b(o / l); +} diff --git a/zig/kernels/metal/music3/dav.metal b/zig/kernels/metal/music3/dav.metal new file mode 100644 index 00000000000..642eb1d1b80 --- /dev/null +++ b/zig/kernels/metal/music3/dav.metal @@ -0,0 +1,62 @@ +// music3 DAV glue (fp32): snake, bias rows, the transposed convs' overlap-add, the stereo halves and tanh. +#include "m3_common.h" + +struct ChanArgs { + uint C, n; +}; + +// Snake: y = x + sin^2(alpha x) / (alpha + 1e-9), x [T, C] time-major (C contiguous). y may be x. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_snake(device const float* x [[buffer(0)]], device const float* alpha [[buffer(1)]], + device float* y [[buffer(2)]], constant ChanArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.n) return; + const float al = alpha[i % a.C], v = x[i]; + const float s = precise::sin(al * v); + y[i] = v + (1.0f / (al + 1e-9f)) * (s * s); +} + +// y[t, c] = bias[c] (set = 1) or y[t, c] += bias[c] (set = 0), over n = T C values. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_bias_rows(device float* y [[buffer(0)]], device const float* bias [[buffer(1)]], + constant uint3& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.y) return; + y[i] = a.z ? bias[i % a.x] : y[i] + bias[i % a.x]; +} + +struct OverlapArgs { + uint Tin, stride, pad, C, Tout; +}; + +// Transposed conv overlap-add: taps z [Tin, 2s, C] into y [Tout, C] + bias, each output its two sources in order. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_overlap_add(device const float* z [[buffer(0)]], device const float* bias [[buffer(1)]], + device float* y [[buffer(2)]], constant OverlapArgs& a [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + if (i >= a.Tout * a.C) return; + const int t = int(i / a.C), c = int(i % a.C), s = int(a.stride), K = 2 * s; + float sum = bias[c]; + const int u = t + int(a.pad); + const int hi = u / s; + for (int ti = hi; ti >= 0 && ti > hi - 2; --ti) { + const int j = u - ti * s; + if (j < 0 || j >= K || ti >= int(a.Tin)) continue; + sum += z[((ulong)ti * K + j) * a.C + c]; + } + y[i] = sum; +} + +// y[0, n) = 0 (the halo rows of a padded buffer). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_zero(device float* y [[buffer(0)]], constant uint& n [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + if (i < n) y[i] = 0.0f; +} + +// One stereo half of latent rows [a, a + T) of lat [L, 128] (fp32): out [T, 64] = lat[a + t, half 64 + c]. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_latent_half(device const float* lat [[buffer(0)]], device float* out [[buffer(1)]], + constant uint3& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.y * 64) return; + out[i] = lat[(ulong)(a.x + i / 64) * 128 + a.z * 64 + i % 64]; +} + +// The decoder's tanh, rows [T] of one channel. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_tanh(device float* y [[buffer(0)]], constant uint& n [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + if (i < n) y[i] = precise::tanh(y[i]); +} diff --git a/zig/kernels/metal/music3/dit.metal b/zig/kernels/metal/music3/dit.metal new file mode 100644 index 00000000000..a59da25e423 --- /dev/null +++ b/zig/kernels/metal/music3/dit.metal @@ -0,0 +1,174 @@ +// music3 DiT glue in fp16: the condition, the windows, LayerNorm, rope, GLU, the guided velocity and the Euler step. +#include "m3_common.h" + +// The condition mix of frame states [T, 8, 4096] (bf16) in fp16: sum_l w_l h_l (fp32 sum, fp16 out) times scale (fp16). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_cond_mix(device const bf16* states [[buffer(0)]], device const float* w8 [[buffer(1)]], + device half* out [[buffer(2)]], constant float2& a [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + const uint n = uint(a.y) * 4096; + if (i >= n) return; + const uint t = i / 4096, d = i % 4096; + float s = 0.0f; + for (int l = 0; l < 8; ++l) s = fma(rh(b2f(states[((ulong)t * 8 + l) * 4096 + d])), w8[l], s); + out[i] = half(rh(rh(s) * a.x)); +} + +// im2col for the k=3, pad 1 condition conv: col [T, 3, 4096] from x [T, 4096] (fp16; zero outside). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_im2col3(device const half* x [[buffer(0)]], device half* col [[buffer(1)]], + constant uint& T [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= T * 3 * 4096) return; + const uint t = i / (3 * 4096), rem = i % (3 * 4096); + const int src = int(t) + int(rem / 4096) - 1; + col[i] = (src >= 0 && src < int(T)) ? x[(ulong)src * 4096 + rem % 4096] : half(0.0f); +} + +// Window inputs [S, Lw, 2304] = [x, 0, condition] (branch 1 reads the null condition, the bias); short rows 0. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_dit_input(device const float* x [[buffer(0)]], device const half* cond [[buffer(1)]], + device const half* null_row [[buffer(2)]], device const int* wins [[buffer(3)]], + device half* full [[buffer(4)]], constant uint2& a [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + const uint nwin = a.x, Lw = a.y, s = tg.y, j = tg.x; + const uint w = s % nwin, branch = s / nwin; + const int start = wins[2 * w], len = wins[2 * w + 1]; + device half* row = full + ((ulong)s * Lw + j) * 2304; + for (uint c = t; c < 2304; c += 256) { + float v = 0.0f; + if (int(j) < len) { + const ulong tt = ulong(start) + j; + if (c < 128) v = x[tt * 128 + c]; + else if (c >= 256) v = branch == 0 ? float(cond[tt * 2048 + c - 256]) : float(null_row[c - 256]); + } + row[c] = half(v); + } +} + +// a = round(a + b) in fp16. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_add_h(device half* a [[buffer(0)]], device const half* b [[buffer(1)]], + constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < n) a[i] = half(float(a[i]) + float(b[i])); +} + +// The timestep embedding input: [cos(2 pi t f), sin(2 pi t f)] (fp32, then fp16), f = features [128]. +[[max_total_threads_per_threadgroup(128)]] kernel void m3_time_features(device const half* f [[buffer(0)]], device half* out [[buffer(1)]], + constant float& t [[buffer(2)]], uint i [[thread_index_in_threadgroup]]) { + const float a = 2.0f * 3.14159265358979323846f * t * float(f[i]); + out[i] = half(precise::cos(a)); + out[128 + i] = half(precise::sin(a)); +} + +// y = silu(x) (fp16) for the timestep MLP. +[[max_total_threads_per_threadgroup(1024)]] kernel void m3_silu_h(device const half* x [[buffer(0)]], device half* y [[buffer(1)]], + constant uint& n [[buffer(2)]], uint t [[thread_index_in_threadgroup]]) { + for (uint i = t; i < n; i += 1024) y[i] = half(m3_silu(float(x[i]))); +} + +struct SmallArgs { + uint K, N; +}; + +// One fp16 row through a small Linear: y [N] = round(W [N, K] x + b) (fp32 sum), a simdgroup an output. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_linear_h1(device const half* w [[buffer(0)]], device const half* b [[buffer(1)]], + device const half* x [[buffer(2)]], device half* y [[buffer(3)]], constant SmallArgs& a [[buffer(4)]], + uint tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg * 8 + sg; + if (n >= a.N) return; + float s = 0.0f; + for (uint k = lane; k < a.K; k += 32) s = fma(float(w[(ulong)n * a.K + k]), float(x[k]), s); + s = simd_sum(s); + if (lane == 0) y[n] = half(s + float(b[n])); +} + +// dst [n, 2048] = src [idx[i], 2048] (fp16 rows: the condition's nearest-neighbour stretch to the latent timeline). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_gather_rows_h(device const half* src [[buffer(0)]], device const int* idx [[buffer(1)]], + device half* dst [[buffer(2)]], uint i [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + for (uint c = t; c < 2048; c += 256) dst[(ulong)i * 2048 + c] = src[(ulong)idx[i] * 2048 + c]; +} + +// Row 0 of each sequence of h [S, Lseq, 2048] = the timestep embedding. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_put_time(device const half* te [[buffer(0)]], device half* h [[buffer(1)]], + constant uint& Lseq [[buffer(2)]], uint s [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + for (uint c = t; c < 2048; c += 256) h[(ulong)s * Lseq * 2048 + c] = te[c]; +} + +// LayerNorm (eps 1e-5) of fp16 rows of 2048 in fp32; `has_bias` first adds the previous block's ff_out bias into x. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_layernorm_h(device half* x [[buffer(0)]], device const half* bias [[buffer(1)]], + device const half* g [[buffer(2)]], device const half* b [[buffer(3)]], device half* y [[buffer(4)]], + constant uint& has_bias [[buffer(5)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float sh[32]; + device half* xr = x + (ulong)row * 2048; + float v[8]; + float s = 0.0f; + for (int j = 0; j < 8; ++j) { + const uint c = t + 256 * j; + v[j] = float(xr[c]); + if (has_bias) { + v[j] = rh(v[j] + float(bias[c])); + xr[c] = half(v[j]); + } + s += v[j]; + } + const float mean = group_sum(s, sh, sg, lane, 8) / 2048.0f; + float q = 0.0f; + for (int j = 0; j < 8; ++j) q = fma(v[j] - mean, v[j] - mean, q); + const float var = group_sum(q, sh, sg, lane, 8) / 2048.0f; + const float rs = 1.0f / precise::sqrt(var + 1e-5f); + device half* yr = y + (ulong)row * 2048; + for (int j = 0; j < 8; ++j) { + const uint c = t + 256 * j; + yr[c] = half((v[j] - mean) * rs * float(g[c]) + float(b[c])); + } +} + +// h [rows, 2048] = round(h + bias) (the last block's ff_out bias). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_bias_h(device half* h [[buffer(0)]], device const half* bias [[buffer(1)]], + constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < n) h[i] = half(float(h[i]) + float(bias[i % 2048])); +} + +struct GatherArgs { + uint nwin, Lw, L; + float cfg; +}; + +// A batch of windows' guided velocity -(o + post) summed into vsum / vcnt, windows in order (no atomics). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_dit_gather(device const half* o [[buffer(0)]], device const half* post [[buffer(1)]], + device const int* wins [[buffer(2)]], device float* vsum [[buffer(3)]], device float* vcnt [[buffer(4)]], + constant GatherArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + if (i >= a.L * 128) return; + const int t = int(i / 128), c = int(i % 128); + float sum = vsum[i], cnt = vcnt[i]; + for (uint w = 0; w < a.nwin; ++w) { + const int start = wins[2 * w], len = wins[2 * w + 1]; + if (t < start || t >= start + len) continue; + const ulong rc = ((ulong)w * a.Lw + (t - start)) * 128 + c, ru = ((ulong)(a.nwin + w) * a.Lw + (t - start)) * 128 + c; + const float vc = -rh(float(o[rc]) + float(post[rc])); + const float vu = -rh(float(o[ru]) + float(post[ru])); + sum += vu + (vc - vu) * a.cfg; + cnt += 1.0f; + } + vsum[i] = sum; + vcnt[i] = cnt; +} + +// Euler: x += (vsum / vcnt) (sigma_next - sigma); the sums cleared for the next step. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_euler(device float* x [[buffer(0)]], device float* vsum [[buffer(1)]], + device float* vcnt [[buffer(2)]], constant float2& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= uint(a.y)) return; + x[i] = fma(vsum[i] / vcnt[i], a.x, x[i]); + vsum[i] = 0.0f; + vcnt[i] = 0.0f; +} + +// Gaussian noise [n] from (seed, i): Philox normals, two a counter. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_noise(device float* x [[buffer(0)]], constant ulong2& a [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + if (2 * ulong(i) >= a.y) return; + const float2 g = philox_normal2(a.x, i, 0x6e6f697365ul); + x[2 * i] = g.x; + if (2 * ulong(i) + 1 < a.y) x[2 * i + 1] = g.y; +} diff --git a/zig/kernels/metal/music3/dit_attn.metal b/zig/kernels/metal/music3/dit_attn.metal new file mode 100644 index 00000000000..6a01fc573ce --- /dev/null +++ b/zig/kernels/metal/music3/dit_attn.metal @@ -0,0 +1,115 @@ +// music3 DiT attention on the tensor units: heads of 64 from roped qkv rows, keys to each window's length. +#include +using namespace metal; +#include "../nax.h" + +namespace m3 { +using namespace tfp; + +constant constexpr float kMasked = -3.402823466e+38f; +constant constexpr int kAnyCols = 1 << 30; + +// Fold one fragment's rows into r[2] (rows home.y, home.y + 8): pairs, then lanes 1 and 8 apart, then into r. +template +inline void row_fold(thread const frag& f, thread float (&r)[2]) { + for (short h = 0; h < 2; h++) { + const short b = 4 * h; + float t = MAX ? max(max(f[b], f[b + 1]), max(f[b + 2], f[b + 3])) : (f[b] + f[b + 1]) + (f[b + 2] + f[b + 3]); + const float u = simd_shuffle_xor(t, ushort(1)); + t = MAX ? max(t, u) : t + u; + const float w = simd_shuffle_xor(t, ushort(8)); + t = MAX ? max(t, w) : t + w; + r[h] = MAX ? max(r[h], t) : r[h] + t; + } +} + +} // namespace m3 + +struct DitAttnArgs { + uint Lseq; + float scale; +}; + +// qkv [S, Lseq, 6144] (roped), lens [S] keys a row, out [S, Lseq, 2048]: 64 queries a group, 32 keys a block, exp2. +[[max_total_threads_per_threadgroup(128)]] kernel void m3_dit_attn(const device half* qkv [[buffer(0)]], const device int* lens [[buffer(1)]], + device half* out [[buffer(2)]], constant DitAttnArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + using namespace tfp; + constexpr int BQ = 64, BK = 32, RS = 6144; + const int L = lens[tg.z], Lseq = int(a.Lseq); + const int q0 = int(tg.x) * BQ + 16 * int(sg); + const device half* rows = qkv + (ulong)tg.z * Lseq * RS + tg.y * 64; + const device half* Q = rows + (long)q0 * RS; + const device half* K = rows + 2048; + const device half* V = rows + 4096; + const float scale2 = a.scale * 1.44269504089f; + const short2 home = frag_home(ushort(lane)); + const int q_rows = Lseq - q0; + frag q[4]; + for (short d = 0; d < 4; d++) frag_get_in(q[d], Q, RS, 0, 16 * d, home, q_rows, m3::kAnyCols); + frag acc[4]; + for (short i = 0; i < 4; i++) acc[i] = frag(0); + float top[2] = {m3::kMasked, m3::kMasked}, total[2] = {0.0f, 0.0f}; + const int blocks = (L + BK - 1) / BK; + for (int kb = 0; kb < blocks; kb++) { + const int k_rows = L - kb * BK; + const bool part = k_rows < BK; + frag s[2] = {frag(0), frag(0)}; + for (short d = 0; d < 4; d++) { + frag k0, k1; + if (part) { + frag_get_t_in(k0, K, RS, 0, 16 * d, home, k_rows, m3::kAnyCols); + frag_get_t_in(k1, K, RS, 16, 16 * d, home, k_rows, m3::kAnyCols); + } else { + frag_get_t(k0, K, RS, 0, 16 * d, home); + frag_get_t(k1, K, RS, 16, 16 * d, home); + } + mma_16x32(s[0], s[1], q[d], k0, k1); + } + for (short f = 0; f < 2; f++) + for (short e = 0; e < 8; e++) { + const bool live = !part || (16 * f + home.x + TF_COL(e)) < k_rows; + s[f][e] = live ? s[f][e] * scale2 : m3::kMasked; + } + float top_new[2] = {top[0], top[1]}; + m3::row_fold(s[0], top_new); + m3::row_fold(s[1], top_new); + for (short f = 0; f < 2; f++) + for (short e = 0; e < 8; e++) s[f][e] = precise::exp2(s[f][e] - top_new[e >> 2]); + float scale_old[2]; + for (short h = 0; h < 2; h++) { + scale_old[h] = precise::exp2(top[h] - top_new[h]); + top[h] = top_new[h]; + total[h] = total[h] * scale_old[h]; + } + m3::row_fold(s[0], total); + m3::row_fold(s[1], total); + for (short i = 0; i < 4; i++) + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * scale_old[e >> 2]; + frag p[2]; + for (short f = 0; f < 2; f++) + for (short e = 0; e < 8; e++) p[f][e] = half(s[f][e]); // probabilities in fp16 for P V, as on CUDA + for (short d = 0; d < 4; d += 2) { + for (short k = 0; k < 2; k++) { + frag v0, v1; + if (part) { + frag_get_in(v0, V, RS, 16 * k, 16 * d, home, k_rows, m3::kAnyCols); + frag_get_in(v1, V, RS, 16 * k, 16 * d + 16, home, k_rows, m3::kAnyCols); + } else { + frag_get(v0, V, RS, 16 * k, 16 * d, home); + frag_get(v1, V, RS, 16 * k, 16 * d + 16, home); + } + mma_16x32(acc[d], acc[d + 1], p[k], v0, v1); + } + } + K += BK * RS; + V += BK * RS; + } + if (q_rows <= 0) return; + const float inv[2] = {1.0f / total[0], 1.0f / total[1]}; + for (short i = 0; i < 4; i++) + for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * inv[e >> 2]; + device half* O = out + ((ulong)tg.z * Lseq + q0) * 2048 + tg.y * 64; + for (short i = 0; i < 4; i++) frag_put_in(acc[i], O, 2048, 0, 16 * i, home, q_rows, m3::kAnyCols); +} diff --git a/zig/kernels/metal/music3/gemm.metal b/zig/kernels/metal/music3/gemm.metal new file mode 100644 index 00000000000..941c95413d3 --- /dev/null +++ b/zig/kernels/metal/music3/gemm.metal @@ -0,0 +1,146 @@ +// music3 GEMMs Y[b] = X[b] W^T (+ bias) (+ Y[b]), fp32 sums, one rounding: bf16 / fp16 on the tensor units. +#include "../prefill/gemm_nax.metal" + +inline float rh(float x) { return float(half(x)); } + +struct LinearArgs { + int M, N, K, ldx, ldy, has_bias, accumulate, pad; + long sx, sy; // batch strides (elements) of X and Y +}; + +// Epilogues: plain (+ bias, + Y); kGlu (W rows in 32s: 16 values, their 16 gates) the GLU at col / 2; kRope q, k. +enum Mode { kPlain = 0, kGlu = 1, kRope = 2 }; + +// A 64x128 block a threadgroup, a 32x32 block a simdgroup (2 x 4), as MLX's steel_gemm_fused_nax. +template +inline void linear(const device T* X, const device T* W, const device T* bias, const device float* cs, device T* Y, + constant LinearArgs& a, uint3 tg, uint sg, uint lane) { + const int row = int(tg.y) * 64 + 32 * int(sg / 4), col = int(tg.x) * 128 + 32 * int(sg % 4); + X += long(tg.z) * a.sx + long(row) * a.ldx; + W += long(col) * a.K; + Y += long(tg.z) * a.sy + long(row) * a.ldy + (MODE == kGlu ? col / 2 : col); + const int rows = min(32, a.M - row), cols = min(32, a.N - col); + const short2 home = tfp::frag_home(ushort(lane)); + tfp::frag acc[2][2]; + if (rows == 32 && cols == 32) { + tfp::gemm_block(acc, X, W, a.ldx, a.K, a.K, a.K / 256, rows, cols, home); + } else { + tfp::gemm_block(acc, X, W, a.ldx, a.K, a.K, a.K / 256, rows, cols, home); + } + if (rows <= 0 || cols <= 0) return; + if (MODE != kPlain) { + const bool rot = MODE == kRope && col < 4096 && col % 64 == 0; // dims (i, i + 16) of a q or k head, at row % Lseq + for (short i = 0; i < 2; i++) { + for (short e = 0; e < 8; e++) { + const int r = 16 * i + home.y + (e >> 2) * 8, c = home.x + TF_COL(e); + if (r >= rows) continue; + const float x0 = float(T(acc[i][0][e])), x1 = float(T(acc[i][1][e])); // the GEMM's rounded outputs + device T* y = Y + long(r) * a.ldy + c; + if (MODE == kGlu) { + const int p = col / 2 + c; + const float v = rh(x0 + float(bias[p])), g = rh(x1 + float(bias[a.N / 2 + p])); + *y = T(v * rh(g / (1.0f + fast::exp(-g)))); // fast: precise exp here spills the GEMM (2.5x slower) + } else if (rot) { + const int j = (row + r) % a.pad; + const float cn = cs[(j * 16 + c) * 2], sn = cs[(j * 16 + c) * 2 + 1]; + y[0] = T(x0 * cn - x1 * sn); + y[16] = T(x1 * cn + x0 * sn); + } else { + y[0] = T(x0); + y[16] = T(x1); + } + } + } + return; + } + for (short i = 0; i < 2; i++) { + for (short j = 0; j < 2; j++) { + for (short e = 0; e < 8; e++) { + const int r = 16 * i + home.y + (e >> 2) * 8, c = 16 * j + home.x + TF_COL(e); + if (r >= rows || c >= cols) continue; + float v = acc[i][j][e]; + if (a.has_bias) v += float(bias[col + c]); + device T* y = Y + long(r) * a.ldy + c; + if (a.accumulate) v += float(*y); + *y = T(v); + } + } + } +} + +#define LINEAR(NAME, T, MODE) \ + [[max_total_threads_per_threadgroup(256)]] kernel void NAME( \ + const device T* X [[buffer(0)]], const device T* W [[buffer(1)]], const device T* bias [[buffer(2)]], \ + device T* Y [[buffer(3)]], const device float* cs [[buffer(4)]], constant LinearArgs& a [[buffer(5)]], \ + uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]]) { \ + linear(X, W, bias, cs, Y, a, tg, sg, lane); \ + } +LINEAR(m3_linear_b, bfloat, kPlain) +LINEAR(m3_linear_h, half, kPlain) +LINEAR(m3_linear_glu_h, half, kGlu) +LINEAR(m3_linear_rope_h, half, kRope) + +// fp32 Y (+)= X W^T from bf16 halves x = xh + xl, w = wh + wl: xh wh + (xh wl + xl wh), about 16 bits an operand. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_linear_s( + const device bfloat* Xh [[buffer(0)]], const device bfloat* Xl [[buffer(1)]], const device bfloat* Wh [[buffer(2)]], + const device bfloat* Wl [[buffer(3)]], device float* Y [[buffer(4)]], constant LinearArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const int row = int(tg.y) * 64 + 32 * int(sg / 4), col = int(tg.x) * 128 + 32 * int(sg % 4); + const long xo = long(tg.z) * a.sx + long(row) * a.ldx, wo = long(col) * a.K; + Y += long(tg.z) * a.sy + long(row) * a.ldy + col; + const int rows = min(32, a.M - row), cols = min(32, a.N - col); + const short2 home = tfp::frag_home(ushort(lane)); + tfp::frag hh[2][2], cross[2][2]; + for (short i = 0; i < 2; i++) + for (short j = 0; j < 2; j++) hh[i][j] = cross[i][j] = tfp::frag(0); + if (rows <= 0 || cols <= 0) return; + const bool full = rows == 32 && cols == 32 && a.K % 16 == 0; + Xh += xo; + Xl += xo; + Wh += wo; + Wl += wo; + for (int k0 = 0; k0 < a.K; k0 += 16) { // each operand's halves read once a step for all three products + tfp::frag ah[2], al[2], bh[2], bl[2]; + for (short i = 0; i < 2; i++) { + if (full) { + tfp::frag_get(ah[i], Xh, a.ldx, 16 * i, k0, home); + tfp::frag_get(al[i], Xl, a.ldx, 16 * i, k0, home); + tfp::frag_get_t(bh[i], Wh, a.K, 16 * i, k0, home); + tfp::frag_get_t(bl[i], Wl, a.K, 16 * i, k0, home); + } else { + tfp::frag_get_in(ah[i], Xh, a.ldx, 16 * i, k0, home, rows, a.K); + tfp::frag_get_in(al[i], Xl, a.ldx, 16 * i, k0, home, rows, a.K); + tfp::frag_get_t_in(bh[i], Wh, a.K, 16 * i, k0, home, cols, a.K); + tfp::frag_get_t_in(bl[i], Wl, a.K, 16 * i, k0, home, cols, a.K); + } + } + for (short i = 0; i < 2; i++) { + tfp::mma_16x32(hh[i][0], hh[i][1], ah[i], bh[0], bh[1]); + tfp::mma_16x32(cross[i][0], cross[i][1], ah[i], bl[0], bl[1]); + tfp::mma_16x32(cross[i][0], cross[i][1], al[i], bh[0], bh[1]); + } + } + for (short i = 0; i < 2; i++) { + for (short j = 0; j < 2; j++) { + for (short e = 0; e < 8; e++) { + const int r = 16 * i + home.y + (e >> 2) * 8, c = 16 * j + home.x + TF_COL(e); + if (r >= rows || c >= cols) continue; + float v = hh[i][j][e] + cross[i][j][e]; + device float* y = Y + long(r) * a.ldy + c; + if (a.accumulate) v += *y; + *y = v; + } + } + } +} + +// x = hi + lo in bf16 halves (hi = bf16(x), lo = bf16(x - hi)), n values. +[[max_total_threads_per_threadgroup(256)]] kernel void m3_split(const device float* x [[buffer(0)]], device bfloat* hi [[buffer(1)]], + device bfloat* lo [[buffer(2)]], constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const bfloat h = bfloat(x[i]); + hi[i] = h; + lo[i] = bfloat(x[i] - float(h)); +} diff --git a/zig/kernels/metal/music3/m3_common.h b/zig/kernels/metal/music3/m3_common.h new file mode 100644 index 00000000000..46310126f2c --- /dev/null +++ b/zig/kernels/metal/music3/m3_common.h @@ -0,0 +1,77 @@ +// music3 kernel helpers: bf16 as ushort bits (round to nearest even), group reductions, the Philox counter draws. +#pragma once +#include +using namespace metal; + +typedef ushort bf16; + +inline float b2f(bf16 x) { return as_type(uint(x) << 16); } + +inline bf16 f2b(float x) { + const uint u = as_type(x); + if ((u & 0x7FFFFFFFu) > 0x7F800000u) return bf16((u >> 16) | 0x40u); + return bf16((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16); +} + +// Round to bf16 / fp16 and back (the reference's rounded intermediates). +inline float rb(float x) { return b2f(f2b(x)); } +inline float rh(float x) { return float(half(x)); } + +inline float m3_silu(float x) { return x / (1.0f + precise::exp(-x)); } + +// Four bf16 values of 8 bytes as floats. +inline float4 bf4(uint2 w) { + return float4(as_type(w.x << 16), as_type(w.x & 0xFFFF0000u), as_type(w.y << 16), + as_type(w.y & 0xFFFF0000u)); +} + +// Sum over a threadgroup of `n` simdgroups (scratch holds 32 floats); every thread gets the total. +inline float group_sum(float v, threadgroup float* scratch, uint sg, uint lane, uint n) { + v = simd_sum(v); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0) scratch[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float s = 0.0f; + for (uint i = 0; i < n; ++i) s += scratch[i]; + return s; +} + +inline float group_max(float v, threadgroup float* scratch, uint sg, uint lane, uint n) { + v = simd_max(v); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0) scratch[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float s = -INFINITY; + for (uint i = 0; i < n; ++i) s = max(s, scratch[i]); + return s; +} + +// Philox4x32-10 of counter (a, b) under key `seed`, as the CUDA kernels draw it. +inline uint4 philox(ulong seed, ulong a, ulong b) { + uint c0 = uint(a), c1 = uint(a >> 32), c2 = uint(b), c3 = uint(b >> 32); + uint k0 = uint(seed), k1 = uint(seed >> 32); + for (int i = 0; i < 10; ++i) { + const uint h0 = mulhi(0xD2511F53u, c0), l0 = 0xD2511F53u * c0; + const uint h1 = mulhi(0xCD9E8D57u, c2), l1 = 0xCD9E8D57u * c2; + const uint n0 = h1 ^ c1 ^ k0, n2 = h0 ^ c3 ^ k1; + c0 = n0; + c1 = l1; + c2 = n2; + c3 = l0; + k0 += 0x9E3779B9u; + k1 += 0xBB67AE85u; + } + return uint4(c0, c1, c2, c3); +} + +// The first word as a uniform in [0, 1) (24 bits). +inline float philox_uniform(ulong seed, ulong a, ulong b) { return float(philox(seed, a, b).x >> 8) * (1.0f / 16777216.0f); } + +// Two normals (Box-Muller) of counter (a, b). +inline float2 philox_normal2(ulong seed, ulong a, ulong b) { + const uint4 c = philox(seed, a, b); + const float u1 = (float(c.x >> 8) + 1.0f) * (1.0f / 16777216.0f); + const float u2 = float(c.y >> 8) * (1.0f / 16777216.0f); + const float r = precise::sqrt(-2.0f * precise::log(u1)); + return float2(r * precise::cos(6.2831853071795864f * u2), r * precise::sin(6.2831853071795864f * u2)); +} diff --git a/zig/kernels/metal/music3/sample.metal b/zig/kernels/metal/music3/sample.metal new file mode 100644 index 00000000000..4388337d412 --- /dev/null +++ b/zig/kernels/metal/music3/sample.metal @@ -0,0 +1,174 @@ +// music3 AR sampling: the CFG top-k draw and the frame's bookkeeping, all on the device between frames. +#include "m3_common.h" + +inline uint ord(float v) { // float -> uint with the same order + const uint u = as_type(v); + return (u & 0x80000000u) ? ~u : (u | 0x80000000u); +} + +#define SAMPLE_THREADS 1024 +#define SAMPLE_CAP 1024 + +struct SampleArgs { + ulong seed; + uint V; + float cfg; + int top_k, rank_cond, slot, has_code, has_tokens, pad; +}; + +inline float guided(device const float* lg, uint V, uint i, float cfg) { return lg[V + i] + (lg[i] - lg[V + i]) * cfg; } + +inline uint key_of(device const float* lg, uint V, uint i, float cfg, int rank_cond) { + return ord(rank_cond ? lg[i] : guided(lg, V, i, cfg)); +} + +// A CFG top-k draw of logits [2, V] (cond, uncond) by inverse CDF in index order on a Philox uniform, as on CUDA. +[[max_total_threads_per_threadgroup(1024)]] kernel void m3_sample(device const float* lg [[buffer(0)]], device const ulong* step [[buffer(1)]], + device int* pick [[buffer(2)]], device int* code [[buffer(3)]], device int* tokens [[buffer(4)]], + device const int* count [[buffer(5)]], constant SampleArgs& a [[buffer(6)]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup atomic_uint hist[256]; + threadgroup uint sel[2]; + threadgroup uint cnt_sh[SAMPLE_THREADS / 32]; + threadgroup int cidx[SAMPLE_CAP]; + threadgroup float cval[SAMPLE_CAP]; + threadgroup int ncand; + const uint V = a.V; + const uint per = (V + SAMPLE_THREADS - 1) / SAMPLE_THREADS; + const uint lo = t * per, hi = min(V, lo + per); + // radix select of the top_k-th largest key, 8 bits at a time from the top + uint prefix = 0, mask = 0; + int want = max(1, min(a.top_k, int(V))); + for (int shift = 24; shift >= 0; shift -= 8) { + if (t < 256) atomic_store_explicit(&hist[t], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = lo; i < hi; ++i) { + const uint k = key_of(lg, V, i, a.cfg, a.rank_cond); + if ((k & mask) == prefix) atomic_fetch_add_explicit(&hist[(k >> shift) & 255], 1u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + int acc = 0, dgt = 0; + for (int dd = 255; dd >= 0; --dd) { + const int hv = int(atomic_load_explicit(&hist[dd], memory_order_relaxed)); + if (acc + hv >= want) { + dgt = dd; + break; + } + acc += hv; + } + sel[0] = uint(dgt); + sel[1] = uint(want - acc); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix |= sel[0] << shift; + mask |= 255u << shift; + want = int(sel[1]); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const uint thr = prefix; // keys >= thr are the candidates + uint mine = 0; + for (uint i = lo; i < hi; ++i) mine += key_of(lg, V, i, a.cfg, a.rank_cond) >= thr; + const uint excl = simd_prefix_exclusive_sum(mine); + if (lane == 31) cnt_sh[sg] = excl + mine; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + uint s = 0; + for (uint w = 0; w < SAMPLE_THREADS / 32; ++w) { + const uint v = cnt_sh[w]; + cnt_sh[w] = s; + s += v; + } + ncand = int(min(s, uint(SAMPLE_CAP))); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint at = cnt_sh[sg] + excl; + for (uint i = lo; i < hi; ++i) + if (key_of(lg, V, i, a.cfg, a.rank_cond) >= thr) { + if (at < SAMPLE_CAP) { + cidx[at] = int(i); + cval[at] = guided(lg, V, i, a.cfg); + } + ++at; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t != 0) return; + int n = ncand; + if (a.rank_cond && n > a.top_k) { + // ComfyUI's second sample_topk: keep values with fewer than top_k strictly greater ones (the top_k with ties) + float kth = INFINITY; + for (int i = 0; i < n; ++i) { + int greater = 0; + for (int j = 0; j < n; ++j) greater += cval[j] > cval[i]; + if (greater < a.top_k) kth = min(kth, cval[i]); + } + int w = 0; + for (int i = 0; i < n; ++i) + if (cval[i] >= kth) { + cidx[w] = cidx[i]; + cval[w] = cval[i]; + ++w; + } + n = w; + } + float m = -INFINITY; + for (int i = 0; i < n; ++i) m = max(m, cval[i]); + int chosen = cidx[0]; + if (a.top_k <= 1) { + for (int i = 0; i < n; ++i) + if (cval[i] == m) { + chosen = cidx[i]; + break; + } + } else { + float sum = 0.0f; + for (int i = 0; i < n; ++i) sum += precise::exp(cval[i] - m); + const float u = philox_uniform(a.seed, *step, ulong(a.slot)) * sum; + float run = 0.0f; + chosen = cidx[n - 1]; + for (int i = 0; i < n; ++i) { + run += precise::exp(cval[i] - m); + if (u < run) { + chosen = cidx[i]; + break; + } + } + } + *pick = chosen; + if (a.has_code) *code = max(chosen - 1, 0); + if (a.has_tokens) tokens[*count] = chosen; +} + +// After a frame: the next position and step, one frame more. +[[max_total_threads_per_threadgroup(32)]] kernel void m3_frame_done(device int* pos [[buffer(0)]], device ulong* step [[buffer(1)]], + device int* count [[buffer(2)]], uint t [[thread_index_in_threadgroup]]) { + if (t == 0) { + *pos += 1; + *step += 1; + *count += 1; + } +} + +// A frame state's part: states[*count, part] = src (bf16 4096). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_state_part(device const uint4* src [[buffer(0)]], device uint4* states [[buffer(1)]], + device const int* count [[buffer(2)]], constant uint& part [[buffer(3)]], + uint t [[thread_index_in_threadgroup]]) { + const ulong base = ((ulong)*count * 8 + part) * 512; + for (uint i = t; i < 512; i += 256) states[base + i] = src[i]; +} + +// A forced frame's codes (teacher forcing): codes[0..8) = forced[*count, 0..8), its token into tokens[*count]. +[[max_total_threads_per_threadgroup(32)]] kernel void m3_force_codes(device const int* forced [[buffer(0)]], device const int* count [[buffer(1)]], + device int* codes [[buffer(2)]], device int* tokens [[buffer(3)]], + uint t [[thread_index_in_threadgroup]]) { + const int c = *count; + if (t < 8) codes[t] = forced[c * 8 + t]; + if (t == 0) tokens[c] = forced[c * 8] + 1; +} + +// dst = src, n 32-bit words (in order with the dispatches around it). +[[max_total_threads_per_threadgroup(256)]] kernel void m3_copy(device const uint* src [[buffer(0)]], device uint* dst [[buffer(1)]], + constant uint& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < n) dst[i] = src[i]; +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 0573c8832b1..1249429a2d8 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -137,3 +137,16 @@ pub const core_simd_qmm = @embedFile("core/simd_qmm.metal"); pub const core_simd_qmm_bits = @embedFile("core/simd_qmm_bits.metal"); /// The kernel contract's planted controls: one kernel breaking each gate (zig/tests/contract/). pub const core_contract_controls = @embedFile("core/contract_controls.metal"); + +/// MiniMax Music 3's kernels (music3.metallib is built ahead of time); the kernel contract compiles this text. +pub const music3 = struct { + pub const common = @embedFile("music3/m3_common.h"); + pub const gemm_nax = @embedFile("prefill/gemm_nax.metal"); + pub const ar = @embedFile("music3/ar.metal"); + pub const attn = @embedFile("music3/attn.metal"); + pub const sample = @embedFile("music3/sample.metal"); + pub const gemm = @embedFile("music3/gemm.metal"); + pub const dit = @embedFile("music3/dit.metal"); + pub const dit_attn = @embedFile("music3/dit_attn.metal"); + pub const dav = @embedFile("music3/dav.metal"); +}; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index b79337b5c51..eb04f16c62a 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -45,6 +45,61 @@ pub const cuda = [_]CudaRecord{ .{ .launch = .{ .name = "vit tf_vit_pointwise", .symbol = "tf_vit_pointwise", .image = "vit", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "vit tf_vit_bias", .symbol = "tf_vit_bias", .image = "vit", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "vit tf_vit_unshuffle", .symbol = "tf_vit_unshuffle", .image = "vit", .threads = 256 }, .usage = .{ .{ .regs = 29, .static = 0, .bound = 256 }, .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_embed", .symbol = "m3_embed", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_embed_code", .symbol = "m3_embed_code", .image = "music3", .threads = 512 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_frame_embed", .symbol = "m3_frame_embed", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_rmsnorm", .symbol = "m3_rmsnorm", .image = "music3", .threads = 512 }, .usage = .{ .{ .regs = 14, .static = 128, .bound = 0 }, .{ .regs = 15, .static = 128, .bound = 0 }, .{ .regs = 15, .static = 128, .bound = 0 }, .{ .regs = 18, .static = 128, .bound = 0 }, .{ .regs = 18, .static = 128, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_add", .symbol = "m3_add", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_swiglu", .symbol = "m3_swiglu", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_quant_groups", .symbol = "m3_quant_groups", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_dequant", .symbol = "m3_dequant", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_quant_rows", .symbol = "m3_quant_rows", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 128, .bound = 0 }, .{ .regs = 18, .static = 128, .bound = 0 }, .{ .regs = 18, .static = 128, .bound = 0 }, .{ .regs = 16, .static = 128, .bound = 0 }, .{ .regs = 16, .static = 128, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_qk_rope", .symbol = "m3_qk_rope", .image = "music3", .threads = 128 }, .usage = .{ .{ .regs = 26, .static = 640, .bound = 0 }, .{ .regs = 26, .static = 640, .bound = 0 }, .{ .regs = 26, .static = 640, .bound = 0 }, .{ .regs = 29, .static = 640, .bound = 0 }, .{ .regs = 29, .static = 640, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_attn_part", .symbol = "m3_attn_part", .image = "music3", .threads = 128 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "music3 m3_attn_merge", .symbol = "m3_attn_merge", .image = "music3", .threads = 128 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_depth_kv", .symbol = "m3_depth_kv", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_depth_attn", .symbol = "m3_depth_attn", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 30, .static = 160, .bound = 0 }, .{ .regs = 32, .static = 160, .bound = 0 }, .{ .regs = 32, .static = 160, .bound = 0 }, .{ .regs = 40, .static = 160, .bound = 0 }, .{ .regs = 40, .static = 160, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_frame_done", .symbol = "m3_frame_done", .image = "music3", .threads = 32 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_state_part", .symbol = "m3_state_part", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_force_codes", .symbol = "m3_force_codes", .image = "music3", .threads = 32 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_cond_mix", .symbol = "m3_cond_mix", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_im2col3", .symbol = "m3_im2col3", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_dit_input", .symbol = "m3_dit_input", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_add_h", .symbol = "m3_add_h", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_time_features", .symbol = "m3_time_features", .image = "music3", .threads = 128 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_silu_h", .symbol = "m3_silu_h", .image = "music3", .threads = 1024 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_linear_h1", .symbol = "m3_linear_h1", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_gather_rows_h", .symbol = "m3_gather_rows_h", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_put_time", .symbol = "m3_put_time", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_layernorm_h", .symbol = "m3_layernorm_h", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 128, .bound = 0 }, .{ .regs = 37, .static = 128, .bound = 0 }, .{ .regs = 37, .static = 128, .bound = 0 }, .{ .regs = 39, .static = 128, .bound = 0 }, .{ .regs = 39, .static = 128, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_bias_h", .symbol = "m3_bias_h", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_dit_rope", .symbol = "m3_dit_rope", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_softmax_rows", .symbol = "m3_softmax_rows", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 128, .bound = 0 }, .{ .regs = 19, .static = 128, .bound = 0 }, .{ .regs = 19, .static = 128, .bound = 0 }, .{ .regs = 20, .static = 128, .bound = 0 }, .{ .regs = 20, .static = 128, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_flash_attn", .symbol = "m3_flash_attn", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 128, .static = 18432, .bound = 256 }, .{ .regs = 128, .static = 18432, .bound = 256 }, .{ .regs = 128, .static = 18432, .bound = 256 }, .{ .regs = 128, .static = 18432, .bound = 256 }, .{ .regs = 128, .static = 18432, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_heads_to_rows", .symbol = "m3_heads_to_rows", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_glu_h", .symbol = "m3_glu_h", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_dit_gather", .symbol = "m3_dit_gather", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 33, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_euler", .symbol = "m3_euler", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_noise", .symbol = "m3_noise", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_snake", .symbol = "m3_snake", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 21, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_bias_rows", .symbol = "m3_bias_rows", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_overlap_add", .symbol = "m3_overlap_add", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_zero_rows", .symbol = "m3_zero_rows", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 8, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_add_bias", .symbol = "m3_add_bias", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_latent_half", .symbol = "m3_latent_half", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 0 }, .{ .regs = 11, .static = 0, .bound = 0 }, .{ .regs = 11, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_tanh", .symbol = "m3_tanh", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_bf16_2", .symbol = "m3_gemv_bf16_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 56, .static = 0, .bound = 256 }, .{ .regs = 56, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_bf16_4", .symbol = "m3_gemv_bf16_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 72, .static = 0, .bound = 256 }, .{ .regs = 72, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_i8_2", .symbol = "m3_gemv_i8_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 66, .static = 0, .bound = 256 }, .{ .regs = 68, .static = 0, .bound = 256 }, .{ .regs = 68, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_i8_4", .symbol = "m3_gemv_i8_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 78, .static = 0, .bound = 256 }, .{ .regs = 78, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_bf16_2", .symbol = "m3_glu_bf16_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 70, .static = 0, .bound = 256 }, .{ .regs = 70, .static = 0, .bound = 256 }, .{ .regs = 70, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_bf16_4", .symbol = "m3_glu_bf16_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 76, .static = 0, .bound = 256 }, .{ .regs = 76, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_i8_2", .symbol = "m3_glu_i8_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 71, .static = 0, .bound = 256 }, .{ .regs = 71, .static = 0, .bound = 256 }, .{ .regs = 71, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 }, .{ .regs = 64, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_i8_4", .symbol = "m3_glu_i8_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 97, .static = 0, .bound = 256 }, .{ .regs = 104, .static = 0, .bound = 256 }, .{ .regs = 104, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 }, .{ .regs = 80, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_g8_2", .symbol = "m3_gemv_g8_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 102, .static = 0, .bound = 256 }, .{ .regs = 104, .static = 0, .bound = 256 }, .{ .regs = 104, .static = 0, .bound = 256 }, .{ .regs = 68, .static = 0, .bound = 256 }, .{ .regs = 68, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_gemv_g8_4", .symbol = "m3_gemv_g8_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 76, .static = 0, .bound = 256 }, .{ .regs = 76, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_g8_2", .symbol = "m3_glu_g8_2", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 90, .static = 0, .bound = 256 }, .{ .regs = 90, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "music3 m3_glu_g8_4", .symbol = "m3_glu_g8_4", .image = "music3", .threads = 256 }, .usage = .{ .{ .regs = 118, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 98, .static = 0, .bound = 256 }, .{ .regs = 98, .static = 0, .bound = 256 } } }, }; /// Gate 5's planted CUDA controls: a launch past its __launch_bounds__, one needing more registers than a block has. @@ -147,6 +202,64 @@ pub const metal = [_]M{ .{ .name = "qwen vision qwv_residual", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen vision qwv_bias", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen27 copy q27_take", .threads = 256, .tg_memory = 0, .reserved = 256 }, + // MiniMax Music 3 (music3.metallib): every kernel reserves its threads in the source + .{ .name = "music3 ar m3_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_embed_code", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_frame_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_rmsnorm", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "music3 ar m3_add", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_quant", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "music3 ar m3_dequant", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 ar m3_gemv_bf16_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_gemv_bf16_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_gemv_i8_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_gemv_i8_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_gemv_g8_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_gemv_g8_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_bf16_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_bf16_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_i8_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_i8_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_g8_2", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 ar m3_glu_g8_4", .threads = 64, .tg_memory = 0, .reserved = 64 }, + .{ .name = "music3 attn m3_qk_rope", .threads = 128, .tg_memory = 640, .reserved = 128 }, + .{ .name = "music3 attn m3_attn_part", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "music3 attn m3_attn_merge", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "music3 attn m3_depth_kv", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 attn m3_depth_attn", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "music3 sample m3_sample", .threads = 1024, .tg_memory = 9360, .reserved = 1024 }, + .{ .name = "music3 sample m3_frame_done", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "music3 sample m3_state_part", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 sample m3_force_codes", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "music3 sample m3_copy", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_linear_b", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_linear_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_linear_glu_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_linear_rope_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_linear_s", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 gemm m3_split", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_cond_mix", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_im2col3", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_dit_input", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_add_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_time_features", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "music3 dit m3_silu_h", .threads = 1024, .tg_memory = 0, .reserved = 1024 }, + .{ .name = "music3 dit m3_linear_h1", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_gather_rows_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_put_time", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_layernorm_h", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "music3 dit m3_bias_h", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_dit_gather", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_euler", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit m3_noise", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dit_attn m3_dit_attn", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "music3 dav m3_snake", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dav m3_bias_rows", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dav m3_overlap_add", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dav m3_zero", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dav m3_latent_half", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "music3 dav m3_tanh", .threads = 256, .tg_memory = 0, .reserved = 256 }, }; /// Gate 5's planted Metal controls: a launch past M1/M2's compiled limit (#708's class), 36 KiB of threadgroup memory. diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 18542b8cb47..c9ea303b971 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -56,6 +56,7 @@ 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 music3: []const u8 = if (available) &Blob("fatbin_music3").bytes else &.{}; /// Symbols in the gdn image as cuobjdump lists them for the built fatbin (named namespace tf_gdn). pub const gdn_symbols = struct { diff --git a/zig/src/families/music3/ar.zig b/zig/src/families/music3/ar.zig new file mode 100644 index 00000000000..2234faa269b --- /dev/null +++ b/zig/src/families/music3/ar.zig @@ -0,0 +1,360 @@ +//! The AR stage: the prompt's CFG rows in cuBLAS GEMMs, then a CUDA-graph frame step (code 0, 7 depth codes, states). +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const kern = @import("kernels.zig"); +const common = @import("common.zig"); + +const H = cfg.hidden; +const Buf = cuda.DeviceBuffer; +const decode_splits = 16; + +pub const Sampling = common.Sampling; +pub const Trace = common.Trace; +pub const Result = common.Result; + +pub const Ar = struct { + gpa: std.mem.Allocator, + k: *kern.Kernels, + w: *const wts.Ar, + d: *const cuda.Driver, + s: cuda.Stream, + bufs: std.ArrayList(Buf) = .empty, + // the cache, sized per request + ctx: usize = 0, + kc: [cfg.layers]u64 = @splat(0), + vc: [cfg.layers]u64 = @splat(0), + cache_buf: ?Buf = null, + // device scalars + pos: u64 = 0, + step: u64 = 0, + count: u64 = 0, + codes: u64 = 0, // i32 [8] + pick: u64 = 0, + tokens: u64 = 0, // i32 [max_frames + 2] + forced: u64 = 0, // i32 [max_frames + 2, 8] + states: u64 = 0, // bf16 [max_frames + 2, 8, 4096] + // frame scratch + x: u64 = 0, + xn: u64 = 0, + qkv: u64 = 0, + q: u64 = 0, + att: u64 = 0, + gu: u64 = 0, + ml: u64 = 0, + acc: u64 = 0, + last: u64 = 0, // [2, 4096] the body's normed last state + d_in: u64 = 0, // [4, 4096] + dx: u64 = 0, + dxn: u64 = 0, + dqkv: u64 = 0, + datt: u64 = 0, + dgu: u64 = 0, + dout: u64 = 0, + dkc: [cfg.depth_layers]u64 = @splat(0), + dvc: [cfg.depth_layers]u64 = @splat(0), + c0_logits: u64 = 0, // f32 [2, 16385] + code_logits: u64 = 0, // f32 [2, 1024] + graph: ?cuda.graph.Exec = null, + graph_smp: Sampling = .{}, + graph_ctx: usize = 0, + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, k: *kern.Kernels, w: *const wts.Ar) !Ar { + var a: Ar = .{ .gpa = gpa, .k = k, .w = w, .d = d, .s = s }; + errdefer a.deinit(); + a.pos = try a.alloc(16); + a.step = try a.alloc(16); + a.count = try a.alloc(16); + a.codes = try a.alloc(64); + a.pick = try a.alloc(16); + a.tokens = try a.alloc((cfg.max_frames + 2) * 4); + a.forced = try a.alloc((cfg.max_frames + 2) * 8 * 4); + a.states = try a.alloc((cfg.max_frames + 2) * 8 * H * 2); + a.x = try a.alloc(2 * H * 2); + a.xn = try a.alloc(2 * H * 2); + a.qkv = try a.alloc(2 * cfg.qkv_width * 2); + a.q = try a.alloc(2 * H * 2); + a.att = try a.alloc(2 * H * 2); + a.gu = try a.alloc(2 * 2 * cfg.mlp * 2); + a.ml = try a.alloc(2 * 32 * decode_splits * 2 * 4); + a.acc = try a.alloc(2 * 32 * decode_splits * 128 * 4); + a.last = try a.alloc(2 * H * 2); + a.d_in = try a.alloc(4 * H * 2); + a.dx = try a.alloc(4 * H * 2); + a.dxn = try a.alloc(4 * H * 2); + a.dqkv = try a.alloc(4 * 3 * H * 2); + a.datt = try a.alloc(4 * H * 2); + a.dgu = try a.alloc(4 * 2 * cfg.depth_mlp * 2); + a.dout = try a.alloc(2 * H * 2); + for (0..cfg.depth_layers) |i| { + a.dkc[i] = try a.alloc(2 * 16 * 8 * 256 * 2); + a.dvc[i] = try a.alloc(2 * 16 * 8 * 256 * 2); + } + a.c0_logits = try a.alloc(2 * (cfg.c0_codes + 1) * 4); + a.code_logits = try a.alloc(2 * cfg.codebook_size * 4); + return a; + } + + pub fn deinit(a: *Ar) void { + if (a.graph) |*g| g.deinit(); + a.graph = null; + if (a.cache_buf) |*b| b.free(); + a.cache_buf = null; + for (a.bufs.items) |*b| b.free(); + a.bufs.deinit(a.gpa); + } + + fn alloc(a: *Ar, bytes: usize) !u64 { + const b = try Buf.alloc(a.d, @max(bytes, 256)); + try a.bufs.append(a.gpa, b); + return b.ptr; + } + + fn view(a: *Ar, ptr: u64) Buf { + return .{ .d = a.d, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + fn put(a: *Ar, dst: u64, bytes: []const u8) !void { + try a.view(dst).uploadAsync(0, bytes, a.s.handle); + } + + fn get(a: *Ar, src: u64, out: []u8) !void { + try a.view(src).downloadAsync(0, out, a.s.handle); + try a.s.synchronize(); + } + + fn setI32(a: *Ar, dst: u64, v: i32) !void { + try a.put(dst, std.mem.asBytes(&v)); + try a.s.synchronize(); + } + + /// KV caches for `need` positions (both rows, every layer); a new size drops the captured graph. + fn ensureCache(a: *Ar, need: usize) !void { + if (a.ctx >= need) return; + if (a.graph) |*g| g.deinit(); + a.graph = null; + if (a.cache_buf) |*b| b.free(); + a.cache_buf = null; + const ctxn = (need + 255) / 256 * 256; + const per = 2 * cfg.kv_heads * ctxn * cfg.head_dim * 2; + a.cache_buf = try Buf.alloc(a.d, per * 2 * cfg.layers); + for (0..cfg.layers) |i| { + a.kc[i] = a.cache_buf.?.ptr + (2 * i) * per; + a.vc[i] = a.cache_buf.?.ptr + (2 * i + 1) * per; + } + a.ctx = ctxn; + } + + /// The prompt rows (conditional ids, then the unconditional ones) through the body; leaves `last` and the caches. + pub fn prefill(a: *Ar, ids: []const u32, unc: []const u32) !void { + const n = ids.len; + const t = 2 * n; + const k = a.k; + const s = a.s; + const w = a.w; + // per-request prompt scratch + var scratch: std.ArrayList(Buf) = .empty; + defer { + for (scratch.items) |*b| b.free(); + scratch.deinit(a.gpa); + } + const P = struct { + fn mk(list: *std.ArrayList(Buf), gpa: std.mem.Allocator, d: *const cuda.Driver, bytes: usize) !u64 { + const b = try Buf.alloc(d, @max(bytes, 256)); + try list.append(gpa, b); + return b.ptr; + } + }; + const ids_d = try P.mk(&scratch, a.gpa, a.d, t * 4); + const x = try P.mk(&scratch, a.gpa, a.d, t * H * 2); + const xn = try P.mk(&scratch, a.gpa, a.d, t * H * 2); + const tmp = try P.mk(&scratch, a.gpa, a.d, t * H * 2); + const qkv = try P.mk(&scratch, a.gpa, a.d, t * cfg.qkv_width * 2); + const q = try P.mk(&scratch, a.gpa, a.d, t * H * 2); + const gu = try P.mk(&scratch, a.gpa, a.d, t * 2 * cfg.mlp * 2); + const act = try P.mk(&scratch, a.gpa, a.d, t * cfg.mlp * 2); + const ml = try P.mk(&scratch, a.gpa, a.d, t * 32 * 2 * 4); + const acc = try P.mk(&scratch, a.gpa, a.d, t * 32 * 128 * 4); + const wtmp: u64 = if (w.format == .int8) try P.mk(&scratch, a.gpa, a.d, 2 * cfg.mlp * H * 2) else 0; + const all = try a.gpa.alloc(i32, t); + defer a.gpa.free(all); + for (ids, 0..) |v, i| all[i] = @intCast(v); + for (unc, 0..) |v, i| all[n + i] = @intCast(v); + try a.put(ids_d, std.mem.sliceAsBytes(all)); + try a.setI32(a.pos, 0); + try k.embed(s, ids_d, w.embed_prefill, x, t); + for (0..cfg.layers) |li| { + const L = &w.body[li]; + try k.rmsnorm(s, x, H, L.in_norm, xn, H, t, cfg.eps); + try k.linearRows(s, L.qkv, xn, qkv, t, wtmp); + try k.qkRope(s, qkv, L.q_norm, L.k_norm, w.inv_freq, a.pos, n, t, q, a.kc[li], a.vc[li], a.ctx); + try k.attention(s, q, a.kc[li], a.vc[li], a.pos, n, t, a.ctx, 1, ml, acc, xn); + try k.linearRows(s, L.o, xn, tmp, t, wtmp); + try k.add(s, x, tmp, t * H); + try k.rmsnorm(s, x, H, L.post_norm, xn, H, t, cfg.eps); + try k.linearRows(s, L.gate_up, xn, gu, t, wtmp); + try k.swiglu(s, gu, act, cfg.mlp, t); + try k.linearRows(s, L.down, act, tmp, t, wtmp); + try k.add(s, x, tmp, t * H); + } + // the last row of each: the normed state code 0 is drawn from + try k.rmsnorm(s, x + (n - 1) * H * 2, n * H, w.norm, a.last, H, 2, cfg.eps); + try a.s.synchronize(); + } + + fn depthPass(a: *Ar, rows: usize, p0: usize) !void { + const k = a.k; + const s = a.s; + const w = a.w; + for (0..cfg.depth_layers) |li| { + const L = &w.depth[li]; + try k.rmsnorm(s, a.dx, H, L.in_norm, a.dxn, H, rows, cfg.eps); + try k.gemv(s, L.qkv, a.dxn, rows, .{ .y = a.dqkv }); + try k.depthAttention(s, a.dqkv, p0, rows, a.dkc[li], a.dvc[li], a.datt); + try k.gemv(s, L.o, a.datt, rows, .{ .y = a.dx, .res = a.dx }); + try k.rmsnorm(s, a.dx, H, L.post_norm, a.dxn, H, rows, cfg.eps); + try k.gemv(s, L.gate_up, a.dxn, rows, .{ .glu = true, .y = a.dgu }); + try k.gemv(s, L.down, a.dgu, rows, .{ .y = a.dx, .res = a.dx }); + } + // the last position's two rows, normed + try k.rmsnorm(s, a.dx + (rows - 2) * H * 2, H, w.depth_norm, a.dout, H, 2, cfg.eps); + } + + /// One frame: code 0, the 7 depth codes, the states, the frame fed back (`forced`: codes from the forced table). + fn enqueueFrame(a: *Ar, smp: Sampling, forced: bool, trace: ?*Trace) !void { + const k = a.k; + const s = a.s; + const w = a.w; + try k.gemv(s, w.lm_head, a.last, 2, .{ .yf = a.c0_logits }); + if (trace) |tr| try a.pull(&tr.c0, a.c0_logits, 2 * (cfg.c0_codes + 1)); + if (forced) { + try k.forceCodes(s, a.forced, a.count, a.codes, a.pick); + try a.copyI32(a.pick, a.tokens, a.count); + } else { + try k.sample(s, a.c0_logits, cfg.c0_codes + 1, true, .{ .cfg = smp.ar_cfg, .top_k = smp.top_k, .seed = smp.seed, .step = a.step, .slot = 0, .pick = a.pick, .code = a.codes, .tokens = a.tokens, .count = a.count }); + } + try k.statePart(s, a.last, a.states, a.count, 0); + // depth pass 0: [hidden, code-0 embedding] at positions 0 and 1, both rows + try a.copy(a.d_in, a.last, 2 * H * 2); + try k.embedCode(s, a.codes, 0, w.embed_audio, a.d_in + 2 * H * 2, 2); + try k.gemv(s, w.projection, a.d_in, 4, .{ .y = a.dx, .res = w.pos_emb, .res_div = 2 }); + try a.depthPass(4, 0); + for (1..cfg.codebooks) |ci| { + if (ci > 1) { + // the code drawn last, embedded, at position ci + try k.embedCode(s, a.codes + (ci - 1) * 4, (ci - 2) * cfg.codebook_size, w.extra, a.d_in, 2); + try k.gemv(s, w.projection, a.d_in, 2, .{ .y = a.dx, .res = w.pos_emb + ci * H * 2, .res_div = 2 }); + try a.depthPass(2, ci); + } + try k.statePart(s, a.dout, a.states, a.count, ci); + try k.gemv(s, w.heads[ci - 1], a.dout, 2, .{ .yf = a.code_logits }); + if (trace) |tr| try a.pull(&tr.depth, a.code_logits, 2 * cfg.codebook_size); + if (!forced) try k.sample(s, a.code_logits, cfg.codebook_size, false, .{ .cfg = smp.ar_cfg, .top_k = smp.top_k, .seed = smp.seed, .step = a.step, .slot = @intCast(ci), .pick = a.codes + ci * 4 }); + } + // the frame fed back: one body row a CFG row at pos + try k.frameEmbed(s, a.codes, w.embed_audio, w.extra, a.x, 2); + for (0..cfg.layers) |li| { + const L = &w.body[li]; + try k.rmsnorm(s, a.x, H, L.in_norm, a.xn, H, 2, cfg.eps); + try k.gemv(s, L.qkv, a.xn, 2, .{ .y = a.qkv }); + try k.qkRope(s, a.qkv, L.q_norm, L.k_norm, w.inv_freq, a.pos, 1, 2, a.q, a.kc[li], a.vc[li], a.ctx); + try k.attention(s, a.q, a.kc[li], a.vc[li], a.pos, 1, 2, a.ctx, decode_splits, a.ml, a.acc, a.att); + try k.gemv(s, L.o, a.att, 2, .{ .y = a.x, .res = a.x }); + try k.rmsnorm(s, a.x, H, L.post_norm, a.xn, H, 2, cfg.eps); + try k.gemv(s, L.gate_up, a.xn, 2, .{ .glu = true, .y = a.gu }); + try k.gemv(s, L.down, a.gu, 2, .{ .y = a.x, .res = a.x }); + } + try k.rmsnorm(s, a.x, H, w.norm, a.last, H, 2, cfg.eps); + try k.frameDone(s, a.pos, a.step, a.count); + } + + fn copy(a: *Ar, dst: u64, src: u64, bytes: usize) !void { + try a.view(dst).copyFrom(0, src, bytes, a.s.handle); + } + + /// tokens[*count] = *pick (forced frames), as a kernel-free device copy is not count-indexed: through the host. + fn copyI32(a: *Ar, src: u64, table: u64, count: u64) !void { + var c: i32 = 0; + try a.get(count, std.mem.asBytes(&c)); + try a.copy(table + @as(u64, @intCast(c)) * 4, src, 4); + } + + fn pull(a: *Ar, list: *std.ArrayList(f32), src: u64, n: usize) !void { + const at = list.items.len; + try list.resize(a.gpa, at + n); + try a.get(src, std.mem.sliceAsBytes(list.items[at..])); + } + + fn frame(a: *Ar, smp: Sampling, graphs: bool) !void { + if (!graphs) return a.enqueueFrame(smp, false, null); + if (a.graph == null or !std.meta.eql(a.graph_smp, smp) or a.graph_ctx != a.ctx) { + if (a.graph) |*g| g.deinit(); + a.graph = null; + try cuda.graph.beginCapture(a.s, .thread_local); + a.enqueueFrame(smp, false, null) catch |e| { + var g = cuda.graph.endCapture(a.s) catch return e; + g.deinit(); + return e; + }; + var g = try cuda.graph.endCapture(a.s); + defer g.deinit(); + a.graph = try g.instantiate(); + a.graph_smp = smp; + a.graph_ctx = a.ctx; + } + try a.graph.?.launchOn(a.s); + } + + pub const Progress = common.Progress; + + /// Prompt, then frames to the stop code or `limit` kept; `forced_codes` replaces every draw, `trace` keeps logits. + pub fn run(a: *Ar, io: std.Io, ids: []const u32, unc: []const u32, smp: Sampling, limit: usize, graphs: bool, sync_every: usize, forced_codes: ?[]const [8]i32, trace: ?*Trace, progress: ?Progress) !Result { + const t0 = nowNs(io); + const frames_max = if (forced_codes) |fc| @min(limit + 1, fc.len) else limit + 1; + try a.ensureCache(ids.len + frames_max + 2); + try a.prefill(ids, unc); + const t1 = nowNs(io); + try a.setI32(a.pos, @intCast(ids.len)); + try a.setI32(a.count, 0); + const one: u64 = 0; + try a.put(a.step, std.mem.asBytes(&one)); + if (forced_codes) |fc| try a.put(a.forced, std.mem.sliceAsBytes(fc[0..frames_max])); + try a.s.synchronize(); + const tokens = try a.gpa.alloc(i32, frames_max); + defer a.gpa.free(tokens); + var made: usize = 0; + var stop_at: ?usize = null; + const every = @max(1, sync_every); + var reported: usize = 0; + while (made < frames_max and stop_at == null) { + const burst = @min(every, frames_max - made); + for (0..burst) |_| { + if (forced_codes != null) try a.enqueueFrame(smp, true, trace) else try a.frame(smp, graphs); + } + try a.get(a.tokens + made * 4, std.mem.sliceAsBytes(tokens[made .. made + burst])); + for (tokens[made .. made + burst], made..) |tok, fi| if (tok == 0 and forced_codes == null) { + stop_at = fi; + break; + }; + made += burst; + if (progress) |p| if (made - reported >= 25 or stop_at != null or made == frames_max) { + reported = made; + const kept_now = @min(if (stop_at) |st| st else made, limit + 1) -| 1; + p.f(p.ctx, "ar", kept_now, limit); + }; + } + const end = if (stop_at) |st| st else made; // frames 1 .. end - 1 are kept + const kept = @min(end -| 1, limit); + if (kept == 0) return error.NoAudioFrames; + const states = try a.gpa.alloc(u16, kept * 8 * H); + errdefer a.gpa.free(states); + try a.get(a.states + 8 * H * 2, std.mem.sliceAsBytes(states)); + const t2 = nowNs(io); + const dec_s = @as(f64, @floatFromInt(t2 - t1)) / 1e9; + return .{ .states = states, .frames = kept, .stopped = stop_at != null, .prompt_tokens = ids.len, .prefill_ms = ms(t0, t1), .ar_ms = ms(t0, t2), .frames_per_s = @as(f64, @floatFromInt(made)) / @max(dec_s, 1e-9) }; + } +}; + +pub const nowNs = common.nowNs; +pub const ms = common.ms; diff --git a/zig/src/families/music3/blas.zig b/zig/src/families/music3/blas.zig new file mode 100644 index 00000000000..543bcd28061 --- /dev/null +++ b/zig/src/families/music3/blas.zig @@ -0,0 +1,92 @@ +//! cuBLAS (the classic API) at run time: strided batched GEMMs for the prompt rows, the DiT and the DAV. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const Status = c_int; +pub const Handle = ?*opaque {}; +pub const Op = enum(c_int) { n = 0, t = 1 }; +/// cudaDataType_t +pub const DataType = enum(c_int) { f32 = 0, f16 = 2, bf16 = 14 }; +/// cublasComputeType_t CUBLAS_COMPUTE_32F (fp32 compute, no TF32) +pub const compute_32f: c_int = 68; +/// cublasGemmAlgo_t CUBLAS_GEMM_DEFAULT_TENSOR_OP +pub const gemm_default_tensor_op: c_int = 99; +/// cublasMath_t CUBLAS_DEFAULT_MATH, CUBLAS_TF32_TENSOR_OP_MATH +pub const default_math: c_int = 0; +pub const tf32_math: c_int = 3; + +pub const Error = error{ LibraryUnavailable, MissingSymbol, CublasFailed }; + +const S = Status; +const CPtr = ?*const anyopaque; +const Ptr = cuda.abi.DevicePtr; +const StreamHandle = cuda.abi.Stream; + +pub const Api = struct { + cublasCreate_v2: *const fn (*Handle) callconv(.c) S, + cublasDestroy_v2: *const fn (Handle) callconv(.c) S, + cublasSetStream_v2: *const fn (Handle, StreamHandle) callconv(.c) S, + cublasSetWorkspace_v2: *const fn (Handle, Ptr, usize) callconv(.c) S, + cublasSetMathMode: *const fn (Handle, c_int) callconv(.c) S, + cublasGetStatusName: *const fn (S) callconv(.c) ?[*:0]const u8, + cublasGemmStridedBatchedEx: *const fn (Handle, Op, Op, c_int, c_int, c_int, CPtr, Ptr, DataType, c_int, c_longlong, Ptr, DataType, c_int, c_longlong, CPtr, Ptr, DataType, c_int, c_longlong, c_int, c_int, c_int) callconv(.c) S, +}; + +/// The library and one handle with its workspace, bound to a stream per call. +pub const Blas = struct { + lib: std.DynLib, + api: Api, + h: Handle, + + /// The CUDA 13 soname first, then the unversioned link name, as cuda/cublaslt.zig opens cuBLASLt. + pub fn open(workspace: Ptr, workspace_bytes: usize) Error!Blas { + for ([_][]const u8{ "libcublas.so.13", "libcublas.so" }) |path| { + return openPath(path, workspace, workspace_bytes) catch |e| switch (e) { + error.LibraryUnavailable => continue, + else => return e, + }; + } + return error.LibraryUnavailable; + } + + fn openPath(path: []const u8, workspace: Ptr, workspace_bytes: usize) Error!Blas { + var lib = std.DynLib.open(path) catch return error.LibraryUnavailable; + errdefer lib.close(); + var b: Blas = .{ .lib = lib, .api = undefined, .h = null }; + const info = @typeInfo(Api).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + @field(b.api, name) = b.lib.lookup(T, name) orelse { + std.log.err("{s} has no {s}", .{ path, name }); + return error.MissingSymbol; + }; + } + try b.check(b.api.cublasCreate_v2(&b.h), "cublasCreate"); + errdefer _ = b.api.cublasDestroy_v2(b.h); + try b.check(b.api.cublasSetWorkspace_v2(b.h, workspace, workspace_bytes), "cublasSetWorkspace"); + try b.check(b.api.cublasSetMathMode(b.h, default_math), "cublasSetMathMode"); + return b; + } + + /// TF32 tensor-core math for fp32 GEMMs (on) or plain fp32 (off, the default). + pub fn tf32(b: *const Blas, on: bool) Error!void { + try b.check(b.api.cublasSetMathMode(b.h, if (on) tf32_math else default_math), "cublasSetMathMode"); + } + + pub fn close(b: *Blas) void { + _ = b.api.cublasDestroy_v2(b.h); + b.lib.close(); + } + + fn check(b: *const Blas, s: Status, what: []const u8) Error!void { + if (s == 0) return; + const name = b.api.cublasGetStatusName(s); + std.log.err("{s}: {s} ({d})", .{ what, if (name) |p| std.mem.span(p) else "?", s }); + return error.CublasFailed; + } + + /// Column-major C[i] = alpha op(A[i]) op(B[i]) + beta C[i] for i < batch, fp32 compute, on stream `s`. + pub fn gemm(b: *const Blas, s: cuda.Stream, ta: Op, tb: Op, m: usize, n: usize, k: usize, alpha: f32, a: Ptr, lda: usize, sa: usize, bm: Ptr, ldb: usize, sb: usize, beta: f32, c: Ptr, ldc: usize, sc: usize, batch: usize, in_t: DataType, out_t: DataType) Error!void { + try b.check(b.api.cublasSetStream_v2(b.h, s.handle), "cublasSetStream"); + try b.check(b.api.cublasGemmStridedBatchedEx(b.h, ta, tb, @intCast(m), @intCast(n), @intCast(k), &alpha, a, in_t, @intCast(lda), @intCast(sa), bm, in_t, @intCast(ldb), @intCast(sb), &beta, c, out_t, @intCast(ldc), @intCast(sc), @intCast(batch), compute_32f, gemm_default_tensor_op), "cublasGemmStridedBatchedEx"); + } +}; diff --git a/zig/src/families/music3/common.zig b/zig/src/families/music3/common.zig new file mode 100644 index 00000000000..9830edf5b3a --- /dev/null +++ b/zig/src/families/music3/common.zig @@ -0,0 +1,73 @@ +//! What every backend shares: the AR's sampling knobs, its result and trace, a song's timings, the clock. +const std = @import("std"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); + +pub const Sampling = struct { + ar_cfg: f32 = 1.5, + top_k: i32 = 50, + seed: u64 = 0, // the AR stage's own seed (config.deriveSeed(song seed, "ar")) +}; + +/// Per-frame logits for parity (teacher forcing): code 0 [2, 16385] and the depth heads [7, 2, 1024], fp32. +pub const Trace = struct { + c0: std.ArrayList(f32) = .empty, + depth: std.ArrayList(f32) = .empty, +}; + +pub const Result = struct { + states: []u16, // bf16 [frames, 8 * 4096] of the kept frames (frame 0 dropped, as the reference) + frames: usize, + stopped: bool, + prompt_tokens: usize, + prefill_ms: f64, + ar_ms: f64, + frames_per_s: f64, +}; + +pub const Progress = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void, +}; + +pub const Song = struct { + audio: []f32, // [2, samples] + samples: usize, + frames: usize, + stopped: bool, + prompt_tokens: usize, + prefill_ms: f64, + ar_ms: f64, + frames_per_s: f64, + dit_ms: f64, + dav_ms: f64, + total_ms: f64, + latent_frames: usize, + peak_device_gb: f64, +}; + +/// Weight bytes a frame reads: body and lm_head once, the depth decoder 7 times, each head once. +pub fn frameBytes(a: *const wts.Ar) f64 { + const per: f64 = if (a.format == .int8) 1 else 2; + var n: f64 = 0; + const add = struct { + fn m(x: wts.Mat) f64 { + return @floatFromInt(x.n * x.k); + } + }.m; + for (a.body) |L| n += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down); + n += add(a.lm_head); + var dn: f64 = add(a.projection); + for (a.depth) |L| dn += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down); + n += @as(f64, cfg.codebooks - 1) * dn; + for (a.heads) |h| n += add(h); + return n * per; +} + +pub fn nowNs(io: std.Io) i128 { + return @intCast(std.Io.Clock.awake.now(io).toNanoseconds()); +} + +pub fn ms(a: i128, b: i128) f64 { + return @as(f64, @floatFromInt(b - a)) / 1e6; +} diff --git a/zig/src/families/music3/config.zig b/zig/src/families/music3/config.zig new file mode 100644 index 00000000000..8f66f86a099 --- /dev/null +++ b/zig/src/families/music3/config.zig @@ -0,0 +1,142 @@ +//! MiniMax Music 3's shapes, the request settings and the reference's schedules (ComfyUI's comfy/ldm/minimax_music). +const std = @import("std"); + +pub const hidden = 4096; +pub const layers = 36; +pub const heads = 32; +pub const kv_heads = 8; +pub const head_dim = 128; +pub const qkv_width = (heads + 2 * kv_heads) * head_dim; // 6144 +pub const mlp = 12288; +pub const rope_theta: f32 = 1_000_000.0; +pub const eps: f32 = 1e-6; +pub const prompt_vocab = 151675; // embed_tokens_prefill rows (the text ids) +pub const c0_codes = 16384; // code 0's codes; lm_head_pruned has one more row (0 = stop) +pub const codebooks = 8; +pub const codebook_size = 1024; +pub const depth_layers = 4; +pub const depth_heads = 16; +pub const depth_head_dim = 256; +pub const depth_mlp = 6144; +pub const frame_rate = 25; +pub const sample_rate = 44100; +pub const max_frames = 9000; // 6 minutes +pub const max_prompt = 5000; + +// the DiT +pub const dit_width = 2048; +pub const dit_blocks = 36; +pub const dit_heads = 32; +pub const dit_head_dim = 64; +pub const dit_mlp = 8192; +pub const dit_in = 2304; // [latent 128, zeros 128, condition 2048] +pub const latent_ch = 128; +pub const window_frames = 200; +pub const hop_frames = 100; + +/// One request's knobs (the reference's defaults). +pub const Settings = struct { + seconds: f64 = 60.0, + seed: u64 = 0, + ar_cfg: f32 = 1.5, + top_k: i32 = 50, + steps: usize = 30, + dit_cfg: f32 = 1.7, + + /// The AR frame cap: round(seconds * 25), at most 9000. + pub fn frameLimit(s: Settings) usize { + const f = @round(s.seconds * frame_rate); + if (!(f >= 1)) return 1; + return @min(max_frames, @as(usize, @intFromFloat(f))); + } +}; + +/// Latent frames (44100 / 512 a second) for AR frames (25 a second): max(1, int(frames 44100 / 24000 960 / 512)). +pub fn framesToLatents(frames: usize) usize { + const v: f64 = @as(f64, @floatFromInt(frames)) * 44100.0 / 24000.0 * 960.0 / 512.0; + return @max(1, @as(usize, @intFromFloat(@floor(v)))); +} + +/// PyTorch's interpolate(mode="nearest") indices from `source` rows to `target` (float32 scale, floor). +pub fn nearest(gpa: std.mem.Allocator, source: usize, target: usize) ![]i32 { + const out = try gpa.alloc(i32, target); + const scale: f32 = @as(f32, @floatFromInt(source)) / @as(f32, @floatFromInt(target)); + for (out, 0..) |*o, i| { + const v: f32 = @floor(@as(f32, @floatFromInt(i)) * scale); + o.* = @intCast(@min(@as(usize, @intFromFloat(v)), source - 1)); + } + return out; +} + +/// ComfyUI's "simple" schedule over 1000 discrete flow sigmas (shift 1): steps + 1 values from 1 down to 0. +pub fn sigmas(gpa: std.mem.Allocator, steps: usize) ![]f32 { + const out = try gpa.alloc(f32, steps + 1); + const stride: f64 = 1000.0 / @as(f64, @floatFromInt(steps)); + for (0..steps) |i| { + const idx: usize = @intFromFloat(@floor(@as(f64, @floatFromInt(i)) * stride)); + // table[-(1 + idx)] with table[j] = (j + 1) / 1000 in float32 + const j = 999 - idx; + out[i] = @as(f32, @floatFromInt(j + 1)) / @as(f32, 1000.0); + } + out[steps] = 0; + return out; +} + +pub const Span = struct { start: usize, len: usize }; + +/// The DiT's windows over `length` latent rows: 200 AR frames' worth every 100, the last one ending at length. +pub fn windows(gpa: std.mem.Allocator, length: usize) ![]Span { + const size = framesToLatents(window_frames); + const hop = framesToLatents(hop_frames); + var list: std.ArrayList(Span) = .empty; + errdefer list.deinit(gpa); + if (length <= size) { + try list.append(gpa, .{ .start = 0, .len = length }); + return list.toOwnedSlice(gpa); + } + var start: usize = 0; + while (true) { + const end = @min(start + size, length); + try list.append(gpa, .{ .start = start, .len = end - start }); + if (end == length) break; + start += hop; + } + return list.toOwnedSlice(gpa); +} + +/// A stage's seed from the song seed: blake2b-64, personalization "minimax-ttm", as the reference derives it. +pub fn deriveSeed(seed: u64, part: []const u8) u64 { + var person: [16]u8 = @splat(0); + @memcpy(person[0..11], "minimax-ttm"); + var h = std.crypto.hash.blake2.Blake2b(64).init(.{ .context = person }); + var b: [8]u8 = undefined; + std.mem.writeInt(u64, &b, seed, .little); + h.update(&b); + var l: [4]u8 = undefined; + std.mem.writeInt(u32, &l, @intCast(part.len), .little); + h.update(&l); + h.update(part); + var out: [8]u8 = undefined; + h.final(&out); + return std.mem.readInt(u64, &out, .little) & ((@as(u64, 1) << 63) - 1); +} + +test "schedules match the reference" { + const gpa = std.testing.allocator; + try std.testing.expectEqual(@as(usize, 689), framesToLatents(200)); + try std.testing.expectEqual(@as(usize, 344), framesToLatents(100)); + try std.testing.expectEqual(@as(usize, 5167), framesToLatents(1500)); + const s = try sigmas(gpa, 30); + defer gpa.free(s); + try std.testing.expectEqual(@as(f32, 1.0), s[0]); + try std.testing.expectEqual(@as(f32, 0.967), s[1]); + try std.testing.expectEqual(@as(f32, 0), s[30]); + const w = try windows(gpa, 5167); + defer gpa.free(w); + try std.testing.expectEqual(@as(usize, 15), w.len); + try std.testing.expectEqual(@as(usize, 5167), w[w.len - 1].start + w[w.len - 1].len); + const n = try nearest(gpa, 1500, 5167); + defer gpa.free(n); + try std.testing.expectEqual(@as(i32, 1499), n[5166]); + try std.testing.expectEqual(@as(usize, 1500), (Settings{ .seconds = 60 }).frameLimit()); +} diff --git a/zig/src/families/music3/dav.zig b/zig/src/families/music3/dav.zig new file mode 100644 index 00000000000..9e10dfd99fe --- /dev/null +++ b/zig/src/families/music3/dav.zig @@ -0,0 +1,227 @@ +//! The DAV in fp32: latents [L, 128] to stereo 44.1 kHz; convs as tap SGEMMs on rows with zero halos, in chunks. +const std = @import("std"); +const cuda = @import("cuda"); +const wts = @import("weights.zig"); +const kern = @import("kernels.zig"); + +const Buf = cuda.DeviceBuffer; +const halo_rows = 27; // the widest conv's padding: 3 x dilation 9 + +pub const Options = struct { chunk: usize = 512, context: usize = 32, level: bool = true, tf32: bool = false }; + +pub const Dav = struct { + gpa: std.mem.Allocator, + k: *kern.Kernels, + w: *const wts.Dav, + d: *const cuda.Driver, + s: cuda.Stream, + o: Options = .{}, + + fn i(x: usize) i32 { + return @intCast(x); + } + + fn view(dv: *Dav, p: u64) Buf { + return .{ .d = dv.d, .ptr = p, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + const Bufs = struct { lat: u64, x0: u64, p: u64, r: u64, y: u64, z: u64, out: u64, cap: usize, zcap: usize }; + + /// y [T, Cout] = bias + sum_j W_j x[t + j dil - pad] with x padded (data at halo_rows rows in). + fn conv(dv: *Dav, c: wts.Conv, xpad: u64, T: usize, dil: usize, y: u64) !void { + const k = dv.k; + const pad = (c.k - 1) / 2 * dil; + var a: cuda.Args = .{}; + a.add(y); + a.add(c.b); + a.add(i(c.cout)); + a.add(T * c.cout); + try k.flat(.bias_rows, dv.s, T * c.cout, &a); + for (0..c.k) |j| { + const row = halo_rows - pad + j * dil; + try k.blas.gemm(dv.s, .t, .n, c.cout, T, c.cin, 1.0, c.w + j * c.cout * c.cin * 4, c.cin, 0, xpad + row * c.cin * 4, c.cin, 0, 1.0, y, c.cout, 0, 1, .f32, .f32); + } + } + + /// y = snake(x) into the padded buffer `pad` (C channels, T rows), its halos zeroed. + fn snakeInto(dv: *Dav, x: u64, alpha: u64, T: usize, C: usize, pad: u64) !void { + const k = dv.k; + var z1: cuda.Args = .{}; + z1.add(pad); + z1.add(halo_rows * C); + try k.flat(.zero_rows, dv.s, halo_rows * C, &z1); + var z2: cuda.Args = .{}; + z2.add(pad + (halo_rows + T) * C * 4); + z2.add(halo_rows * C); + try k.flat(.zero_rows, dv.s, halo_rows * C, &z2); + var a: cuda.Args = .{}; + a.add(x); + a.add(alpha); + a.add(pad + halo_rows * C * 4); + a.add(i(C)); + a.add(T * C); + try k.flat(.snake, dv.s, T * C, &a); + } + + fn data(p: u64, C: usize) u64 { + return p + halo_rows * C * 4; + } + + /// One stereo half's latent rows [a, a + T) -> audio [T 512] into b.out. + fn decodeRows(dv: *Dav, b: Bufs, a0: usize, T0: usize, half: usize) !usize { + const k = dv.k; + const s = dv.s; + const w = dv.w; + { + var a: cuda.Args = .{}; + a.add(b.lat); + a.add(i(a0)); + a.add(i(T0)); + a.add(i(half)); + a.add(b.x0); + try k.flat(.latent_half, s, T0 * 64, &a); + } + // in_proj (k 1) straight into the padded buffer, then conv0 (k 7) + var T = T0; + { + const C = w.in_proj.cout; + var z1: cuda.Args = .{}; + z1.add(b.p); + z1.add(halo_rows * C); + try k.flat(.zero_rows, s, halo_rows * C, &z1); + var z2: cuda.Args = .{}; + z2.add(b.p + (halo_rows + T) * C * 4); + z2.add(halo_rows * C); + try k.flat(.zero_rows, s, halo_rows * C, &z2); + const c = w.in_proj; + var a: cuda.Args = .{}; + a.add(data(b.p, C)); + a.add(c.b); + a.add(i(C)); + a.add(T * C); + try k.flat(.bias_rows, s, T * C, &a); + try k.blas.gemm(s, .t, .n, C, T, c.cin, 1.0, c.w, c.cin, 0, b.x0, c.cin, 0, 1.0, data(b.p, C), C, 0, 1, .f32, .f32); + } + try dv.conv(w.conv0, b.p, T, 1, b.r); + var C = w.conv0.cout; + for (w.blocks) |B| { + // snake, the transposed conv (stride s, kernel 2s) as one GEMM into its taps, then the overlap-add + try dv.snakeInto(b.r, B.alpha, T, C, b.p); + const up = B.up; + if (T * 2 * B.stride * up.cout > b.zcap) return error.DavBuffers; + try k.blas.gemm(s, .t, .n, up.k * up.cout, T, up.cin, 1.0, up.w, up.cin, 0, data(b.p, C), up.cin, 0, 0.0, b.z, up.k * up.cout, 0, 1, .f32, .f32); + const Tout = T * B.stride; + { + var a: cuda.Args = .{}; + a.add(b.z); + a.add(up.b); + a.add(i(T)); + a.add(i(B.stride)); + a.add(i((B.stride + 1) / 2)); + a.add(i(up.cout)); + a.add(i(Tout)); + a.add(b.r); + try k.flat(.overlap_add, s, Tout * up.cout, &a); + } + T = Tout; + C = up.cout; + if ((T + 2 * halo_rows) * C > b.cap) return error.DavBuffers; + for (B.res) |R| { + try dv.snakeInto(b.r, R.a1, T, C, b.p); + try dv.conv(R.c1, b.p, T, R.dilation, b.y); + { + var a: cuda.Args = .{}; + a.add(b.y); + a.add(R.a2); + a.add(b.y); + a.add(i(C)); + a.add(T * C); + try k.flat(.snake, s, T * C, &a); + } + // r += c2(y) (k 1) + its bias + try k.blas.gemm(s, .t, .n, C, T, C, 1.0, R.c2.w, C, 0, b.y, C, 0, 1.0, b.r, C, 0, 1, .f32, .f32); + var a: cuda.Args = .{}; + a.add(b.r); + a.add(R.c2.b); + a.add(i(C)); + a.add(T * C); + try k.flat(.add_bias, s, T * C, &a); + } + } + try dv.snakeInto(b.r, w.alpha_out, T, C, b.p); + try dv.conv(w.conv_out, b.p, T, 1, b.out); + var a: cuda.Args = .{}; + a.add(b.out); + a.add(T); + try k.flat(.tanh, s, T, &a); + return T; + } + + /// Latents [L, 128] (host) -> stereo [2, 512 L] (host, f32), then ComfyUI's level rule (/ max(1, 5 std)). + pub fn decode(dv: *Dav, latents: []const f32, L: usize) ![]f32 { + const chunk = dv.o.chunk; + const ctxr = dv.o.context; + const rows_max = @min(L, chunk + 2 * ctxr); + const t_max = rows_max * 512; + var list: std.ArrayList(Buf) = .empty; + defer { + for (list.items) |*bf| bf.free(); + list.deinit(dv.gpa); + } + const P = struct { + fn mk(l: *std.ArrayList(Buf), gpa: std.mem.Allocator, d: *const cuda.Driver, bytes: usize) !u64 { + const bf = try Buf.alloc(d, @max(bytes, 256)); + try l.append(gpa, bf); + return bf.ptr; + } + }; + // the largest T x C over the stages: 96 x 512 rows (equal to 192 x 256) + const cap = (t_max + 2 * halo_rows) * 96 + (rows_max * 8 + 2 * halo_rows) * 1536; + const zcap = t_max / 2 * 4 * 96; + const b: Bufs = .{ + .lat = try P.mk(&list, dv.gpa, dv.d, L * 128 * 4), + .x0 = try P.mk(&list, dv.gpa, dv.d, rows_max * 64 * 4), + .p = try P.mk(&list, dv.gpa, dv.d, cap * 4), + .r = try P.mk(&list, dv.gpa, dv.d, cap * 4), + .y = try P.mk(&list, dv.gpa, dv.d, cap * 4), + .z = try P.mk(&list, dv.gpa, dv.d, zcap * 4), + .out = try P.mk(&list, dv.gpa, dv.d, t_max * 4), + .cap = cap, + .zcap = zcap, + }; + try dv.view(b.lat).upload(0, std.mem.sliceAsBytes(latents)); + try dv.k.blas.tf32(dv.o.tf32); + defer dv.k.blas.tf32(false) catch {}; + const audio = try dv.gpa.alloc(f32, 2 * L * 512); + errdefer dv.gpa.free(audio); + var start: usize = 0; + while (start < L) : (start += chunk) { + const end = @min(start + chunk, L); + const a0 = start -| ctxr; + const a1 = @min(L, end + ctxr); + for (0..2) |half| { + const T = try dv.decodeRows(b, a0, a1 - a0, half); + std.debug.assert(T == (a1 - a0) * 512); + const off = (start - a0) * 512; + const n = (end - start) * 512; + try dv.view(b.out + off * 4).downloadAsync(0, std.mem.sliceAsBytes(audio[half * L * 512 + start * 512 ..][0..n]), dv.s.handle); + } + try dv.s.synchronize(); + } + // level: std over both channels (unbiased), divide by max(1, 5 std) + var mean: f64 = 0; + for (audio) |v| mean += v; + mean /= @floatFromInt(audio.len); + var ss: f64 = 0; + for (audio) |v| { + const dd = @as(f64, v) - mean; + ss += dd * dd; + } + const sd = @sqrt(ss / @as(f64, @floatFromInt(audio.len - 1))); + const level = @max(1.0, sd * 5.0); + if (dv.o.level and level > 1.0) for (audio) |*v| { + v.* = @floatCast(@as(f64, v.*) / level); + }; + return audio; + } +}; diff --git a/zig/src/families/music3/dit.zig b/zig/src/families/music3/dit.zig new file mode 100644 index 00000000000..5e45357e118 --- /dev/null +++ b/zig/src/families/music3/dit.zig @@ -0,0 +1,382 @@ +//! The DiT: condition, then Euler steps over windows (both CFG branches a forward) on cuBLASLt fp16 and our kernels. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const kern = @import("kernels.zig"); + +const Buf = cuda.DeviceBuffer; +const D = cfg.dit_width; + +pub const Options = struct { + window_batch: usize = 16, // windows a forward (each with both CFG branches) + attn_group: usize = 8, // sequences a score buffer + comfy_rope: bool = true, // rope angles rounded to fp16 before cos / sin, as ComfyUI computes them + flash: bool = true, // the tensor-core flash attention kernel (else cuBLAS score GEMMs, a softmax, cuBLAS PV) +}; + +pub const Dit = struct { + gpa: std.mem.Allocator, + k: *kern.Kernels, + w: *const wts.Dit, + d: *const cuda.Driver, + s: cuda.Stream, + o: Options, + + fn i(x: usize) i32 { + return @intCast(x); + } + + const Scratch = struct { + list: std.ArrayList(Buf) = .empty, + gpa: std.mem.Allocator, + d: *const cuda.Driver, + fn mk(sc: *Scratch, bytes: usize) !u64 { + const b = try Buf.alloc(sc.d, @max(bytes, 256)); + try sc.list.append(sc.gpa, b); + return b.ptr; + } + fn deinit(sc: *Scratch) void { + for (sc.list.items) |*b| b.free(); + sc.list.deinit(sc.gpa); + } + }; + + fn view(dt: *Dit, p: u64) Buf { + return .{ .d = dt.d, .ptr = p, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + /// The condition [L, 2048] fp16 (device) from frame states bf16 [T, 8, 4096] (host). + pub fn condition(dt: *Dit, sc: *Scratch, states: []const u16, frames: usize, L: usize) !u64 { + const k = dt.k; + const s = dt.s; + const st_d = try sc.mk(states.len * 2); + try dt.view(st_d).upload(0, std.mem.sliceAsBytes(states)); + const w8 = try sc.mk(32); + try dt.view(w8).upload(0, std.mem.sliceAsBytes(&dt.w.cond_w8)); + const mixed = try sc.mk(frames * 4096 * 2); + var a: cuda.Args = .{}; + a.add(st_d); + a.add(w8); + a.add(dt.w.cond_scale); + a.add(mixed); + a.add(i(frames)); + try k.flat(.cond_mix, s, frames * 4096, &a); + const col = try sc.mk(frames * 3 * 4096 * 2); + var b: cuda.Args = .{}; + b.add(mixed); + b.add(col); + b.add(i(frames)); + b.add(i(4096)); + try k.flat(.im2col3, s, frames * 3 * 4096, &b); + const conv = try sc.mk(frames * D * 2); + try k.lt.linear(s, col, dt.w.cond_conv, dt.w.cond_bias, conv, frames, D, 3 * 4096, false); + const idx = try cfg.nearest(dt.gpa, frames, L); + defer dt.gpa.free(idx); + const idx_d = try sc.mk(L * 4); + try dt.view(idx_d).upload(0, std.mem.sliceAsBytes(idx)); + const cond = try sc.mk(L * D * 2); + var c: cuda.Args = .{}; + c.add(conv); + c.add(idx_d); + c.add(cond); + c.add(i(D)); + try k.go(.gather_rows_h, s, .{ L, 1, 1 }, 256, &c); + return cond; + } + + /// cos, sin [Lseq, 16, 2] (f32 values of fp16 numbers) for positions 0..Lseq (0 is the timestep token). + fn ropeTable(dt: *Dit, sc: *Scratch, Lseq: usize) !u64 { + const host = try dt.gpa.alloc(f32, Lseq * 32); + defer dt.gpa.free(host); + for (0..Lseq) |j| for (0..16) |q| { + var ang: f32 = @as(f32, @floatFromInt(j)) * dt.w.inv_freq[q]; + if (dt.o.comfy_rope) ang = @floatCast(@as(f16, @floatCast(ang))); + host[(j * 16 + q) * 2] = @floatCast(@as(f16, @floatCast(@cos(ang)))); + host[(j * 16 + q) * 2 + 1] = @floatCast(@as(f16, @floatCast(@sin(ang)))); + }; + const p = try sc.mk(host.len * 4); + try dt.view(p).upload(0, std.mem.sliceAsBytes(host)); + return p; + } + + pub const Progress = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void, + }; + + pub const Probe = struct { cfg: f32, t: f32 }; // one forward at timestep t, returning u + (c - u) cfg + + /// Frame states (bf16 [frames, 32768]) to latents [L, 128]; `noise` or the seed's own; `probe`: one forward only. + pub fn denoise(dt: *Dit, states: []const u16, frames: usize, steps: usize, dit_cfg: f32, seed: u64, noise: ?[]const f32, probe: ?Probe, progress: ?Progress) ![]f32 { + const k = dt.k; + const s = dt.s; + const L = cfg.framesToLatents(frames); + var sc: Scratch = .{ .gpa = dt.gpa, .d = dt.d }; + defer sc.deinit(); + const cond = try dt.condition(&sc, states, frames, L); + const spans = try cfg.windows(dt.gpa, L); + defer dt.gpa.free(spans); + const x = try sc.mk(L * 128 * 4); + if (noise) |nz| { + if (nz.len != L * 128) return error.NoiseShape; + try dt.view(x).upload(0, std.mem.sliceAsBytes(nz)); + } else { + var a: cuda.Args = .{}; + a.add(x); + a.add(seed); + a.add(L * 128); + try k.flat(.noise, s, L * 128 / 2 + 1, &a); + } + const vsum = try sc.mk(L * 128 * 4); + const vcnt = try sc.mk(L * 128 * 4); + for ([_]u64{ vsum, vcnt }) |p| { + var b = dt.view(p); + b.len = L * 128 * 4; + try b.fill8(0, s.handle); + } + // per-batch buffers at the largest batch + const nb_max = @min(dt.o.window_batch, spans.len); + var lw_max: usize = 0; + for (spans) |sp| lw_max = @max(lw_max, sp.len); + const S_max = 2 * nb_max; + const Lseq_max = lw_max + 1; + const T_max = S_max * Lseq_max; + const ld_max = (Lseq_max + 7) / 8 * 8; + const full = try sc.mk(S_max * lw_max * cfg.dit_in * 2); + const full2 = try sc.mk(S_max * lw_max * cfg.dit_in * 2); + const h = try sc.mk(T_max * D * 2); + const hn = try sc.mk(T_max * D * 2); + const qkv = try sc.mk(T_max * 3 * D * 2); + const qh = if (dt.o.flash) 0 else try sc.mk(T_max * D * 2); + const kh = if (dt.o.flash) 0 else try sc.mk(T_max * D * 2); + const vh = if (dt.o.flash) 0 else try sc.mk(T_max * D * 2); + const oh = if (dt.o.flash) 0 else try sc.mk(T_max * D * 2); + const att = try sc.mk(T_max * D * 2); + const ffi = try sc.mk(T_max * 2 * cfg.dit_mlp * 2); + const glu = try sc.mk(T_max * cfg.dit_mlp * 2); + const G = dt.o.attn_group; + const scores = if (dt.o.flash) 0 else try sc.mk(G * 32 * Lseq_max * ld_max * 4); + const probs = if (dt.o.flash) 0 else try sc.mk(G * 32 * Lseq_max * ld_max * 2); + const po = try sc.mk(S_max * lw_max * 128 * 2); + const pp = try sc.mk(S_max * lw_max * 128 * 2); + const tf = try sc.mk(256 * 2); + const te1 = try sc.mk(D * 2); + const te2 = try sc.mk(D * 2); + const te = try sc.mk(D * 2); + const wins_d = try sc.mk(2 * nb_max * 4); + const lens_d = try sc.mk(S_max * 4); + const rope_tabs = try dt.gpa.alloc(?u64, Lseq_max + 1); + defer dt.gpa.free(rope_tabs); + @memset(rope_tabs, null); + const sig = try cfg.sigmas(dt.gpa, steps); + defer dt.gpa.free(sig); + const n_steps = if (probe != null) 1 else steps; + for (0..n_steps) |step| { + const sigma = sig[step]; + const t_val: f32 = if (probe) |p| p.t else 1.0 - sigma; + const guide = if (probe) |p| p.cfg else dit_cfg; + // the timestep embedding (the same for every window and branch) + { + var a: cuda.Args = .{}; + a.add(dt.w.time_features); + a.add(t_val); + a.add(tf); + try k.go(.time_features, s, .{ 1, 1, 1 }, 128, &a); + try dt.small(dt.w.time_in, dt.w.time_in_b, tf, 256, D, te1); + var b: cuda.Args = .{}; + b.add(te1); + b.add(te2); + b.add(i(D)); + try k.go(.silu_h, s, .{ 1, 1, 1 }, 1024, &b); + try dt.small(dt.w.time_out, dt.w.time_out_b, te2, D, D, te); + } + var b0: usize = 0; + while (b0 < spans.len) : (b0 += nb_max) { + const nb = @min(nb_max, spans.len - b0); + const batch = spans[b0 .. b0 + nb]; + var lw: usize = 0; + for (batch) |sp| lw = @max(lw, sp.len); + const S = 2 * nb; + const Lseq = lw + 1; + const T = S * Lseq; + const ld = (Lseq + 7) / 8 * 8; + var wins: [64]i32 = undefined; + var lens: [128]i32 = undefined; + for (batch, 0..) |sp, wi| { + wins[2 * wi] = @intCast(sp.start); + wins[2 * wi + 1] = @intCast(sp.len); + lens[wi] = @intCast(sp.len + 1); + lens[nb + wi] = @intCast(sp.len + 1); + } + try dt.view(wins_d).uploadAsync(0, std.mem.sliceAsBytes(wins[0 .. 2 * nb]), s.handle); + try dt.view(lens_d).uploadAsync(0, std.mem.sliceAsBytes(lens[0..S]), s.handle); + if (rope_tabs[Lseq] == null) rope_tabs[Lseq] = try dt.ropeTable(&sc, Lseq); + const cs = rope_tabs[Lseq].?; + // inputs: [x, 0, condition] + preprocess(...), project_in into rows 1.. of each sequence + { + var a: cuda.Args = .{}; + a.add(x); + a.add(cond); + a.add(dt.w.cond_bias); + a.add(wins_d); + a.add(i(nb)); + a.add(i(lw)); + a.add(full); + try k.go(.dit_input, s, .{ lw, S, 1 }, 256, &a); + } + try k.lt.linear(s, full, dt.w.pre, 0, full2, S * lw, cfg.dit_in, cfg.dit_in, false); + try dt.addH(full2, full, S * lw * cfg.dit_in); + try k.hgemm(s, .t, .n, D, lw, cfg.dit_in, 1.0, dt.w.project_in, cfg.dit_in, 0, full2, cfg.dit_in, lw * cfg.dit_in, 0.0, h + D * 2, D, Lseq * D, S, .f16); + { + var a: cuda.Args = .{}; + a.add(te); + a.add(h); + a.add(i(Lseq)); + try k.go(.put_time, s, .{ S, 1, 1 }, 256, &a); + } + for (&dt.w.blocks, 0..) |*B, bi| { + // the previous block's ff_out bias goes in with this block's pre-norm + try dt.layerNorm(h, if (bi > 0) dt.w.blocks[bi - 1].ff_out_b else 0, B.pre_g, B.pre_b, hn, T); + try k.lt.linear(s, hn, B.qkv, 0, qkv, T, 3 * D, D, false); + if (!dt.o.flash) { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(cs); + a.add(i(Lseq)); + a.add(qh); + a.add(kh); + a.add(vh); + try k.go(.dit_rope, s, .{ Lseq, S, 1 }, 256, &a); + } + if (dt.o.flash) { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(cs); + a.add(i(Lseq)); + a.add(lens_d); + a.add(@as(f32, 0.125)); + a.add(att); + try k.go(.flash_attn, s, .{ (Lseq + 127) / 128, S * 32, 1 }, 256, &a); + } else { + var g0: usize = 0; + while (g0 < S) : (g0 += G) { + const g = @min(G, S - g0); + const off = g0 * 32 * Lseq * 64 * 2; + const bh = g * 32; + try k.hgemm(s, .t, .n, Lseq, Lseq, 64, 0.125, kh + off, 64, Lseq * 64, qh + off, 64, Lseq * 64, 0.0, scores, ld, Lseq * ld, bh, .f32); + var a: cuda.Args = .{}; + a.add(scores); + a.add(i(ld)); + a.add(i(Lseq)); + a.add(lens_d); + a.add(i(g0)); + a.add(probs); + try k.go(.softmax_rows, s, .{ Lseq, bh, 1 }, 256, &a); + try k.hgemm(s, .n, .n, 64, Lseq, Lseq, 1.0, vh + off, 64, Lseq * 64, probs, ld, Lseq * ld, 0.0, oh + off, 64, Lseq * 64, bh, .f16); + } + var a: cuda.Args = .{}; + a.add(oh); + a.add(i(Lseq)); + a.add(att); + try k.go(.heads_to_rows, s, .{ Lseq, S, 1 }, 256, &a); + } + try k.lt.linear(s, att, B.out, 0, h, T, D, D, true); + try dt.layerNorm(h, 0, B.ff_g, B.ff_b, hn, T); + try k.lt.linear(s, hn, B.ff_in, 0, ffi, T, 2 * cfg.dit_mlp, D, false); + { + var a: cuda.Args = .{}; + a.add(ffi); + a.add(B.ff_in_b); + a.add(glu); + a.add(T); + try k.flat(.glu_h, s, T * 1024, &a); + } + try k.lt.linear(s, glu, B.ff_out, 0, h, T, D, cfg.dit_mlp, true); + } + { + var a: cuda.Args = .{}; + a.add(h); + a.add(dt.w.blocks[cfg.dit_blocks - 1].ff_out_b); + a.add(T * D); + try k.flat(.bias_h, s, T * D, &a); + } + // project_out on rows 1.., the 1x1 postprocess, the guided velocity into the sums + try k.hgemm(s, .t, .n, 128, lw, D, 1.0, dt.w.project_out, D, 0, h + D * 2, D, Lseq * D, 0.0, po, 128, lw * 128, S, .f16); + try k.lt.linear(s, po, dt.w.post, 0, pp, S * lw, 128, 128, false); + { + var a: cuda.Args = .{}; + a.add(po); + a.add(pp); + a.add(wins_d); + a.add(i(nb)); + a.add(i(lw)); + a.add(guide); + a.add(i(L)); + a.add(vsum); + a.add(vcnt); + try k.flat(.dit_gather, s, L * 128, &a); + } + } + if (probe != null) { + // the model output itself: vsum / vcnt, with no Euler step + const out = try dt.gpa.alloc(f32, L * 128); + errdefer dt.gpa.free(out); + const cnt = try dt.gpa.alloc(f32, L * 128); + defer dt.gpa.free(cnt); + try dt.view(vsum).downloadAsync(0, std.mem.sliceAsBytes(out), s.handle); + try dt.view(vcnt).downloadAsync(0, std.mem.sliceAsBytes(cnt), s.handle); + try s.synchronize(); + for (out, cnt) |*o, c| o.* /= c; + return out; + } + { + var a: cuda.Args = .{}; + a.add(x); + a.add(vsum); + a.add(vcnt); + a.add(sig[step + 1] - sigma); + a.add(L * 128); + try k.flat(.euler, s, L * 128, &a); + } + if (progress) |p| { + try s.synchronize(); + p.f(p.ctx, "dit", step + 1, steps); + } + } + const out = try dt.gpa.alloc(f32, L * 128); + errdefer dt.gpa.free(out); + try dt.view(x).downloadAsync(0, std.mem.sliceAsBytes(out), s.handle); + try s.synchronize(); + return out; + } + + fn small(dt: *Dit, w: u64, b: u64, x: u64, K: usize, N: usize, y: u64) !void { + var a: cuda.Args = .{}; + a.add(w); + a.add(b); + a.add(x); + a.add(i(K)); + a.add(i(N)); + a.add(y); + try dt.k.go(.linear_h1, dt.s, .{ (N + 7) / 8, 1, 1 }, 256, &a); + } + + fn addH(dt: *Dit, a_: u64, b_: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(a_); + a.add(b_); + a.add(n); + try dt.k.flat(.add_h, dt.s, n, &a); + } + + fn layerNorm(dt: *Dit, x: u64, bias: u64, g: u64, b: u64, y: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(bias); + a.add(g); + a.add(b); + a.add(y); + try dt.k.go(.layernorm_h, dt.s, .{ rows, 1, 1 }, 256, &a); + } +}; diff --git a/zig/src/families/music3/engine.zig b/zig/src/families/music3/engine.zig new file mode 100644 index 00000000000..bde21f14e71 --- /dev/null +++ b/zig/src/families/music3/engine.zig @@ -0,0 +1,140 @@ +//! MiniMax Music 3 on one GPU: the three stages behind one load (AR frames, the DiT, the DAV), timed apart. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const kern = @import("kernels.zig"); +const prompt = @import("prompt.zig"); +const ar_ = @import("ar.zig"); +const dit_ = @import("dit.zig"); +const dav_ = @import("dav.zig"); +const common = @import("common.zig"); +const Store = @import("store.zig").Store; + +pub const Options = struct { + format: wts.Format = .int8, + depth_group: usize = 128, // int8 depth decoder and heads: a scale a group of 128 inputs (0: a row) + load_ar: bool = true, + load_dit: bool = true, + load_dav: bool = true, + dit: dit_.Options = .{}, + dav_tf32: bool = false, + graphs: bool = true, + sync_every: usize = 16, + log: bool = true, +}; + +pub const Song = common.Song; + +pub const Progress = common.Progress; + +pub const Engine = struct { + gpa: std.mem.Allocator, + o: Options, + driver: cuda.Driver, + ctx: cuda.Context, + stream: cuda.Stream, + k: *kern.Kernels, + store: Store, + arw: ?wts.Ar = null, + ditw: ?wts.Dit = null, + davw: ?wts.Dav = null, + tok: ?core.tokenizer.Tokenizer = null, + ar: ?ar_.Ar = null, + load_ms: f64 = 0, + + pub fn create(gpa: std.mem.Allocator, io: std.Io, model_dir: []const u8, o: Options) !*Engine { + const t0 = ar_.nowNs(io); + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.* = .{ .gpa = gpa, .o = o, .driver = undefined, .ctx = undefined, .stream = undefined, .k = undefined, .store = undefined }; + e.driver = try cuda.Driver.open(); + e.ctx = try cuda.Context.init(&e.driver, 0); + e.stream = try cuda.Stream.init(&e.driver, true); + e.k = try gpa.create(kern.Kernels); + e.k.* = try kern.Kernels.load(gpa, &e.driver, &e.ctx); + e.store = .{ .gpa = gpa, .d = &e.driver }; + if (o.load_ar) { + e.arw = try wts.loadAr(gpa, io, &e.store, model_dir, o.format, o.depth_group, .{ .ctx = e, .f = quantize }, o.log); + e.tok = try core.tokenizer.parse(gpa, e.arw.?.tokenizer_json); + try prompt.checkTokenizer(&e.tok.?); + e.ar = try ar_.Ar.init(gpa, &e.driver, e.stream, e.k, &e.arw.?); + } + if (o.load_dit) e.ditw = try wts.loadDit(gpa, io, &e.store, model_dir, o.log); + if (o.load_dav) e.davw = try wts.loadDav(gpa, io, &e.store, model_dir); + try e.stream.synchronize(); + e.load_ms = ar_.ms(t0, ar_.nowNs(io)); + if (o.log) std.log.info("music3: weights on the device: {d:.2} GB, loaded in {d:.1} s", .{ @as(f64, @floatFromInt(e.store.bytes)) / 1e9, e.load_ms / 1000 }); + return e; + } + + fn quantize(ctx: *anyopaque, src: u64, n: usize, k: usize, group: usize, q: u64, sc: u64) anyerror!void { + const e: *Engine = @ptrCast(@alignCast(ctx)); + try e.k.quantRows(e.stream, src, n, k, group, q, sc); + try e.stream.synchronize(); + } + + pub fn destroy(e: *Engine) void { + if (e.ar) |*a| a.deinit(); + if (e.tok) |*t| t.deinit(); + if (e.arw) |a| e.gpa.free(a.tokenizer_json); + e.store.deinit(); + e.k.unload(); + e.gpa.destroy(e.k); + e.stream.deinit(); + e.ctx.deinit(); + e.driver.close(); + e.gpa.destroy(e); + } + + pub fn dit(e: *Engine) dit_.Dit { + return .{ .gpa = e.gpa, .k = e.k, .w = &e.ditw.?, .d = &e.driver, .s = e.stream, .o = e.o.dit }; + } + + pub fn dav(e: *Engine) dav_.Dav { + return .{ .gpa = e.gpa, .k = e.k, .w = &e.davw.?, .d = &e.driver, .s = e.stream, .o = .{ .tf32 = e.o.dav_tf32 } }; + } + + /// The conditional prompt's ids and the unconditional row (caller frees both). + pub fn ids(e: *Engine, caption: []const u8, lyrics: []const u8) !struct { cond: []u32, unc: []u32 } { + const c = try prompt.encode(e.gpa, &e.tok.?, caption, lyrics); + errdefer e.gpa.free(c); + return .{ .cond = c, .unc = try prompt.unconditional(e.gpa, c) }; + } + + /// Weight bytes a frame reads: body and lm_head once, the depth decoder 7 times, each head once. + pub fn frameBytes(e: *const Engine) f64 { + return common.frameBytes(&e.arw.?); + } + + /// Weight bytes on the device. + pub fn deviceBytes(e: *const Engine) usize { + return e.store.bytes; + } + + pub fn generate(e: *Engine, io: std.Io, caption: []const u8, lyrics: []const u8, s: cfg.Settings, progress: ?Progress) !Song { + _ = cuda.usage(true); + const t0 = ar_.nowNs(io); + const pr = try e.ids(caption, lyrics); + defer e.gpa.free(pr.cond); + defer e.gpa.free(pr.unc); + const smp: ar_.Sampling = .{ .ar_cfg = s.ar_cfg, .top_k = s.top_k, .seed = cfg.deriveSeed(s.seed, "ar") }; + const r = try e.ar.?.run(io, pr.cond, pr.unc, smp, s.frameLimit(), e.o.graphs, e.o.sync_every, null, null, progress); + defer e.gpa.free(r.states); + const t1 = ar_.nowNs(io); + var d = e.dit(); + const dp: ?dit_.Dit.Progress = if (progress) |p| .{ .ctx = p.ctx, .f = p.f } else null; + const latents = try d.denoise(r.states, r.frames, s.steps, s.dit_cfg, cfg.deriveSeed(s.seed, "dit"), null, null, dp); + defer e.gpa.free(latents); + const t2 = ar_.nowNs(io); + const L = cfg.framesToLatents(r.frames); + if (progress) |p| p.f(p.ctx, "dav", 0, 1); + var v = e.dav(); + const audio = try v.decode(latents, L); + const t3 = ar_.nowNs(io); + if (progress) |p| p.f(p.ctx, "dav", 1, 1); + const u = cuda.usage(false); + return .{ .audio = audio, .samples = L * 512, .frames = r.frames, .stopped = r.stopped, .prompt_tokens = r.prompt_tokens, .prefill_ms = r.prefill_ms, .ar_ms = ar_.ms(t0, t1), .frames_per_s = r.frames_per_s, .dit_ms = ar_.ms(t1, t2), .dav_ms = ar_.ms(t2, t3), .total_ms = ar_.ms(t0, t3), .latent_frames = L, .peak_device_gb = @as(f64, @floatFromInt(u.peak)) / 1e9 }; + } +}; diff --git a/zig/src/families/music3/generate.zig b/zig/src/families/music3/generate.zig new file mode 100644 index 00000000000..04f5804db78 --- /dev/null +++ b/zig/src/families/music3/generate.zig @@ -0,0 +1,294 @@ +//! music3-generate: MiniMax Music 3 songs on CUDA or Metal, --serve, parity dumps (MiniMax-Music3 License). +const std = @import("std"); +const core = @import("core"); +const m3 = @import("music3"); + +const cfg = m3.config; + +const usage = + \\usage: music3-generate --caption-file C [--lyrics-file L] --out song.wav [--seconds 60] [--seed 0] + \\ [--ar-cfg 1.5] [--top-k 50] [--steps 30] [--dit-cfg 1.7] [--stats stats.json] + \\ [--model DIR] [--weights int8|bf16] [--int8-group 128] [--comfy-rope 1] [--flash 1] [--dav-tf32 0] [--graphs 1] [--sync-every 16] + \\ music3-generate --serve 1 [--model DIR] [--weights int8|bf16] (one JSON request a line on stdin) + \\ music3-generate --ids --caption-file C --lyrics-file L (prompt ids as JSON, no GPU) + \\ music3-generate --parity-ar REF --out DIR --caption-file C --lyrics-file L [--frames N] + \\ music3-generate --parity-dit REF --out DIR [--steps 30 --dit-cfg 1.7] + \\ music3-generate --parity-probe REF --out DIR music3-generate --parity-dav REF --out DIR + \\ + \\--model (or $TF_MUSIC3_MODEL) is the folder holding Comfy-Org's three MiniMax-Music3 files; it is required. + \\--caption / --lyrics take the text itself. WAV out: 16-bit PCM stereo 44.1 kHz. + \\--flash, --dav-tf32 and --graphs choose CUDA kernels; the Metal build accepts and ignores them. + \\ +; + +const built_with = "[music3] MiniMax-Music3 runs locally under the MiniMax-Music3 Community License (show \"MiniMax-Music3\" in a commercial UI)."; + +const Args = struct { + model: []const u8 = "", + caption: ?[]const u8 = null, + lyrics: ?[]const u8 = null, + out: ?[]const u8 = null, + stats: ?[]const u8 = null, + s: cfg.Settings = .{}, + serve: bool = false, + ids: bool = false, + format: m3.weights.Format = .int8, + comfy_rope: bool = true, + flash: bool = true, + dav_tf32: bool = false, + depth_group: usize = 128, + graphs: bool = true, + sync_every: usize = 16, + parity_ar: ?[]const u8 = null, + parity_dit: ?[]const u8 = null, + parity_probe: ?[]const u8 = null, + parity_dav: ?[]const u8 = null, + frames: usize = 0, +}; + +var home: []const u8 = ""; + +fn expand(a: std.mem.Allocator, p: []const u8) ![]const u8 { + if (std.mem.startsWith(u8, p, "~/")) return std.mem.concat(a, u8, &.{ home, p[1..] }); + return p; +} + +fn readText(a: std.mem.Allocator, io: std.Io, path: []const u8) ![]const u8 { + return std.Io.Dir.cwd().readFileAlloc(io, try expand(a, path), a, .limited(16 << 20)); +} + +pub fn main(init: std.process.Init) !u8 { + const arena = init.arena.allocator(); + const gpa = std.heap.c_allocator; + const io = init.io; + home = init.environ_map.get("HOME") orelse ""; + const argv = try init.minimal.args.toSlice(arena); + var a: Args = .{}; + a.model = init.environ_map.get("TF_MUSIC3_MODEL") orelse ""; + var i: usize = 1; + while (i < argv.len) : (i += 1) { + const k = argv[i]; + if (std.mem.eql(u8, k, "--ids")) { + a.ids = true; + continue; + } + if (i + 1 >= argv.len) { + std.debug.print("{s}", .{usage}); + return 2; + } + const v = argv[i + 1]; + i += 1; + const eq = std.mem.eql; + if (eq(u8, k, "--model")) a.model = try expand(arena, v) else if (eq(u8, k, "--caption")) a.caption = v else if (eq(u8, k, "--caption-file")) a.caption = try readText(arena, io, v) else if (eq(u8, k, "--lyrics")) a.lyrics = v else if (eq(u8, k, "--lyrics-file")) a.lyrics = try readText(arena, io, v) else if (eq(u8, k, "--out")) a.out = try expand(arena, v) else if (eq(u8, k, "--stats")) a.stats = try expand(arena, v) else if (eq(u8, k, "--seconds")) a.s.seconds = try std.fmt.parseFloat(f64, v) else if (eq(u8, k, "--seed")) a.s.seed = try std.fmt.parseInt(u64, v, 10) else if (eq(u8, k, "--ar-cfg")) a.s.ar_cfg = try std.fmt.parseFloat(f32, v) else if (eq(u8, k, "--top-k")) a.s.top_k = try std.fmt.parseInt(i32, v, 10) else if (eq(u8, k, "--steps")) a.s.steps = try std.fmt.parseInt(usize, v, 10) else if (eq(u8, k, "--dit-cfg")) a.s.dit_cfg = try std.fmt.parseFloat(f32, v) else if (eq(u8, k, "--serve")) a.serve = !(eq(u8, v, "0") or eq(u8, v, "false") or eq(u8, v, "no")) else if (eq(u8, k, "--weights")) a.format = std.meta.stringToEnum(m3.weights.Format, v) orelse return error.BadWeights else if (eq(u8, k, "--comfy-rope")) a.comfy_rope = !eq(u8, v, "0") else if (eq(u8, k, "--int8-group")) a.depth_group = try std.fmt.parseInt(usize, v, 10) else if (eq(u8, k, "--dav-tf32")) a.dav_tf32 = !eq(u8, v, "0") else if (eq(u8, k, "--flash")) a.flash = !eq(u8, v, "0") else if (eq(u8, k, "--graphs")) a.graphs = !eq(u8, v, "0") else if (eq(u8, k, "--sync-every")) a.sync_every = try std.fmt.parseInt(usize, v, 10) else if (eq(u8, k, "--parity-ar")) a.parity_ar = try expand(arena, v) else if (eq(u8, k, "--parity-dit")) a.parity_dit = try expand(arena, v) else if (eq(u8, k, "--parity-probe")) a.parity_probe = try expand(arena, v) else if (eq(u8, k, "--parity-dav")) a.parity_dav = try expand(arena, v) else if (eq(u8, k, "--frames")) a.frames = try std.fmt.parseInt(usize, v, 10) else { + std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); + return 2; + } + } + if (a.model.len == 0) { + std.debug.print("pass --model DIR or set TF_MUSIC3_MODEL\n{s}", .{usage}); + return 2; + } + if (a.ids) return idsOnly(gpa, io, a); + const parity = a.parity_ar != null or a.parity_dit != null or a.parity_probe != null or a.parity_dav != null; + if (!a.serve and !parity and (a.caption == null or a.out == null)) { + std.debug.print("{s}", .{usage}); + return 2; + } + var opts: m3.Options = .{ .format = a.format, .graphs = a.graphs, .sync_every = a.sync_every, .dit = .{ .comfy_rope = a.comfy_rope, .flash = a.flash }, .dav_tf32 = a.dav_tf32, .depth_group = a.depth_group }; + if (parity) { + opts.load_ar = a.parity_ar != null; + opts.load_dit = a.parity_dit != null or a.parity_probe != null; + opts.load_dav = a.parity_dav != null; + } + if (a.serve) return serve(gpa, io, a, opts); + std.debug.print("{s}\n", .{built_with}); + const e = try m3.Engine.create(gpa, io, a.model, opts); + defer e.destroy(); + if (parity) return m3.parity.run(gpa, io, e, .{ .ar = a.parity_ar, .dit = a.parity_dit, .probe = a.parity_probe, .dav = a.parity_dav, .out = a.out orelse return error.OutRequired, .caption = a.caption orelse "", .lyrics = a.lyrics orelse "", .frames = a.frames, .steps = a.s.steps, .dit_cfg = a.s.dit_cfg }); + var pc: PrintProgress = .{ .io = io }; + const song = try e.generate(io, a.caption.?, a.lyrics orelse "", a.s, .{ .ctx = &pc, .f = PrintProgress.f }); + defer gpa.free(song.audio); + try writeWav(gpa, io, a.out.?, song.audio); + const stats = try statsJson(gpa, e, song, a.s, null); + defer gpa.free(stats); + if (a.stats) |p| try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = stats }); + std.debug.print("[music3] wrote {s}: {d:.1}s ({d} frames, {s}); AR {d:.1}s ({d:.2} frames/s), DiT {d:.1}s, DAV {d:.1}s, total {d:.1}s, RTF {d:.3}; device peak {d:.2} GB\n", .{ a.out.?, audioS(song), song.frames, if (song.stopped) "model ended it" else "hit the cap", song.ar_ms / 1000, song.frames_per_s, song.dit_ms / 1000, song.dav_ms / 1000, song.total_ms / 1000, song.total_ms / 1000 / @max(audioS(song), 1e-9), song.peak_device_gb }); + std.debug.print("RESULT music3 OK {s}\n", .{stats}); + return 0; +} + +fn audioS(song: m3.Song) f64 { + return @as(f64, @floatFromInt(song.samples)) / 44100.0; +} + +const PrintProgress = struct { + io: std.Io, + last: i128 = 0, + fn f(ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void { + const p: *PrintProgress = @ptrCast(@alignCast(ctx)); + const now = m3.common.nowNs(p.io); + if (done != total and now - p.last < 2_000_000_000) return; + p.last = now; + std.debug.print("[music3] {s} {d}/{d}\n", .{ stage, done, total }); + } +}; + +fn writeWav(gpa: std.mem.Allocator, io: std.Io, path: []const u8, audio: []const f32) !void { + const bytes = try m3.wav.encode(gpa, audio, 2, 44100); + defer gpa.free(bytes); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }); +} + +fn statsJson(gpa: std.mem.Allocator, e: *m3.Engine, song: m3.Song, s: cfg.Settings, extra: ?[]const u8) ![]u8 { + const aus = audioS(song); + const gbs = e.frameBytes() * song.frames_per_s / 1e9; + return std.fmt.allocPrint(gpa, "{{\"engine\":\"tensorfold-music3-" ++ m3.backend ++ "\",\"weights\":\"{s}\",\"prompt_tokens\":{d},\"frames\":{d},\"stopped\":{},\"prefill_s\":{d:.3},\"ar_s\":{d:.3},\"frames_per_s\":{d:.2},\"ar_weight_gb_per_frame\":{d:.2},\"ar_achieved_gb_s\":{d:.1},\"dit_s\":{d:.3},\"dav_s\":{d:.3},\"total_s\":{d:.3},\"audio_s\":{d:.3},\"rtf\":{d:.3},\"latent_frames\":{d},\"steps\":{d},\"seed\":{d},\"load_s\":{d:.2},\"peak_memory_gb\":{d:.2}{s}}}", .{ @tagName(e.o.format), song.prompt_tokens, song.frames, song.stopped, song.prefill_ms / 1000, song.ar_ms / 1000, song.frames_per_s, e.frameBytes() / 1e9, gbs, song.dit_ms / 1000, song.dav_ms / 1000, song.total_ms / 1000, aus, song.total_ms / 1000 / @max(aus, 1e-9), song.latent_frames, s.steps, s.seed, e.load_ms / 1000, song.peak_device_gb, extra orelse "" }); +} + +fn idsOnly(gpa: std.mem.Allocator, io: std.Io, a: Args) !u8 { + const path = try std.fs.path.join(gpa, &.{ a.model, m3.weights.text_encoder }); + defer gpa.free(path); + var f = try core.safetensors.File.open(gpa, io, path); + defer f.close(io); + const tj = f.get("tokenizer_json") orelse return error.NoTokenizer; + var tok = try core.tokenizer.parse(gpa, tj.bytes); + defer tok.deinit(); + try m3.prompt.checkTokenizer(&tok); + const ids = try m3.prompt.encode(gpa, &tok, a.caption orelse "", a.lyrics orelse ""); + defer gpa.free(ids); + const js = try std.json.Stringify.valueAlloc(gpa, .{ .ids = ids }, .{}); + defer gpa.free(js); + std.debug.print("{s}\n", .{js}); + return 0; +} + +// ---------------------------------------------------------------------------------------------- --serve + +extern "c" fn getline(line: *?[*]u8, n: *usize, f: *anyopaque) isize; +extern "c" fn fdopen(fd: c_int, mode: [*:0]const u8) ?*anyopaque; +extern "c" fn free(p: ?*anyopaque) void; + +/// One protocol line on stderr (log lines never start with '{'). +fn answer(text: []const u8) void { + std.debug.print("{s}\n", .{text}); +} + +const ServeProgress = struct { + io: std.Io, + id: []const u8, // the request's id as JSON + on: bool, + last: [3]i128 = @splat(0), + fn f(ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void { + const p: *ServeProgress = @ptrCast(@alignCast(ctx)); + if (!p.on) return; + const si: usize = if (std.mem.eql(u8, stage, "ar")) 0 else if (std.mem.eql(u8, stage, "dit")) 1 else 2; + const now = m3.common.nowNs(p.io); + if (done != total and now - p.last[si] < 1_000_000_000) return; + p.last[si] = now; + std.debug.print("{{\"id\":{s},\"progress\":{{\"stage\":\"{s}\",\"done\":{d},\"total\":{d}}}}}\n", .{ p.id, stage, done, total }); + } +}; + +fn serve(gpa: std.mem.Allocator, io: std.Io, a: Args, opts: m3.Options) !u8 { + std.debug.print("{s}\n", .{built_with}); + const t0 = m3.common.nowNs(io); + const e = m3.Engine.create(gpa, io, a.model, opts) catch |er| { + var buf: [256]u8 = undefined; + answer(std.fmt.bufPrint(&buf, "{{\"ok\":false,\"error\":\"load failed: {s}\"}}", .{@errorName(er)}) catch "{\"ok\":false,\"error\":\"load failed\"}"); + return 1; + }; + defer e.destroy(); + const load_s = m3.common.ms(t0, m3.common.nowNs(io)) / 1000; + std.debug.print("[music3] serving {s}: loaded in {d:.1}s; weights on the device: {d:.1} GB ({s})\n", .{ a.model, load_s, @as(f64, @floatFromInt(e.deviceBytes())) / 1e9, @tagName(opts.format) }); + { + var buf: [256]u8 = undefined; + answer(try std.fmt.bufPrint(&buf, "{{\"ready\":true,\"engine\":\"tensorfold-music3-" ++ m3.backend ++ "\",\"load_s\":{d:.2},\"sample_rate\":44100,\"channels\":2,\"license_display\":\"MiniMax-Music3\",\"weights\":\"{s}\"}}", .{ load_s, @tagName(opts.format) })); + } + const in = fdopen(0, "r") orelse return error.Stdin; + var line: ?[*]u8 = null; + var cap: usize = 0; + defer free(line); + while (true) { + const n = getline(&line, &cap, in); + if (n <= 0) break; + const text = std.mem.trim(u8, line.?[0..@intCast(n)], " \t\r\n"); + if (text.len == 0) continue; + var parsed = std.json.parseFromSlice(std.json.Value, gpa, text, .{}) catch { + answer("{\"ok\":false,\"error\":\"bad json\"}"); + continue; + }; + defer parsed.deinit(); + if (parsed.value != .object) { + answer("{\"ok\":false,\"error\":\"bad json\"}"); + continue; + } + var ra = std.heap.ArenaAllocator.init(gpa); + defer ra.deinit(); + const ar = ra.allocator(); + const o = parsed.value.object; + const id_json = try std.json.Stringify.valueAlloc(ar, o.get("id") orelse std.json.Value.null, .{}); + const reply = serveOne(gpa, ar, io, e, a, o, id_json) catch |er| blk: { + const msg = try std.json.Stringify.valueAlloc(ar, @errorName(er), .{}); + break :blk try std.fmt.allocPrint(ar, "{{\"ok\":false,\"error\":{s},\"id\":{s}}}", .{ msg, id_json }); + }; + answer(reply); + } + return 0; +} + +fn str(o: std.json.ObjectMap, k: []const u8) ?[]const u8 { + const v = o.get(k) orelse return null; + return if (v == .string) v.string else null; +} + +fn num(o: std.json.ObjectMap, k: []const u8) ?f64 { + const v = o.get(k) orelse return null; + return switch (v) { + .float => |x| x, + .integer => |x| @floatFromInt(x), + .number_string => |x| std.fmt.parseFloat(f64, x) catch null, + else => null, + }; +} + +fn flag(o: std.json.ObjectMap, k: []const u8) bool { + const v = o.get(k) orelse return false; + return switch (v) { + .bool => |b| b, + .integer => |x| x != 0, + else => false, + }; +} + +fn serveOne(gpa: std.mem.Allocator, ar: std.mem.Allocator, io: std.Io, e: *m3.Engine, a: Args, o: std.json.ObjectMap, id_json: []const u8) ![]u8 { + const caption = str(o, "caption") orelse return error.RequestNeedsCaption; + if (std.mem.trim(u8, caption, " \t\r\n").len == 0) return error.RequestNeedsCaption; + var lyrics: []const u8 = str(o, "lyrics") orelse ""; + if (o.get("lyrics") == null or o.get("lyrics").? == .null) { + if (str(o, "lyrics_file")) |p| lyrics = try readText(ar, io, p); + } + const wav = str(o, "wav") orelse return error.RequestNeedsWav; + var s = a.s; + if (num(o, "seconds")) |x| s.seconds = x; + if (num(o, "seed")) |x| s.seed = @intFromFloat(@max(0, x)); + if (num(o, "ar_cfg")) |x| s.ar_cfg = @floatCast(x); + if (num(o, "top_k")) |x| s.top_k = @intFromFloat(x); + if (num(o, "steps")) |x| s.steps = @intFromFloat(@max(1, x)); + if (num(o, "dit_cfg")) |x| s.dit_cfg = @floatCast(x); + std.debug.print("[music3] request {s}: {d:.0}s cap, seed {d}\n", .{ id_json, s.seconds, s.seed }); + var pc: ServeProgress = .{ .io = io, .id = id_json, .on = flag(o, "progress") }; + const song = try e.generate(io, caption, lyrics, s, .{ .ctx = &pc, .f = ServeProgress.f }); + defer gpa.free(song.audio); + const path = try expand(ar, wav); + if (std.fs.path.dirname(path)) |dir| std.Io.Dir.cwd().createDirPath(io, dir) catch {}; + try writeWav(gpa, io, path, song.audio); + const aus = audioS(song); + const wav_json = try std.json.Stringify.valueAlloc(ar, wav, .{}); + const reply = try std.fmt.allocPrint(ar, "{{\"ok\":true,\"id\":{s},\"wav\":{s},\"audio_s\":{d:.3},\"frames\":{d},\"eos\":{},\"ar_ms\":{d:.1},\"dit_ms\":{d:.1},\"dav_ms\":{d:.1},\"total_ms\":{d:.1},\"rtf\":{d:.3},\"first_audio_ms\":{d:.1},\"stream\":false,\"seed\":{d},\"peak_memory_gb\":{d:.2}}}", .{ id_json, wav_json, aus, song.frames, song.stopped, song.ar_ms, song.dit_ms, song.dav_ms, song.total_ms, song.total_ms / 1000 / @max(aus, 1e-9), song.total_ms, s.seed, song.peak_device_gb }); + if (str(o, "stats")) |sp| { + const st = try statsJson(gpa, e, song, s, try std.fmt.allocPrint(ar, ",\"reply\":{s}", .{reply})); + defer gpa.free(st); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try expand(ar, sp), .data = st }); + } + return reply; +} diff --git a/zig/src/families/music3/kernels.zig b/zig/src/families/music3/kernels.zig new file mode 100644 index 00000000000..fbfe817c461 --- /dev/null +++ b/zig/src/families/music3/kernels.zig @@ -0,0 +1,379 @@ +//! MiniMax Music 3's launches: music3.cu by symbol, and the cuBLAS / cuBLASLt products beside them. +const std = @import("std"); +const cuda = @import("cuda"); +const blas = @import("blas.zig"); +const lt = @import("lt.zig"); +const wts = @import("weights.zig"); + +const names = .{ + "m3_embed", "m3_embed_code", "m3_frame_embed", "m3_rmsnorm", "m3_add", "m3_swiglu", + "m3_dequant", "m3_quant_rows", "m3_gemv_bf16_2", "m3_gemv_bf16_4", "m3_gemv_i8_2", "m3_gemv_i8_4", + "m3_qk_rope", "m3_attn_part", "m3_attn_merge", "m3_depth_kv", "m3_depth_attn", "m3_sample", + "m3_frame_done", "m3_state_part", "m3_force_codes", "m3_cond_mix", "m3_im2col3", "m3_dit_input", + "m3_add_h", "m3_time_features", "m3_silu_h", "m3_linear_h1", "m3_gather_rows_h", "m3_put_time", + "m3_layernorm_h", "m3_dit_rope", "m3_softmax_rows", "m3_heads_to_rows", "m3_glu_h", "m3_dit_gather", + "m3_euler", "m3_noise", "m3_snake", "m3_bias_rows", "m3_overlap_add", "m3_zero_rows", + "m3_tanh", "m3_add_bias", "m3_latent_half", "m3_flash_attn", "m3_glu_bf16_2", "m3_glu_bf16_4", + "m3_glu_i8_2", "m3_glu_i8_4", "m3_gemv_g8_2", "m3_gemv_g8_4", "m3_glu_g8_2", "m3_glu_g8_4", + "m3_quant_groups", "m3_bias_h", +}; + +pub const F = enum(u8) { + embed, + embed_code, + frame_embed, + rmsnorm, + add, + swiglu, + dequant, + quant_rows, + gemv_bf16_2, + gemv_bf16_4, + gemv_i8_2, + gemv_i8_4, + qk_rope, + attn_part, + attn_merge, + depth_kv, + depth_attn, + sample, + frame_done, + state_part, + force_codes, + cond_mix, + im2col3, + dit_input, + add_h, + time_features, + silu_h, + linear_h1, + gather_rows_h, + put_time, + layernorm_h, + dit_rope, + softmax_rows, + heads_to_rows, + glu_h, + dit_gather, + euler, + noise, + snake, + bias_rows, + overlap_add, + zero_rows, + tanh, + add_bias, + latent_half, + flash_attn, + glu_bf16_2, + glu_bf16_4, + glu_i8_2, + glu_i8_4, + gemv_g8_2, + gemv_g8_4, + glu_g8_2, + glu_g8_4, + quant_groups, + bias_h, +}; + +comptime { + std.debug.assert(names.len == @typeInfo(F).@"enum".field_names.len); +} + +const n_fns = names.len; + +pub const Kernels = struct { + d: *const cuda.Driver, + mod: cuda.Module, + fns: [n_fns]cuda.Function, + blas: blas.Blas, + ws: cuda.DeviceBuffer, + lt: lt.Plans, + sms: usize, + pdl: bool = false, // GEMVs with programmatic dependent launch (sm_90 up) + + pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ctx: *const cuda.Context) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = undefined; + k.d = d; + k.sms = @intCast(try ctx.attribute(.multiprocessor_count)); + k.pdl = try ctx.capability() >= 90; + k.mod = try cuda.Module.load(d, cuda.kernels.music3); + inline for (names, 0..) |name, j| k.fns[j] = try k.mod.function(name); + const ws_bytes: usize = 64 << 20; + k.ws = try cuda.DeviceBuffer.alloc(d, ws_bytes); + k.blas = try blas.Blas.open(k.ws.ptr, ws_bytes); + k.lt = try lt.Plans.open(gpa, d, 64 << 20); + return k; + } + + pub fn unload(k: *Kernels) void { + k.lt.close(); + k.blas.close(); + k.ws.free(); + k.mod.unload(); + } + + pub fn f(k: *const Kernels, which: F) cuda.Function { + return k.fns[@backingInt(which)]; + } + + pub fn go(k: *const Kernels, which: F, s: cuda.Stream, grid: [3]usize, block: usize, a: *cuda.Args) !void { + try cuda.launch.launch(k.f(which), .{ .grid = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }, .block = .{ .x = @intCast(block) } }, s, a); + } + + /// A grid-stride elementwise launch over n items. + pub fn flat(k: *const Kernels, which: F, s: cuda.Stream, n: usize, a: *cuda.Args) !void { + const blocks = @max(1, @min((n + 255) / 256, k.sms * 32)); + try k.go(which, s, .{ blocks, 1, 1 }, 256, a); + } + + fn i(x: usize) i32 { + return @intCast(x); + } + + // -------------------------------------------------------------------------------------------- AR + + pub fn embed(k: *const Kernels, s: cuda.Stream, ids: u64, table: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(ids); + a.add(table); + a.add(out); + a.add(i(4096)); + try k.go(.embed, s, .{ rows, 1, 1 }, 256, &a); + } + + pub fn embedCode(k: *const Kernels, s: cuda.Stream, code: u64, offset: usize, table: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(code); + a.add(i(offset)); + a.add(table); + a.add(out); + a.add(i(rows)); + a.add(i(4096)); + try k.go(.embed_code, s, .{ 1, 1, 1 }, 512, &a); + } + + pub fn frameEmbed(k: *const Kernels, s: cuda.Stream, codes: u64, audio: u64, extra: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(codes); + a.add(audio); + a.add(extra); + a.add(out); + a.add(i(rows)); + a.add(i(4096)); + a.add(@as(f32, @floatCast(1.0 / @sqrt(8.0)))); + try k.go(.frame_embed, s, .{ 16, 1, 1 }, 256, &a); + } + + pub fn rmsnorm(k: *const Kernels, s: cuda.Stream, x: u64, xs: usize, w: u64, y: u64, ys: usize, rows: usize, eps: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(i(xs)); + a.add(w); + a.add(y); + a.add(i(ys)); + a.add(i(4096)); + a.add(eps); + try k.go(.rmsnorm, s, .{ rows, 1, 1 }, 512, &a); + } + + pub fn add(k: *const Kernels, s: cuda.Stream, x: u64, b: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(b); + a.add(n); + try k.flat(.add, s, n, &a); + } + + pub fn swiglu(k: *const Kernels, s: cuda.Stream, gu: u64, y: u64, width: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(gu); + a.add(y); + a.add(i(width)); + a.add(rows); + try k.flat(.swiglu, s, rows * width, &a); + } + + pub fn dequant(k: *const Kernels, s: cuda.Stream, m: wts.Mat, out: u64) !void { + var a: cuda.Args = .{}; + a.add(m.w); + a.add(m.sc); + a.add(out); + a.add(i(m.k)); + a.add(m.n); + try k.flat(.dequant, s, m.n * m.k, &a); + } + + /// bf16 rows to int8 with a scale a row (group 0) or a scale a group of 128 inputs. + pub fn quantRows(k: *const Kernels, s: cuda.Stream, src: u64, n: usize, kk: usize, group: usize, q: u64, sc: u64) !void { + if (group != 0 and group != 128) return error.UnsupportedGroup; + var a: cuda.Args = .{}; + a.add(src); + a.add(i(kk)); + a.add(q); + a.add(sc); + try k.go(if (group == 0) .quant_rows else .quant_groups, s, .{ n, 1, 1 }, 256, &a); + } + + pub const Gemv = struct { + xs: usize = 0, // x row stride (0: K) + glu: bool = false, // gate | up rows: write the SwiGLU of rows n and N / 2 + n at n + y: u64 = 0, + ys: usize = 0, // 0: N (N / 2 with glu) + yf: u64 = 0, + res: u64 = 0, + res_div: usize = 1, + }; + + /// y[m] = W x[m] for m < rows (2 or 4): bf16 or int8 weights by the Mat. + pub fn gemv(k: *const Kernels, s: cuda.Stream, w: wts.Mat, x: u64, rows: usize, o: Gemv) !void { + std.debug.assert(rows == 2 or rows == 4); + const int8 = w.sc != 0; + const four = rows == 4; + const which: F = if (w.group != 0) (if (o.glu) (if (four) F.glu_g8_4 else F.glu_g8_2) else (if (four) F.gemv_g8_4 else F.gemv_g8_2)) else if (o.glu) + (if (int8) (if (four) F.glu_i8_4 else F.glu_i8_2) else (if (four) F.glu_bf16_4 else F.glu_bf16_2)) + else + (if (int8) (if (four) F.gemv_i8_4 else F.gemv_i8_2) else (if (four) F.gemv_bf16_4 else F.gemv_bf16_2)); + std.debug.assert(w.group == 0 or w.group == 128); + const outs = if (o.glu) w.n / 2 else w.n; + var a: cuda.Args = .{}; + a.add(w.w); + a.add(w.sc); + a.add(x); + a.add(i(if (o.xs != 0) o.xs else w.k)); + a.add(i(w.k)); + a.add(i(w.n)); + a.add(o.y); + a.add(i(if (o.ys != 0) o.ys else outs)); + a.add(o.yf); + a.add(o.res); + a.add(i(o.res_div)); + try cuda.launch.launch(k.f(which), .{ .grid = .{ .x = @intCast((outs + 7) / 8) }, .block = .{ .x = 256 }, .pdl = k.pdl }, s, &a); + } + + /// Prompt rows through cuBLAS: y [t, N] = x [t, K] W^T (bf16, fp32 compute); int8 weights dequantized to `tmp`. + pub fn linearRows(k: *const Kernels, s: cuda.Stream, w: wts.Mat, x: u64, y: u64, t: usize, tmp: u64) !void { + var wp = w.w; + if (w.sc != 0) { + try k.dequant(s, w, tmp); + wp = tmp; + } + try k.blas.gemm(s, .t, .n, w.n, t, w.k, 1.0, wp, w.k, 0, x, w.k, 0, 0.0, y, w.n, 0, 1, .bf16, .bf16); + } + + pub fn qkRope(k: *const Kernels, s: cuda.Stream, qkv: u64, qn: u64, kn: u64, inv_freq: u64, pos: u64, t: usize, rows: usize, q: u64, kc: u64, vc: u64, ctx: usize) !void { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(qn); + a.add(kn); + a.add(inv_freq); + a.add(pos); + a.add(i(t)); + a.add(q); + a.add(kc); + a.add(vc); + a.add(i(ctx)); + a.add(@as(f32, 1e-6)); + try k.go(.qk_rope, s, .{ rows, 48, 1 }, 128, &a); + } + + pub fn attention(k: *const Kernels, s: cuda.Stream, q: u64, kc: u64, vc: u64, pos: u64, t: usize, rows: usize, ctx: usize, splits: usize, ml: u64, acc: u64, out: u64) !void { + var a: cuda.Args = .{}; + a.add(q); + a.add(kc); + a.add(vc); + a.add(pos); + a.add(i(t)); + a.add(i(ctx)); + a.add(i(splits)); + a.add(@as(f32, 1.0 / @sqrt(128.0))); + a.add(ml); + a.add(acc); + try k.go(.attn_part, s, .{ 8, rows, splits }, 128, &a); + var b: cuda.Args = .{}; + b.add(ml); + b.add(acc); + b.add(i(splits)); + b.add(out); + try k.go(.attn_merge, s, .{ rows, 32, 1 }, 128, &b); + } + + pub fn depthAttention(k: *const Kernels, s: cuda.Stream, qkv: u64, p0: usize, rows: usize, kc: u64, vc: u64, out: u64) !void { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(i(p0)); + a.add(i(2)); + a.add(kc); + a.add(vc); + try k.go(.depth_kv, s, .{ rows, 16, 1 }, 256, &a); + var b: cuda.Args = .{}; + b.add(qkv); + b.add(i(p0)); + b.add(i(2)); + b.add(kc); + b.add(vc); + b.add(@as(f32, 1.0 / 16.0)); + b.add(out); + try k.go(.depth_attn, s, .{ rows, 16, 1 }, 256, &b); + } + + pub const Draw = struct { cfg: f32, top_k: i32, seed: u64, step: u64, slot: i32, pick: u64, code: u64 = 0, tokens: u64 = 0, count: u64 = 0, force: u64 = 0 }; + + pub fn sample(k: *const Kernels, s: cuda.Stream, logits: u64, v: usize, rank_cond: bool, d: Draw) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(i(v)); + a.add(d.cfg); + a.add(d.top_k); + a.add(@as(i32, @intFromBool(rank_cond))); + a.add(d.seed); + a.add(d.step); + a.add(d.slot); + a.add(d.pick); + a.add(d.code); + a.add(d.tokens); + a.add(d.count); + a.add(d.force); + try k.go(.sample, s, .{ 1, 1, 1 }, 1024, &a); + } + + pub fn frameDone(k: *const Kernels, s: cuda.Stream, pos: u64, step: u64, count: u64) !void { + var a: cuda.Args = .{}; + a.add(pos); + a.add(step); + a.add(count); + try k.go(.frame_done, s, .{ 1, 1, 1 }, 32, &a); + } + + pub fn statePart(k: *const Kernels, s: cuda.Stream, src: u64, states: u64, count: u64, part: usize) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(states); + a.add(count); + a.add(i(part)); + try k.go(.state_part, s, .{ 1, 1, 1 }, 256, &a); + } + + pub fn forceCodes(k: *const Kernels, s: cuda.Stream, forced: u64, count: u64, codes: u64, token: u64) !void { + var a: cuda.Args = .{}; + a.add(forced); + a.add(count); + a.add(codes); + a.add(token); + try k.go(.force_codes, s, .{ 1, 1, 1 }, 32, &a); + } + + // -------------------------------------------------------------------------------------------- DiT + + pub fn hgemm(k: *const Kernels, s: cuda.Stream, ta: blas.Op, tb: blas.Op, m: usize, n: usize, kk: usize, alpha: f32, a_: u64, lda: usize, sa: usize, b_: u64, ldb: usize, sb: usize, beta: f32, c: u64, ldc: usize, sc: usize, batch: usize, out_t: blas.DataType) !void { + try k.blas.gemm(s, ta, tb, m, n, kk, alpha, a_, lda, sa, b_, ldb, sb, beta, c, ldc, sc, batch, .f16, out_t); + } + + pub fn args(comptime T: type, vals: T) cuda.Args { + var a: cuda.Args = .{}; + inline for (std.meta.fields(T)) |fd| a.add(@field(vals, fd.name)); + return a; + } +}; diff --git a/zig/src/families/music3/lt.zig b/zig/src/families/music3/lt.zig new file mode 100644 index 00000000000..3f56c451f83 --- /dev/null +++ b/zig/src/families/music3/lt.zig @@ -0,0 +1,163 @@ +//! The DiT's fp16 projections on the runtime's cuBLASLt: D = X W^T (+ bias) (+ D), fp32 compute, a tuned plan a shape. +const std = @import("std"); +const cuda = @import("cuda"); + +const lt_ = cuda.cublaslt; +const Ptr = cuda.abi.DevicePtr; + +pub const Plan = struct { + lib: *const lt_.Library, + handle: lt_.Handle, + desc: lt_.MatmulDesc, + a: lt_.Layout, + b: lt_.Layout, + c: lt_.Layout, + algo: lt_.Algo, + ws_need: usize, + bias: bool, + beta: f32, + m: u64, + n: u64, + k: u64, + found: [max_algos]lt_.Heuristic = undefined, + n_found: usize = 0, + tuned: bool = false, + + /// m rows of X, n outputs, k inputs; `bias` adds a fp16 bias over the outputs; `accumulate` adds D's old values. + pub fn init(lib: *const lt_.Library, handle: lt_.Handle, m: u64, n: u64, k: u64, bias: bool, accumulate: bool, ws_limit: usize) !Plan { + var p: Plan = undefined; + p.lib = lib; + p.handle = handle; + p.bias = bias; + p.beta = if (accumulate) 1 else 0; + p.m = m; + p.n = n; + p.k = k; + const api = lib.api; + try lib.check(api.cublasLtMatmulDescCreate(&p.desc, lt_.compute_32f, .f32), "cublasLtMatmulDescCreate"); + errdefer _ = api.cublasLtMatmulDescDestroy(p.desc); + const ta: c_int = @backingInt(lt_.Op.t); + const tb: c_int = @backingInt(lt_.Op.n); + try lib.check(api.cublasLtMatmulDescSetAttribute(p.desc, lt_.desc_transa, &ta, @sizeOf(c_int)), "transa"); + try lib.check(api.cublasLtMatmulDescSetAttribute(p.desc, lt_.desc_transb, &tb, @sizeOf(c_int)), "transb"); + if (bias) { + const e: u32 = @backingInt(lt_.Epilogue.bias); + try lib.check(api.cublasLtMatmulDescSetAttribute(p.desc, lt_.desc_epilogue, &e, @sizeOf(u32)), "epilogue"); + const bt: c_int = @backingInt(lt_.DataType.f16); + try lib.check(api.cublasLtMatmulDescSetAttribute(p.desc, desc_bias_data_type, &bt, @sizeOf(c_int)), "bias type"); + } + try lib.check(api.cublasLtMatrixLayoutCreate(&p.a, .f16, k, n, @intCast(k)), "layout W"); + errdefer _ = api.cublasLtMatrixLayoutDestroy(p.a); + try lib.check(api.cublasLtMatrixLayoutCreate(&p.b, .f16, k, m, @intCast(k)), "layout X"); + errdefer _ = api.cublasLtMatrixLayoutDestroy(p.b); + try lib.check(api.cublasLtMatrixLayoutCreate(&p.c, .f16, n, m, @intCast(n)), "layout D"); + errdefer _ = api.cublasLtMatrixLayoutDestroy(p.c); + var pref: lt_.Preference = null; + try lib.check(api.cublasLtMatmulPreferenceCreate(&pref), "preference"); + defer _ = api.cublasLtMatmulPreferenceDestroy(pref); + const limit: u64 = ws_limit; + try lib.check(api.cublasLtMatmulPreferenceSetAttribute(pref, lt_.pref_max_workspace_bytes, &limit, @sizeOf(u64)), "workspace"); + var count: c_int = 0; + try lib.check(api.cublasLtMatmulAlgoGetHeuristic(handle, p.desc, p.a, p.b, p.c, p.c, pref, max_algos, &p.found, &count), "heuristic"); + if (count < 1 or p.found[0].state != 0) return error.NoAlgorithm; + p.n_found = @intCast(count); + p.algo = p.found[0].algo; + p.ws_need = p.found[0].workspace_size; + p.tuned = count == 1; + return p; + } + + /// Times the heuristic's candidates on this shape (D into `scratch`, the real output untouched), keeps the best. + pub fn tune(p: *Plan, d: *const cuda.Driver, s: cuda.Stream, x: Ptr, w: Ptr, bias: Ptr, scratch: Ptr, ws: Ptr, ws_len: usize) !void { + p.tuned = true; + var e0 = try cuda.Event.init(d, true); + defer e0.deinit(); + var e1 = try cuda.Event.init(d, true); + defer e1.deinit(); + var best: f32 = std.math.inf(f32); + var pick: usize = 0; + for (p.found[0..p.n_found], 0..) |hcand, idx| { + if (hcand.state != 0 or hcand.workspace_size > ws_len) continue; + p.algo = hcand.algo; + p.run(s, x, w, bias, scratch, ws, ws_len) catch continue; + try e0.record(s); + for (0..3) |_| try p.run(s, x, w, bias, scratch, ws, ws_len); + try e1.record(s); + try e1.synchronize(); + const t = try cuda.Event.elapsedMs(e0, e1); + if (t < best) { + best = t; + pick = idx; + } + } + p.algo = p.found[pick].algo; + p.ws_need = p.found[pick].workspace_size; + std.log.debug("music3: lt {d}x{d}x{d} bias {} acc {}: {d} candidates, best #{d} {d:.3} ms", .{ p.m, p.n, p.k, p.bias, p.beta != 0, p.n_found, pick, best / 3 }); + } + + pub fn deinit(p: *Plan) void { + const api = p.lib.api; + _ = api.cublasLtMatrixLayoutDestroy(p.c); + _ = api.cublasLtMatrixLayoutDestroy(p.b); + _ = api.cublasLtMatrixLayoutDestroy(p.a); + _ = api.cublasLtMatmulDescDestroy(p.desc); + } + + /// D = X W^T (+ bias) (+ D) on stream s. + pub fn run(p: *const Plan, s: cuda.Stream, x: Ptr, w: Ptr, bias: Ptr, d: Ptr, ws: Ptr, ws_len: usize) !void { + if (ws_len < p.ws_need) return error.WorkspaceTooSmall; + const api = p.lib.api; + if (p.bias) try p.lib.check(api.cublasLtMatmulDescSetAttribute(p.desc, lt_.desc_bias_pointer, &bias, @sizeOf(Ptr)), "bias"); + const one: f32 = 1; + try p.lib.check(api.cublasLtMatmul(p.handle, p.desc, &one, w, p.a, x, p.b, &p.beta, d, p.c, d, p.c, &p.algo, ws, ws_len, s.handle), "cublasLtMatmul"); + } +}; + +const max_algos = 32; + +/// CUBLASLT_MATMUL_DESC_BIAS_DATA_TYPE +const desc_bias_data_type: c_int = 26; + +/// Plans by shape, made on first use. +pub const Plans = struct { + gpa: std.mem.Allocator, + lib: lt_.Library, + handle: lt_.Handle, + list: std.ArrayList(Plan) = .empty, + ws: cuda.DeviceBuffer, + + pub fn open(gpa: std.mem.Allocator, d: *const cuda.Driver, ws_bytes: usize) !Plans { + var lib = try lt_.Library.open(); + errdefer lib.close(); + var h: lt_.Handle = null; + try lib.check(lib.api.cublasLtCreate(&h), "cublasLtCreate"); + return .{ .gpa = gpa, .lib = lib, .handle = h, .ws = try cuda.DeviceBuffer.alloc(d, ws_bytes) }; + } + + pub fn close(ps: *Plans) void { + for (ps.list.items) |*p| p.deinit(); + ps.list.deinit(ps.gpa); + _ = ps.lib.api.cublasLtDestroy(ps.handle); + ps.lib.close(); + ps.ws.free(); + } + + pub fn get(ps: *Plans, m: u64, n: u64, k: u64, bias: bool, accumulate: bool) !*Plan { + for (ps.list.items) |*p| if (p.m == m and p.n == n and p.k == k and p.bias == bias and (p.beta != 0) == accumulate) return p; + try ps.list.append(ps.gpa, try Plan.init(&ps.lib, ps.handle, m, n, k, bias, accumulate, ps.ws.len)); + return &ps.list.items[ps.list.items.len - 1]; + } + + /// D[m, n] = X W^T (+ bias when nonzero) (+ D when accumulate); a new shape is tuned first. + pub fn linear(ps: *Plans, s: cuda.Stream, x: Ptr, w: Ptr, bias: Ptr, d: Ptr, m: usize, n: usize, k: usize, accumulate: bool) !void { + const p = try ps.get(m, n, k, bias != 0, accumulate); + if (!p.tuned) { + var scratch = try cuda.DeviceBuffer.alloc(ps.ws.d, m * n * 2); + defer scratch.free(); + try s.synchronize(); + try p.tune(ps.ws.d, s, x, w, bias, scratch.ptr, ps.ws.ptr, ps.ws.len); + try s.synchronize(); + } + try p.run(s, x, w, bias, d, ps.ws.ptr, ps.ws.len); + } +}; diff --git a/zig/src/families/music3/metal/ar.zig b/zig/src/families/music3/metal/ar.zig new file mode 100644 index 00000000000..5867d1c336f --- /dev/null +++ b/zig/src/families/music3/metal/ar.zig @@ -0,0 +1,270 @@ +//! The AR stage on Metal: the prompt's CFG rows in tensor-unit GEMMs, then frames (code 0, 7 depth codes, states). +const std = @import("std"); +const cfg = @import("../config.zig"); +const wts = @import("../weights.zig"); +const common = @import("../common.zig"); +const gpu = @import("gpu.zig"); +const k = @import("kernels.zig"); + +const H = cfg.hidden; +const Gpu = gpu.Gpu; +const decode_splits = 16; + +pub const Sampling = common.Sampling; +pub const Trace = common.Trace; +pub const Result = common.Result; +pub const Progress = common.Progress; + +pub const Ar = struct { + gpa: std.mem.Allocator, + g: *Gpu, + w: *const wts.Ar, + ctx: usize = 0, + cache: u64 = 0, + kc: [cfg.layers]u64 = @splat(0), + vc: [cfg.layers]u64 = @splat(0), + // device scalars + pos: u64 = 0, + step: u64 = 0, + count: u64 = 0, + codes: u64 = 0, // i32 [8] + pick: u64 = 0, + tokens: u64 = 0, // i32 [max_frames + 2] + forced: u64 = 0, // i32 [max_frames + 2, 8] + states: u64 = 0, // bf16 [max_frames + 2, 8, 4096] + // frame scratch + x: u64 = 0, + xn: u64 = 0, + qkv: u64 = 0, + q: u64 = 0, + att: u64 = 0, + gu: u64 = 0, + ml: u64 = 0, + acc: u64 = 0, + last: u64 = 0, // [2, 4096] the body's normed last state + d_in: u64 = 0, // [4, 4096] + dx: u64 = 0, + dxn: u64 = 0, + dqkv: u64 = 0, + datt: u64 = 0, + dgu: u64 = 0, + dout: u64 = 0, + dkc: [cfg.depth_layers]u64 = @splat(0), + dvc: [cfg.depth_layers]u64 = @splat(0), + c0_logits: u64 = 0, // f32 [2, 16385] + code_logits: u64 = 0, // f32 [2, 1024] + + pub fn init(gpa: std.mem.Allocator, g: *Gpu, w: *const wts.Ar) !Ar { + var a: Ar = .{ .gpa = gpa, .g = g, .w = w }; + a.pos = try g.alloc(16); + a.step = try g.alloc(16); + a.count = try g.alloc(16); + a.codes = try g.alloc(64); + a.pick = try g.alloc(16); + a.tokens = try g.alloc((cfg.max_frames + 2) * 4); + a.forced = try g.alloc((cfg.max_frames + 2) * 8 * 4); + a.states = try g.alloc((cfg.max_frames + 2) * 8 * H * 2); + a.x = try g.alloc(2 * H * 2); + a.xn = try g.alloc(2 * H * 2); + a.qkv = try g.alloc(2 * cfg.qkv_width * 2); + a.q = try g.alloc(2 * H * 2); + a.att = try g.alloc(2 * H * 2); + a.gu = try g.alloc(2 * 2 * cfg.mlp * 2); + a.ml = try g.alloc(2 * 32 * decode_splits * 2 * 4); + a.acc = try g.alloc(2 * 32 * decode_splits * 128 * 4); + a.last = try g.alloc(2 * H * 2); + a.d_in = try g.alloc(4 * H * 2); + a.dx = try g.alloc(4 * H * 2); + a.dxn = try g.alloc(4 * H * 2); + a.dqkv = try g.alloc(4 * 3 * H * 2); + a.datt = try g.alloc(4 * H * 2); + a.dgu = try g.alloc(4 * 2 * cfg.depth_mlp * 2); + a.dout = try g.alloc(2 * H * 2); + for (0..cfg.depth_layers) |i| { + a.dkc[i] = try g.alloc(2 * 16 * 8 * 256 * 2); + a.dvc[i] = try g.alloc(2 * 16 * 8 * 256 * 2); + } + a.c0_logits = try g.alloc(2 * (cfg.c0_codes + 1) * 4); + a.code_logits = try g.alloc(2 * cfg.codebook_size * 4); + return a; + } + + fn setI32(a: *Ar, dst: u64, v: i32) !void { + try a.g.put(dst, std.mem.asBytes(&v)); + } + + /// KV caches for `need` positions (both rows, every layer). + pub fn ensureCache(a: *Ar, need: usize) !void { + if (a.ctx >= need) return; + try a.g.flush(); + if (a.cache != 0) a.g.free(a.cache); + const ctxn = (need + 255) / 256 * 256; + const per = 2 * cfg.kv_heads * ctxn * cfg.head_dim * 2; + a.cache = try a.g.alloc(per * 2 * cfg.layers); + for (0..cfg.layers) |i| { + a.kc[i] = a.cache + (2 * i) * per; + a.vc[i] = a.cache + (2 * i + 1) * per; + } + a.ctx = ctxn; + } + + /// The prompt rows (conditional ids, then the unconditional ones) through the body; leaves `last` and the caches. + pub fn prefill(a: *Ar, ids: []const u32, unc: []const u32) !void { + const n = ids.len; + const t = 2 * n; + const g = a.g; + const w = a.w; + var scratch: [11]u64 = @splat(0); + defer { + g.flush() catch {}; + for (scratch) |p| g.free(p); + } + const sizes = [_]usize{ t * 4, t * H * 2, t * H * 2, t * H * 2, t * cfg.qkv_width * 2, t * H * 2, t * 2 * cfg.mlp * 2, t * cfg.mlp * 2, t * 32 * 2 * 4, t * 32 * 128 * 4, if (w.format == .int8) 2 * cfg.mlp * H * 2 else 0 }; + for (&scratch, sizes) |*p, sz| p.* = if (sz > 0) try g.alloc(sz) else 0; + const ids_d, const x, const xn, const tmp, const qkv, const q, const gu, const act, const ml, const acc, const wtmp = scratch; + const all = std.mem.bytesAsSlice(i32, g.host(ids_d, t * 4)); + for (ids, 0..) |v, i| all[i] = @intCast(v); + for (unc, 0..) |v, i| all[n + i] = @intCast(v); + try a.setI32(a.pos, 0); + k.embed(g, ids_d, w.embed_prefill, x, t); + for (0..cfg.layers) |li| { + const L = &w.body[li]; + k.rmsnorm(g, x, H, L.in_norm, xn, H, t, cfg.eps); + k.linearRows(g, L.qkv, xn, qkv, t, wtmp); + k.qkRope(g, qkv, L.q_norm, L.k_norm, w.inv_freq, a.pos, n, t, q, a.kc[li], a.vc[li], a.ctx); + k.attention(g, q, a.kc[li], a.vc[li], a.pos, n, t, a.ctx, 1, ml, acc, xn); + k.linearRows(g, L.o, xn, tmp, t, wtmp); + k.add(g, x, tmp, t * H); + k.rmsnorm(g, x, H, L.post_norm, xn, H, t, cfg.eps); + k.linearRows(g, L.gate_up, xn, gu, t, wtmp); + k.swiglu(g, gu, act, cfg.mlp, t); + k.linearRows(g, L.down, act, tmp, t, wtmp); + k.add(g, x, tmp, t * H); + try g.commit(); + } + // the last row of each: the normed state code 0 is drawn from + k.rmsnorm(g, x + (n - 1) * H * 2, n * H, w.norm, a.last, H, 2, cfg.eps); + } + + pub fn depthPass(a: *Ar, rows: usize, p0: usize) void { + const g = a.g; + const w = a.w; + for (0..cfg.depth_layers) |li| { + const L = &w.depth[li]; + k.rmsnorm(g, a.dx, H, L.in_norm, a.dxn, H, rows, cfg.eps); + k.gemv(g, L.qkv, a.dxn, rows, .{ .y = a.dqkv }); + k.depthAttention(g, a.dqkv, p0, rows, a.dkc[li], a.dvc[li], a.datt); + k.gemv(g, L.o, a.datt, rows, .{ .y = a.dx, .res = a.dx }); + k.rmsnorm(g, a.dx, H, L.post_norm, a.dxn, H, rows, cfg.eps); + k.gemv(g, L.gate_up, a.dxn, rows, .{ .glu = true, .y = a.dgu }); + k.gemv(g, L.down, a.dgu, rows, .{ .y = a.dx, .res = a.dx }); + } + // the last position's two rows, normed + k.rmsnorm(g, a.dx + (rows - 2) * H * 2, H, w.depth_norm, a.dout, H, 2, cfg.eps); + } + + /// One frame: code 0, the 7 depth codes, the states, the frame fed back (`forced`: codes from the forced table). + fn enqueueFrame(a: *Ar, smp: Sampling, forced: bool, trace: ?*Trace) !void { + const g = a.g; + const w = a.w; + k.gemv(g, w.lm_head, a.last, 2, .{ .yf = a.c0_logits }); + if (trace) |tr| try a.pull(&tr.c0, a.c0_logits, 2 * (cfg.c0_codes + 1)); + if (forced) { + k.forceCodes(g, a.forced, a.count, a.codes, a.tokens); + } else { + k.sample(g, a.c0_logits, cfg.c0_codes + 1, true, .{ .cfg = smp.ar_cfg, .top_k = smp.top_k, .seed = smp.seed, .step = a.step, .slot = 0, .pick = a.pick, .code = a.codes, .tokens = a.tokens, .count = a.count }); + } + k.statePart(g, a.last, a.states, a.count, 0); + // depth pass 0: [hidden, code-0 embedding] at positions 0 and 1, both rows + g.copy(a.last, a.d_in, 2 * H * 2); + k.embedCode(g, a.codes, 0, w.embed_audio, a.d_in + 2 * H * 2, 2); + k.gemv(g, w.projection, a.d_in, 4, .{ .y = a.dx, .res = w.pos_emb, .res_div = 2 }); + a.depthPass(4, 0); + for (1..cfg.codebooks) |ci| { + if (ci > 1) { + // the code drawn last, embedded, at position ci + k.embedCode(g, a.codes + (ci - 1) * 4, (ci - 2) * cfg.codebook_size, w.extra, a.d_in, 2); + k.gemv(g, w.projection, a.d_in, 2, .{ .y = a.dx, .res = w.pos_emb + ci * H * 2, .res_div = 2 }); + a.depthPass(2, ci); + } + k.statePart(g, a.dout, a.states, a.count, ci); + k.gemv(g, w.heads[ci - 1], a.dout, 2, .{ .yf = a.code_logits }); + if (trace) |tr| try a.pull(&tr.depth, a.code_logits, 2 * cfg.codebook_size); + if (!forced) k.sample(g, a.code_logits, cfg.codebook_size, false, .{ .cfg = smp.ar_cfg, .top_k = smp.top_k, .seed = smp.seed, .step = a.step, .slot = @intCast(ci), .pick = a.codes + ci * 4 }); + } + a.bodyRow(); + try g.commit(); + } + + /// The frame fed back: one body row a CFG row at pos, then the normed state the next code 0 is drawn from. + pub fn bodyRow(a: *Ar) void { + const g = a.g; + const w = a.w; + k.frameEmbed(g, a.codes, w.embed_audio, w.extra, a.x, 2); + for (0..cfg.layers) |li| { + const L = &w.body[li]; + k.rmsnorm(g, a.x, H, L.in_norm, a.xn, H, 2, cfg.eps); + k.gemv(g, L.qkv, a.xn, 2, .{ .y = a.qkv }); + k.qkRope(g, a.qkv, L.q_norm, L.k_norm, w.inv_freq, a.pos, 1, 2, a.q, a.kc[li], a.vc[li], a.ctx); + k.attention(g, a.q, a.kc[li], a.vc[li], a.pos, 1, 2, a.ctx, decode_splits, a.ml, a.acc, a.att); + k.gemv(g, L.o, a.att, 2, .{ .y = a.x, .res = a.x }); + k.rmsnorm(g, a.x, H, L.post_norm, a.xn, H, 2, cfg.eps); + k.gemv(g, L.gate_up, a.xn, 2, .{ .glu = true, .y = a.gu }); + k.gemv(g, L.down, a.gu, 2, .{ .y = a.x, .res = a.x }); + } + k.rmsnorm(g, a.x, H, w.norm, a.last, H, 2, cfg.eps); + k.frameDone(g, a.pos, a.step, a.count); + } + + fn pull(a: *Ar, list: *std.ArrayList(f32), src: u64, n: usize) !void { + const at = list.items.len; + try list.resize(a.gpa, at + n); + try a.g.get(src, std.mem.sliceAsBytes(list.items[at..])); + } + + /// Prompt, then frames to the stop code or `limit` kept; `forced_codes` replaces draws; `graphs` is CUDA's. + pub fn run(a: *Ar, io: std.Io, ids: []const u32, unc: []const u32, smp: Sampling, limit: usize, graphs: bool, sync_every: usize, forced_codes: ?[]const [8]i32, trace: ?*Trace, progress: ?Progress) !Result { + _ = graphs; + const g = a.g; + const t0 = common.nowNs(io); + const frames_max = if (forced_codes) |fc| @min(limit + 1, fc.len) else limit + 1; + try a.ensureCache(ids.len + frames_max + 2); + try a.prefill(ids, unc); + try g.flush(); + const t1 = common.nowNs(io); + try a.setI32(a.pos, @intCast(ids.len)); + try a.setI32(a.count, 0); + @memset(g.host(a.step, 8), 0); + if (forced_codes) |fc| try g.put(a.forced, std.mem.sliceAsBytes(fc[0..frames_max])); + const tokens = try a.gpa.alloc(i32, frames_max); + defer a.gpa.free(tokens); + var made: usize = 0; + var stop_at: ?usize = null; + const every = @max(1, sync_every); + var reported: usize = 0; + while (made < frames_max and stop_at == null) { + const burst = @min(every, frames_max - made); + for (0..burst) |_| try a.enqueueFrame(smp, forced_codes != null, trace); + try g.get(a.tokens + made * 4, std.mem.sliceAsBytes(tokens[made .. made + burst])); + for (tokens[made .. made + burst], made..) |tok, fi| if (tok == 0 and forced_codes == null) { + stop_at = fi; + break; + }; + made += burst; + if (progress) |p| if (made - reported >= 25 or stop_at != null or made == frames_max) { + reported = made; + const kept_now = @min(if (stop_at) |st| st else made, limit + 1) -| 1; + p.f(p.ctx, "ar", kept_now, limit); + }; + } + const end = if (stop_at) |st| st else made; // frames 1 .. end - 1 are kept + const kept = @min(end -| 1, limit); + if (kept == 0) return error.NoAudioFrames; + const states = try a.gpa.alloc(u16, kept * 8 * H); + errdefer a.gpa.free(states); + try g.get(a.states + 8 * H * 2, std.mem.sliceAsBytes(states)); + const t2 = common.nowNs(io); + const dec_s = @as(f64, @floatFromInt(t2 - t1)) / 1e9; + return .{ .states = states, .frames = kept, .stopped = stop_at != null, .prompt_tokens = ids.len, .prefill_ms = common.ms(t0, t1), .ar_ms = common.ms(t0, t2), .frames_per_s = @as(f64, @floatFromInt(made)) / @max(dec_s, 1e-9) }; + } +}; diff --git a/zig/src/families/music3/metal/dav.zig b/zig/src/families/music3/metal/dav.zig new file mode 100644 index 00000000000..a5d79d61119 --- /dev/null +++ b/zig/src/families/music3/metal/dav.zig @@ -0,0 +1,180 @@ +//! The DAV on Metal: latents [L, 128] to 44.1 kHz stereo; fp32 convs as tap GEMMs from bf16 halves, in chunks. +const std = @import("std"); +const wts = @import("../weights.zig"); +const gpu = @import("gpu.zig"); +const k = @import("kernels.zig"); + +const Gpu = gpu.Gpu; +const halo_rows = 27; // the widest conv's padding: 3 x dilation 9 + +pub const Options = struct { chunk: usize = 512, context: usize = 32, level: bool = true }; + +fn u(x: usize) u32 { + return @intCast(x); +} + +/// Every conv's taps as bf16 halves, hi then lo, in place of its fp32 taps (once, at load). +pub fn splitWeights(g: *Gpu, s: anytype, d: *wts.Dav) !void { + var convs: std.ArrayList(*wts.Conv) = .empty; + defer convs.deinit(g.gpa); + try convs.appendSlice(g.gpa, &.{ &d.in_proj, &d.conv0, &d.conv_out }); + for (&d.blocks) |*B| { + try convs.append(g.gpa, &B.up); + for (&B.res) |*R| try convs.appendSlice(g.gpa, &.{ &R.c1, &R.c2 }); + } + for (convs.items) |c| { + const n = c.k * c.cout * c.cin; + const packed_w = try s.alloc(n * 4); + k.split(g, c.w, packed_w, packed_w + n * 2, n); + try g.flush(); + g.free(c.w); + s.bytes -= n * 4; + c.w = packed_w; + } +} + +pub const Dav = struct { + gpa: std.mem.Allocator, + g: *Gpu, + w: *const wts.Dav, + o: Options = .{}, + + const Bufs = struct { lat: u64, x0: u64, p: u64, r: u64, y: u64, z: u64, out: u64, sh: u64, sl: u64, cap: usize, zcap: usize }; + + fn bias(dv: *Dav, y: u64, b: u64, C: usize, n: usize, set: bool) void { + dv.g.flat(.m3_bias_rows, n, &.{ y, b }, [3]u32{ u(C), u(n), @intFromBool(set) }); + } + + /// The halves of x [n] into the split scratch, for the GEMMs after it. + fn halves(dv: *Dav, b: Bufs, x: u64, n: usize) !void { + if (n > b.cap) return error.DavBuffers; + k.split(dv.g, x, b.sh, b.sl, n); + } + + /// y [T, Cout] (+)= x [T, Cin] W_j^T: x at element `xe` of the split scratch, W_j tap j of conv c (split at load). + fn gemm(dv: *Dav, b: Bufs, xe: usize, c: wts.Conv, j: usize, y: u64, T: usize, cout: usize, accumulate: bool) void { + const n = c.k * c.cout * c.cin; + const we = j * c.cout * c.cin; + k.linearSplit(dv.g, b.sh + xe * 2, b.sl + xe * 2, c.w + we * 2, c.w + (n + we) * 2, y, .{ .m = T, .n = cout, .k = c.cin, .accumulate = accumulate }); + } + + /// y [T, Cout] = bias + sum_j W_j x[t + j dil - pad] with x padded (data at halo_rows rows in). + fn conv(dv: *Dav, b: Bufs, c: wts.Conv, xpad: u64, T: usize, dil: usize, y: u64) !void { + const pad = (c.k - 1) / 2 * dil; + try dv.halves(b, xpad, (T + 2 * halo_rows) * c.cin); + dv.bias(y, c.b, c.cout, T * c.cout, true); + for (0..c.k) |j| dv.gemm(b, (halo_rows - pad + j * dil) * c.cin, c, j, y, T, c.cout, true); + } + + fn zeroHalos(dv: *Dav, pad: u64, T: usize, C: usize) void { + dv.g.flat(.m3_zero, halo_rows * C, &.{pad}, u(halo_rows * C)); + dv.g.flat(.m3_zero, halo_rows * C, &.{pad + (halo_rows + T) * C * 4}, u(halo_rows * C)); + } + + /// y = snake(x) into the padded buffer `pad` (C channels, T rows), its halos zeroed. + fn snakeInto(dv: *Dav, x: u64, alpha: u64, T: usize, C: usize, pad: u64) void { + dv.zeroHalos(pad, T, C); + dv.g.flat(.m3_snake, T * C, &.{ x, alpha, data(pad, C) }, [2]u32{ u(C), u(T * C) }); + } + + fn data(p: u64, C: usize) u64 { + return p + halo_rows * C * 4; + } + + /// One stereo half's latent rows [a, a + T) -> audio [T 512] into b.out. + fn decodeRows(dv: *Dav, b: Bufs, a0: usize, T0: usize, half: usize) !usize { + const g = dv.g; + const w = dv.w; + g.flat(.m3_latent_half, T0 * 64, &.{ b.lat, b.x0 }, [3]u32{ u(a0), u(T0), u(half) }); + // in_proj (k 1) straight into the padded buffer, then conv0 (k 7) + var T = T0; + { + const C = w.in_proj.cout; + dv.zeroHalos(b.p, T, C); + dv.bias(data(b.p, C), w.in_proj.b, C, T * C, true); + try dv.halves(b, b.x0, T * w.in_proj.cin); + dv.gemm(b, 0, w.in_proj, 0, data(b.p, C), T, C, true); + } + try dv.conv(b, w.conv0, b.p, T, 1, b.r); + var C = w.conv0.cout; + for (w.blocks) |B| { + // snake, the transposed conv (stride s, kernel 2s) as one GEMM into its taps, then the overlap-add + dv.snakeInto(b.r, B.alpha, T, C, b.p); + const up = B.up; + if (T * 2 * B.stride * up.cout > b.zcap) return error.DavBuffers; + try dv.halves(b, data(b.p, C), T * up.cin); + dv.gemm(b, 0, up, 0, b.z, T, up.k * up.cout, false); + const Tout = T * B.stride; + const OA = extern struct { Tin: u32, stride: u32, pad: u32, C: u32, Tout: u32 }; + g.flat(.m3_overlap_add, Tout * up.cout, &.{ b.z, up.b, b.r }, OA{ .Tin = u(T), .stride = u(B.stride), .pad = u((B.stride + 1) / 2), .C = u(up.cout), .Tout = u(Tout) }); + T = Tout; + C = up.cout; + if ((T + 2 * halo_rows) * C > b.cap) return error.DavBuffers; + for (B.res) |R| { + dv.snakeInto(b.r, R.a1, T, C, b.p); + try dv.conv(b, R.c1, b.p, T, R.dilation, b.y); + g.flat(.m3_snake, T * C, &.{ b.y, R.a2, b.y }, [2]u32{ u(C), u(T * C) }); + // r += c2(y) (k 1) + its bias + try dv.halves(b, b.y, T * C); + dv.gemm(b, 0, R.c2, 0, b.r, T, C, true); + dv.bias(b.r, R.c2.b, C, T * C, false); + } + try g.commit(); + } + dv.snakeInto(b.r, w.alpha_out, T, C, b.p); + try dv.conv(b, w.conv_out, b.p, T, 1, b.out); + g.flat(.m3_tanh, T, &.{b.out}, u(T)); + return T; + } + + /// Latents [L, 128] (host) -> stereo [2, 512 L] (host, f32), then ComfyUI's level rule (/ max(1, 5 std)). + pub fn decode(dv: *Dav, latents: []const f32, L: usize) ![]f32 { + const g = dv.g; + const chunk = dv.o.chunk; + const ctxr = dv.o.context; + const rows_max = @min(L, chunk + 2 * ctxr); + const t_max = rows_max * 512; + // the largest T x C over the stages: 96 x 512 rows (equal to 192 x 256) + const cap = (t_max + 2 * halo_rows) * 96 + (rows_max * 8 + 2 * halo_rows) * 1536; + const zcap = t_max / 2 * 4 * 96; + var list: [9]u64 = @splat(0); + defer { + g.flush() catch {}; + for (list) |p| g.free(p); + } + const sizes = [_]usize{ L * 128 * 4, rows_max * 64 * 4, cap * 4, cap * 4, cap * 4, zcap * 4, t_max * 4, cap * 2, cap * 2 }; + for (&list, sizes) |*p, sz| p.* = try g.alloc(sz); + const b: Bufs = .{ .lat = list[0], .x0 = list[1], .p = list[2], .r = list[3], .y = list[4], .z = list[5], .out = list[6], .sh = list[7], .sl = list[8], .cap = cap, .zcap = zcap }; + @memcpy(g.host(b.lat, latents.len * 4), std.mem.sliceAsBytes(latents)); + const audio = try dv.gpa.alloc(f32, 2 * L * 512); + errdefer dv.gpa.free(audio); + var start: usize = 0; + while (start < L) : (start += chunk) { + const end = @min(start + chunk, L); + const a0 = start -| ctxr; + const a1 = @min(L, end + ctxr); + for (0..2) |half| { + const T = try dv.decodeRows(b, a0, a1 - a0, half); + std.debug.assert(T == (a1 - a0) * 512); + const off = (start - a0) * 512; + const n = (end - start) * 512; + try g.get(b.out + off * 4, std.mem.sliceAsBytes(audio[half * L * 512 + start * 512 ..][0..n])); + } + } + // level: std over both channels (unbiased), divide by max(1, 5 std) + var mean: f64 = 0; + for (audio) |v| mean += v; + mean /= @floatFromInt(audio.len); + var ss: f64 = 0; + for (audio) |v| { + const dd = @as(f64, v) - mean; + ss += dd * dd; + } + const sd = @sqrt(ss / @as(f64, @floatFromInt(audio.len - 1))); + const level = @max(1.0, sd * 5.0); + if (dv.o.level and level > 1.0) for (audio) |*v| { + v.* = @floatCast(@as(f64, v.*) / level); + }; + return audio; + } +}; diff --git a/zig/src/families/music3/metal/dit.zig b/zig/src/families/music3/metal/dit.zig new file mode 100644 index 00000000000..85f749f52d6 --- /dev/null +++ b/zig/src/families/music3/metal/dit.zig @@ -0,0 +1,231 @@ +//! The DiT on Metal: condition, then Euler steps over windows (both CFG branches a forward), fp16 on the tensor units. +const std = @import("std"); +const cfg = @import("../config.zig"); +const wts = @import("../weights.zig"); +const gpu = @import("gpu.zig"); +const k = @import("kernels.zig"); + +const Gpu = gpu.Gpu; +const D = cfg.dit_width; + +pub const Options = struct { + window_batch: usize = 16, // windows a forward (each with both CFG branches) + comfy_rope: bool = true, // rope angles rounded to fp16 before cos / sin, as ComfyUI computes them + flash: bool = true, // CUDA's choice of attention kernel; Metal has one (m3_dit_attn) +}; + +pub const Progress = @import("../common.zig").Progress; + +pub const Probe = struct { cfg: f32, t: f32 }; // one forward at timestep t, returning u + (c - u) cfg + +fn u(x: usize) u32 { + return @intCast(x); +} + +/// Device buffers for one denoise, freed together once the GPU is done. +const Scratch = struct { + g: *Gpu, + list: std.ArrayList(u64) = .empty, + gpa: std.mem.Allocator, + fn mk(sc: *Scratch, bytes: usize) !u64 { + const p = try sc.g.alloc(bytes); + try sc.list.append(sc.gpa, p); + return p; + } + fn up(sc: *Scratch, bytes: []const u8) !u64 { + const p = try sc.mk(bytes.len); + @memcpy(sc.g.host(p, bytes.len), bytes); + return p; + } + fn deinit(sc: *Scratch) void { + sc.g.flush() catch {}; + for (sc.list.items) |p| sc.g.free(p); + sc.list.deinit(sc.gpa); + } +}; + +/// ff_in's rows in 32s, 16 value rows then their 16 gate rows, for m3_linear_glu_h (once, at load, in place). +pub fn pairGlu(gpa: std.mem.Allocator, g: *Gpu, d: *wts.Dit) !void { + const half = cfg.dit_mlp; + const row = D * 2; + const tmp = try gpa.alloc(u8, 2 * half * row); + defer gpa.free(tmp); + for (&d.blocks) |*B| { + const w = g.host(B.ff_in, 2 * half * row); + @memcpy(tmp, w); + for (0..half) |p| { + const at = (p / 16) * 32 + p % 16; + @memcpy(w[at * row ..][0..row], tmp[p * row ..][0..row]); + @memcpy(w[(at + 16) * row ..][0..row], tmp[(half + p) * row ..][0..row]); + } + } +} + +pub const Dit = struct { + gpa: std.mem.Allocator, + g: *Gpu, + w: *const wts.Dit, + o: Options, + + /// The condition [L, 2048] fp16 (device) from frame states bf16 [T, 8, 4096] (host). + fn condition(dt: *Dit, sc: *Scratch, states: []const u16, frames: usize, L: usize) !u64 { + const g = dt.g; + const st_d = try sc.up(std.mem.sliceAsBytes(states)); + const w8 = try sc.up(std.mem.sliceAsBytes(&dt.w.cond_w8)); + const mixed = try sc.mk(frames * 4096 * 2); + g.flat(.m3_cond_mix, frames * 4096, &.{ st_d, w8, mixed }, [2]f32{ dt.w.cond_scale, @floatFromInt(frames) }); + const col = try sc.mk(frames * 3 * 4096 * 2); + g.flat(.m3_im2col3, frames * 3 * 4096, &.{ mixed, col }, u(frames)); + const conv = try sc.mk(frames * D * 2); + k.linear(g, .m3_linear_h, col, dt.w.cond_conv, dt.w.cond_bias, conv, .{ .m = frames, .n = D, .k = 3 * 4096 }); + const idx = try cfg.nearest(dt.gpa, frames, L); + defer dt.gpa.free(idx); + const idx_d = try sc.up(std.mem.sliceAsBytes(idx)); + const cond = try sc.mk(L * D * 2); + g.go(.m3_gather_rows_h, .{ L, 1, 1 }, 256, &.{ conv, idx_d, cond }, {}); + return cond; + } + + /// cos, sin [Lseq, 16, 2] (f32 values of fp16 numbers) for positions 0..Lseq (0 is the timestep token). + fn ropeTable(dt: *Dit, sc: *Scratch, Lseq: usize) !u64 { + const host = try dt.gpa.alloc(f32, Lseq * 32); + defer dt.gpa.free(host); + for (0..Lseq) |j| for (0..16) |q| { + var ang: f32 = @as(f32, @floatFromInt(j)) * dt.w.inv_freq[q]; + if (dt.o.comfy_rope) ang = @floatCast(@as(f16, @floatCast(ang))); + host[(j * 16 + q) * 2] = @floatCast(@as(f16, @floatCast(@cos(ang)))); + host[(j * 16 + q) * 2 + 1] = @floatCast(@as(f16, @floatCast(@sin(ang)))); + }; + return sc.up(std.mem.sliceAsBytes(host)); + } + + /// Frame states (bf16 [frames, 32768]) to latents [L, 128]; `noise` or the seed's own; `probe`: one forward only. + pub fn denoise(dt: *Dit, states: []const u16, frames: usize, steps: usize, dit_cfg: f32, seed: u64, noise: ?[]const f32, probe: ?Probe, progress: ?Progress) ![]f32 { + const g = dt.g; + const L = cfg.framesToLatents(frames); + var sc: Scratch = .{ .g = g, .gpa = dt.gpa }; + defer sc.deinit(); + const cond = try dt.condition(&sc, states, frames, L); + const spans = try cfg.windows(dt.gpa, L); + defer dt.gpa.free(spans); + const x = try sc.mk(L * 128 * 4); + if (noise) |nz| { + if (nz.len != L * 128) return error.NoiseShape; + @memcpy(g.host(x, nz.len * 4), std.mem.sliceAsBytes(nz)); + } else { + g.flat(.m3_noise, L * 128 / 2 + 1, &.{x}, [2]u64{ seed, L * 128 }); + } + const vsum = try sc.mk(L * 128 * 4); + const vcnt = try sc.mk(L * 128 * 4); + const nb_max = @min(dt.o.window_batch, spans.len); + var lw_max: usize = 0; + for (spans) |sp| lw_max = @max(lw_max, sp.len); + const S_max = 2 * nb_max; + const Lseq_max = lw_max + 1; + const T_max = S_max * Lseq_max; + const full = try sc.mk(S_max * lw_max * cfg.dit_in * 2); + const full2 = try sc.mk(S_max * lw_max * cfg.dit_in * 2); + const h = try sc.mk(T_max * D * 2); + const hn = try sc.mk(T_max * D * 2); + const qkv = try sc.mk(T_max * 3 * D * 2); + const att = try sc.mk(T_max * D * 2); + const glu = try sc.mk(T_max * cfg.dit_mlp * 2); + const po = try sc.mk(S_max * lw_max * 128 * 2); + const pp = try sc.mk(S_max * lw_max * 128 * 2); + const tf = try sc.mk(256 * 2); + const te1 = try sc.mk(D * 2); + const te2 = try sc.mk(D * 2); + const te = try sc.mk(D * 2); + const rope_tabs = try dt.gpa.alloc(?u64, Lseq_max + 1); + defer dt.gpa.free(rope_tabs); + @memset(rope_tabs, null); + const sig = try cfg.sigmas(dt.gpa, steps); + defer dt.gpa.free(sig); + const n_steps = if (probe != null) 1 else steps; + for (0..n_steps) |step| { + const sigma = sig[step]; + const t_val: f32 = if (probe) |p| p.t else 1.0 - sigma; + const guide = if (probe) |p| p.cfg else dit_cfg; + // the timestep embedding (the same for every window and branch) + g.go(.m3_time_features, .{ 1, 1, 1 }, 128, &.{ dt.w.time_features, tf }, t_val); + dt.small(dt.w.time_in, dt.w.time_in_b, tf, 256, D, te1); + g.go(.m3_silu_h, .{ 1, 1, 1 }, 1024, &.{ te1, te2 }, u(D)); + dt.small(dt.w.time_out, dt.w.time_out_b, te2, D, D, te); + var b0: usize = 0; + while (b0 < spans.len) : (b0 += nb_max) { + const nb = @min(nb_max, spans.len - b0); + const batch = spans[b0 .. b0 + nb]; + var lw: usize = 0; + for (batch) |sp| lw = @max(lw, sp.len); + const S = 2 * nb; + const Lseq = lw + 1; + const T = S * Lseq; + var wins: [64]i32 = undefined; + var lens: [128]i32 = undefined; + for (batch, 0..) |sp, wi| { + wins[2 * wi] = @intCast(sp.start); + wins[2 * wi + 1] = @intCast(sp.len); + lens[wi] = @intCast(sp.len + 1); + lens[nb + wi] = @intCast(sp.len + 1); + } + const wins_d = try sc.up(std.mem.sliceAsBytes(wins[0 .. 2 * nb])); + const lens_d = try sc.up(std.mem.sliceAsBytes(lens[0..S])); + if (rope_tabs[Lseq] == null) rope_tabs[Lseq] = try dt.ropeTable(&sc, Lseq); + const cs = rope_tabs[Lseq].?; + // inputs: [x, 0, condition] + preprocess(...), project_in into rows 1.. of each sequence + g.go(.m3_dit_input, .{ lw, S, 1 }, 256, &.{ x, cond, dt.w.cond_bias, wins_d, full }, [2]u32{ u(nb), u(lw) }); + k.linear(g, .m3_linear_h, full, dt.w.pre, 0, full2, .{ .m = S * lw, .n = cfg.dit_in, .k = cfg.dit_in }); + g.flat(.m3_add_h, S * lw * cfg.dit_in, &.{ full2, full }, u(S * lw * cfg.dit_in)); + k.linear(g, .m3_linear_h, full2, dt.w.project_in, 0, h + D * 2, .{ .m = lw, .n = D, .k = cfg.dit_in, .ldy = D, .batch = S, .sx = lw * cfg.dit_in, .sy = Lseq * D }); + g.go(.m3_put_time, .{ S, 1, 1 }, 256, &.{ te, h }, u(Lseq)); + for (&dt.w.blocks, 0..) |*B, bi| { + // the previous block's ff_out bias goes in with this block's pre-norm + dt.layerNorm(h, if (bi > 0) dt.w.blocks[bi - 1].ff_out_b else 0, B.pre_g, B.pre_b, hn, T); + // q and k leave the GEMM roped, rounded to fp16 first as the reference rounds them + k.linear(g, .m3_linear_rope_h, hn, B.qkv, 0, qkv, .{ .m = T, .n = 3 * D, .k = D, .cs = cs, .lseq = Lseq }); + const A = extern struct { Lseq: u32, scale: f32 }; + g.go(.m3_dit_attn, .{ (Lseq + 63) / 64, 32, S }, 128, &.{ qkv, lens_d, att }, A{ .Lseq = u(Lseq), .scale = 0.125 }); + k.linear(g, .m3_linear_h, att, B.out, 0, h, .{ .m = T, .n = D, .k = D, .accumulate = true }); + dt.layerNorm(h, 0, B.ff_g, B.ff_b, hn, T); + // ff_in's rows paired at load (dit.pairGlu): the GEMM writes the GLU of value and gate + k.linear(g, .m3_linear_glu_h, hn, B.ff_in, B.ff_in_b, glu, .{ .m = T, .n = 2 * cfg.dit_mlp, .k = D, .ldy = cfg.dit_mlp }); + k.linear(g, .m3_linear_h, glu, B.ff_out, 0, h, .{ .m = T, .n = D, .k = cfg.dit_mlp, .accumulate = true }); + try g.commit(); + } + g.flat(.m3_bias_h, T * D, &.{ h, dt.w.blocks[cfg.dit_blocks - 1].ff_out_b }, u(T * D)); + // project_out on rows 1.., the 1x1 postprocess, the guided velocity into the sums + k.linear(g, .m3_linear_h, h + D * 2, dt.w.project_out, 0, po, .{ .m = lw, .n = 128, .k = D, .ldx = D, .batch = S, .sx = Lseq * D, .sy = lw * 128 }); + k.linear(g, .m3_linear_h, po, dt.w.post, 0, pp, .{ .m = S * lw, .n = 128, .k = 128 }); + const GA = extern struct { nwin: u32, Lw: u32, L: u32, cfg: f32 }; + g.flat(.m3_dit_gather, L * 128, &.{ po, pp, wins_d, vsum, vcnt }, GA{ .nwin = u(nb), .Lw = u(lw), .L = u(L), .cfg = guide }); + } + if (probe != null) { + // the model output itself: vsum / vcnt, with no Euler step + try g.flush(); + const out = try dt.gpa.alloc(f32, L * 128); + const s_ = std.mem.bytesAsSlice(f32, g.host(vsum, L * 128 * 4)); + const c_ = std.mem.bytesAsSlice(f32, g.host(vcnt, L * 128 * 4)); + for (out, s_, c_) |*o, s, c| o.* = s / c; + return out; + } + g.flat(.m3_euler, L * 128, &.{ x, vsum, vcnt }, [2]f32{ sig[step + 1] - sigma, @floatFromInt(L * 128) }); + try g.commit(); + if (progress) |p| { + try g.flush(); + p.f(p.ctx, "dit", step + 1, steps); + } + } + const out = try dt.gpa.alloc(f32, L * 128); + errdefer dt.gpa.free(out); + try g.get(x, std.mem.sliceAsBytes(out)); + return out; + } + + fn small(dt: *Dit, w: u64, b: u64, x: u64, K: usize, N: usize, y: u64) void { + dt.g.go(.m3_linear_h1, .{ (N + 7) / 8, 1, 1 }, 256, &.{ w, b, x, y }, [2]u32{ u(K), u(N) }); + } + + fn layerNorm(dt: *Dit, x: u64, bias: u64, g_: u64, b: u64, y: u64, rows: usize) void { + dt.g.go(.m3_layernorm_h, .{ rows, 1, 1 }, 256, &.{ x, bias, g_, b, y }, @as(u32, @intFromBool(bias != 0))); + } +}; diff --git a/zig/src/families/music3/metal/engine.zig b/zig/src/families/music3/metal/engine.zig new file mode 100644 index 00000000000..053d6667443 --- /dev/null +++ b/zig/src/families/music3/metal/engine.zig @@ -0,0 +1,162 @@ +//! MiniMax Music 3 on Metal: the three stages behind one load (AR frames, the DiT, the DAV), timed apart. +const std = @import("std"); +const core = @import("core"); +const cfg = @import("../config.zig"); +const wts = @import("../weights.zig"); +const prompt = @import("../prompt.zig"); +const common = @import("../common.zig"); +const gpu = @import("gpu.zig"); +const k = @import("kernels.zig"); +const ar_ = @import("ar.zig"); +const dit_ = @import("dit.zig"); +const dav_ = @import("dav.zig"); + +pub const Options = struct { + format: wts.Format = .int8, + depth_group: usize = 128, // int8 depth decoder and heads: a scale a group of 128 inputs (0: a row) + load_ar: bool = true, + load_dit: bool = true, + load_dav: bool = true, + dit: dit_.Options = .{}, + sync_every: usize = 16, + log: bool = true, + graphs: bool = true, // CUDA graphs: a CUDA-only knob, ignored here + dav_tf32: bool = false, // CUDA-only, ignored here (the DAV's GEMMs are fp32 on the tensor units) +}; + +pub const Song = common.Song; +pub const Progress = common.Progress; + +/// The store weights.zig's loaders fill: shared Metal buffers, and one staging buffer for the int8 quantizer. +pub const Store = struct { + g: *gpu.Gpu, + bytes: usize = 0, + staging: u64 = 0, + + const staging_bytes: usize = 24576 * 4096 * 2; + + pub fn alloc(s: *Store, bytes: usize) !u64 { + s.bytes += bytes; + return s.g.alloc(bytes); + } + + pub fn upload(s: *Store, bytes: []const u8) !u64 { + const p = try s.alloc(bytes.len); + @memcpy(s.g.host(p, bytes.len), bytes); + return p; + } + + pub fn stage(s: *Store, bytes: []const u8) !u64 { + if (bytes.len > staging_bytes) return error.StagingTooSmall; + if (s.staging == 0) s.staging = try s.g.alloc(staging_bytes); + try s.g.put(s.staging, bytes); + return s.staging; + } + + pub fn unstage(s: *Store) void { + s.g.flush() catch {}; + s.g.free(s.staging); + s.staging = 0; + } +}; + +pub const Engine = struct { + gpa: std.mem.Allocator, + o: Options, + g: *gpu.Gpu, + store: Store, + arw: ?wts.Ar = null, + ditw: ?wts.Dit = null, + davw: ?wts.Dav = null, + tok: ?core.tokenizer.Tokenizer = null, + ar: ?ar_.Ar = null, + load_ms: f64 = 0, + + pub fn create(gpa: std.mem.Allocator, io: std.Io, model_dir: []const u8, o: Options) !*Engine { + const t0 = common.nowNs(io); + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + const g = try gpu.Gpu.open(gpa, @import("music3_metallib").bytes); + errdefer g.close(); + e.* = .{ .gpa = gpa, .o = o, .g = g, .store = .{ .g = g } }; + if (o.load_ar) { + e.arw = try wts.loadAr(gpa, io, &e.store, model_dir, o.format, o.depth_group, .{ .ctx = e, .f = quantize }, o.log); + e.tok = try core.tokenizer.parse(gpa, e.arw.?.tokenizer_json); + try prompt.checkTokenizer(&e.tok.?); + e.ar = try ar_.Ar.init(gpa, g, &e.arw.?); + } + if (o.load_dit) { + e.ditw = try wts.loadDit(gpa, io, &e.store, model_dir, o.log); + try dit_.pairGlu(gpa, g, &e.ditw.?); + } + if (o.load_dav) { + e.davw = try wts.loadDav(gpa, io, &e.store, model_dir); + try dav_.splitWeights(g, &e.store, &e.davw.?); + } + try g.flush(); + e.load_ms = common.ms(t0, common.nowNs(io)); + if (o.log) std.log.info("music3: weights in Metal buffers: {d:.2} GB, loaded in {d:.1} s", .{ @as(f64, @floatFromInt(e.store.bytes)) / 1e9, e.load_ms / 1000 }); + return e; + } + + fn quantize(ctx: *anyopaque, src: u64, n: usize, kk: usize, group: usize, q: u64, sc: u64) anyerror!void { + const e: *Engine = @ptrCast(@alignCast(ctx)); + if (group != 0 and group != 128) return error.UnsupportedGroup; + k.quant(e.g, src, n, kk, group, q, sc); + try e.g.flush(); + } + + pub fn destroy(e: *Engine) void { + if (e.tok) |*t| t.deinit(); + if (e.arw) |a| e.gpa.free(a.tokenizer_json); + e.g.close(); + e.gpa.destroy(e); + } + + pub fn dit(e: *Engine) dit_.Dit { + return .{ .gpa = e.gpa, .g = e.g, .w = &e.ditw.?, .o = e.o.dit }; + } + + pub fn dav(e: *Engine) dav_.Dav { + return .{ .gpa = e.gpa, .g = e.g, .w = &e.davw.? }; + } + + /// The conditional prompt's ids and the unconditional row (caller frees both). + pub fn ids(e: *Engine, caption: []const u8, lyrics: []const u8) !struct { cond: []u32, unc: []u32 } { + const c = try prompt.encode(e.gpa, &e.tok.?, caption, lyrics); + errdefer e.gpa.free(c); + return .{ .cond = c, .unc = try prompt.unconditional(e.gpa, c) }; + } + + pub fn frameBytes(e: *const Engine) f64 { + return common.frameBytes(&e.arw.?); + } + + /// Weight bytes in Metal buffers. + pub fn deviceBytes(e: *const Engine) usize { + return e.store.bytes; + } + + pub fn generate(e: *Engine, io: std.Io, caption: []const u8, lyrics: []const u8, s: cfg.Settings, progress: ?Progress) !Song { + e.g.peak = e.g.device.allocated(); + const t0 = common.nowNs(io); + const pr = try e.ids(caption, lyrics); + defer e.gpa.free(pr.cond); + defer e.gpa.free(pr.unc); + const smp: ar_.Sampling = .{ .ar_cfg = s.ar_cfg, .top_k = s.top_k, .seed = cfg.deriveSeed(s.seed, "ar") }; + const r = try e.ar.?.run(io, pr.cond, pr.unc, smp, s.frameLimit(), false, e.o.sync_every, null, null, progress); + defer e.gpa.free(r.states); + const t1 = common.nowNs(io); + var d = e.dit(); + const latents = try d.denoise(r.states, r.frames, s.steps, s.dit_cfg, cfg.deriveSeed(s.seed, "dit"), null, null, progress); + defer e.gpa.free(latents); + const t2 = common.nowNs(io); + const L = cfg.framesToLatents(r.frames); + if (progress) |p| p.f(p.ctx, "dav", 0, 1); + var v = e.dav(); + const audio = try v.decode(latents, L); + const t3 = common.nowNs(io); + if (progress) |p| p.f(p.ctx, "dav", 1, 1); + return .{ .audio = audio, .samples = L * 512, .frames = r.frames, .stopped = r.stopped, .prompt_tokens = r.prompt_tokens, .prefill_ms = r.prefill_ms, .ar_ms = common.ms(t0, t1), .frames_per_s = r.frames_per_s, .dit_ms = common.ms(t1, t2), .dav_ms = common.ms(t2, t3), .total_ms = common.ms(t0, t3), .latent_frames = L, .peak_device_gb = @as(f64, @floatFromInt(e.g.peak)) / 1e9 }; + } +}; diff --git a/zig/src/families/music3/metal/gpu.zig b/zig/src/families/music3/metal/gpu.zig new file mode 100644 index 00000000000..32203dd1ce3 --- /dev/null +++ b/zig/src/families/music3/metal/gpu.zig @@ -0,0 +1,235 @@ +//! Music 3's Metal device: one queue, the music3 metallib, and buffers addressed as u64 (slot << 40 | byte offset). +const std = @import("std"); +const mtl = @import("metal"); + +/// Every pipeline of music3.metallib, by its kernel name. +pub const P = enum { + m3_embed, + m3_embed_code, + m3_frame_embed, + m3_rmsnorm, + m3_add, + m3_swiglu, + m3_quant, + m3_dequant, + m3_gemv_bf16_2, + m3_gemv_bf16_4, + m3_gemv_i8_2, + m3_gemv_i8_4, + m3_gemv_g8_2, + m3_gemv_g8_4, + m3_glu_bf16_2, + m3_glu_bf16_4, + m3_glu_i8_2, + m3_glu_i8_4, + m3_glu_g8_2, + m3_glu_g8_4, + m3_qk_rope, + m3_attn_part, + m3_attn_merge, + m3_depth_kv, + m3_depth_attn, + m3_sample, + m3_frame_done, + m3_state_part, + m3_force_codes, + m3_copy, + m3_linear_b, + m3_linear_h, + m3_linear_glu_h, + m3_linear_rope_h, + m3_linear_s, + m3_split, + m3_cond_mix, + m3_im2col3, + m3_dit_input, + m3_add_h, + m3_time_features, + m3_silu_h, + m3_linear_h1, + m3_gather_rows_h, + m3_put_time, + m3_layernorm_h, + m3_bias_h, + m3_dit_gather, + m3_euler, + m3_noise, + m3_dit_attn, + m3_snake, + m3_bias_rows, + m3_overlap_add, + m3_zero, + m3_latent_half, + m3_tanh, +}; + +const n_pipes = @typeInfo(P).@"enum".field_names.len; +const slot_shift = 40; + +pub const Ref = struct { buf: mtl.Buffer, off: usize }; + +pub const Gpu = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + lib: mtl.Library, + pipes: [n_pipes]mtl.Pipeline, + bufs: std.ArrayList(mtl.Buffer), // by slot; slot 0 is a small zeroed buffer bound for address 0 (an unused input) + owned: std.ArrayList(bool), + pool: ?mtl.objc.Pool = null, + cb: ?mtl.CommandBuffer = null, + enc: ?mtl.ComputeEncoder = null, + pending: ?mtl.CommandBuffer = null, // committed, not yet waited for + peak: u64 = 0, + + pub fn open(gpa: std.mem.Allocator, metallib: []const u8) !*Gpu { + const g = try gpa.create(Gpu); + errdefer gpa.destroy(g); + g.* = .{ .gpa = gpa, .device = try mtl.Device.init(), .queue = undefined, .lib = undefined, .pipes = undefined, .bufs = .empty, .owned = .empty }; + if (!g.device.tensorUnits()) { + std.log.err("music3 metal: this GPU has no tensor units; the GEMMs need an M5 or later", .{}); + return error.NeedsTensorUnits; + } + g.queue = try g.device.queue(); + g.lib = try mtl.Library.fromBytes(g.device, metallib); + inline for (@typeInfo(P).@"enum".field_names, 0..) |name, i| g.pipes[i] = try mtl.Pipeline.init(g.device, g.lib, name, false); + const zero = try g.device.buffer(256, mtl.ResourceOptions.shared); + @memset(zero.contents()[0..256], 0); + try g.bufs.append(gpa, zero); + try g.owned.append(gpa, true); + return g; + } + + pub fn close(g: *Gpu) void { + g.flush() catch {}; + for (g.bufs.items, g.owned.items) |b, own| if (own) b.deinit(); + g.bufs.deinit(g.gpa); + g.owned.deinit(g.gpa); + for (&g.pipes) |*p| p.deinit(); + g.lib.deinit(); + g.queue.deinit(); + g.device.deinit(); + g.gpa.destroy(g); + } + + /// A new zeroed shared buffer of `bytes`, by address. + pub fn alloc(g: *Gpu, bytes: usize) !u64 { + const len = std.mem.alignForward(usize, @max(bytes, 256), 256); + const b = try g.device.buffer(len, mtl.ResourceOptions.shared); + @memset(b.contents()[0..len], 0); + g.peak = @max(g.peak, g.device.allocated()); + return g.register(b, true) catch |err| { + b.deinit(); + return err; + }; + } + + /// Release a buffer from alloc (its slot stays, empty); the GPU must be done with it. + pub fn free(g: *Gpu, addr: u64) void { + const slot: usize = @intCast(addr >> slot_shift); + if (slot == 0 or !g.owned.items[slot]) return; + g.bufs.items[slot].deinit(); + g.owned.items[slot] = false; + } + + pub fn register(g: *Gpu, b: mtl.Buffer, own: bool) !u64 { + try g.bufs.ensureUnusedCapacity(g.gpa, 1); + try g.owned.ensureUnusedCapacity(g.gpa, 1); + g.bufs.appendAssumeCapacity(b); + g.owned.appendAssumeCapacity(own); + return @as(u64, g.bufs.items.len - 1) << slot_shift; + } + + pub fn ref(g: *const Gpu, addr: u64) Ref { + return .{ .buf = g.bufs.items[@intCast(addr >> slot_shift)], .off = @intCast(addr & ((@as(u64, 1) << slot_shift) - 1)) }; + } + + /// The host view of `len` bytes at `addr` (unified memory; flush first when the GPU writes them). + pub fn host(g: *const Gpu, addr: u64, len: usize) []u8 { + const r = g.ref(addr); + return r.buf.contents()[r.off..][0..len]; + } + + /// The encoder of the open command buffer (made on first use). + pub fn encoder(g: *Gpu) mtl.ComputeEncoder { + if (g.enc) |e| return e; + if (g.pool == null) g.pool = mtl.objc.Pool.push(); + const cb = g.queue.commandBuffer(); + g.cb = cb; + const e = cb.compute(.serial); + g.enc = e; + return e; + } + + /// One dispatch: buffers bound at 0.., then `args` (an extern struct, a scalar, or void) at the next index. + pub fn go(g: *Gpu, p: P, groups: [3]usize, threads: usize, bufs: []const u64, args: anytype) void { + const e = g.encoder(); + e.setPipeline(g.pipes[@backingInt(p)]); + for (bufs, 0..) |a, i| { + const r = g.ref(a); + e.setBuffer(r.buf, r.off, i); + } + if (@TypeOf(args) != void) e.setBytes(std.mem.asBytes(&args), bufs.len); + e.dispatchGroups(mtl.Size.of(groups[0], groups[1], groups[2]), mtl.Size.of(threads, 1, 1)); + } + + /// An elementwise launch: n threads in groups of 256. + pub fn flat(g: *Gpu, p: P, n: usize, bufs: []const u64, args: anytype) void { + g.go(p, .{ @max(1, (n + 255) / 256), 1, 1 }, 256, bufs, args); + } + + /// Commit what is encoded without waiting (the previous commit is waited for first). + pub fn commit(g: *Gpu) !void { + const e = g.enc orelse return; + e.end(); + const cb = g.cb.?.retain(); + cb.commit(); + g.enc = null; + g.cb = null; + defer { + if (g.pool) |p| p.pop(); + g.pool = null; + } + g.waitPending() catch |err| { + cb.wait(); + cb.release(); + return err; + }; + g.pending = cb; + } + + fn waitPending(g: *Gpu) !void { + const cb = g.pending orelse return; + g.pending = null; + defer cb.release(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("music3 metal: command buffer failed: {s}", .{msg}); + return error.CommandBufferFailed; + } + } + + /// Commit and wait until the GPU is done. + pub fn flush(g: *Gpu) !void { + try g.commit(); + try g.waitPending(); + g.peak = @max(g.peak, g.device.allocated()); + } + + pub fn put(g: *Gpu, dst: u64, bytes: []const u8) !void { + try g.flush(); + @memcpy(g.host(dst, bytes.len), bytes); + } + + pub fn get(g: *Gpu, src: u64, out: []u8) !void { + try g.flush(); + @memcpy(out, g.host(src, out.len)); + } + + /// Copy `bytes` on the GPU, in order with the dispatches around it. + pub fn copy(g: *Gpu, src: u64, dst: u64, bytes: usize) void { + std.debug.assert(bytes % 4 == 0); + const n: u32 = @intCast(bytes / 4); + g.flat(.m3_copy, n, &.{ src, dst }, n); + } +}; diff --git a/zig/src/families/music3/metal/kernels.zig b/zig/src/families/music3/metal/kernels.zig new file mode 100644 index 00000000000..da17e6873a2 --- /dev/null +++ b/zig/src/families/music3/metal/kernels.zig @@ -0,0 +1,168 @@ +//! Music 3's Metal launches: each wrapper binds its buffers and argument struct as zig/kernels/metal/music3 declares. +const std = @import("std"); +const gpu = @import("gpu.zig"); +const wts = @import("../weights.zig"); + +const Gpu = gpu.Gpu; +const H = 4096; + +fn u(x: usize) u32 { + return @intCast(x); +} + +// -------------------------------------------------------------------------------------------- AR rows + +pub fn embed(g: *Gpu, ids: u64, table: u64, out: u64, rows: usize) void { + g.go(.m3_embed, .{ rows, 1, 1 }, 256, &.{ ids, table, out }, u(H)); +} + +pub fn embedCode(g: *Gpu, code: u64, offset: usize, table: u64, out: u64, rows: usize) void { + const A = extern struct { offset: i32, rows: u32, dim: u32 }; + g.go(.m3_embed_code, .{ 1, 1, 1 }, 256, &.{ code, table, out }, A{ .offset = @intCast(offset), .rows = u(rows), .dim = H }); +} + +pub fn frameEmbed(g: *Gpu, codes: u64, audio: u64, extra: u64, out: u64, rows: usize) void { + const A = extern struct { rows: u32, dim: u32, scale: f32 }; + g.go(.m3_frame_embed, .{ 16, 1, 1 }, 256, &.{ codes, audio, extra, out }, A{ .rows = u(rows), .dim = H, .scale = @floatCast(1.0 / @sqrt(8.0)) }); +} + +pub fn rmsnorm(g: *Gpu, x: u64, xs: usize, w: u64, y: u64, ys: usize, rows: usize, eps: f32) void { + const A = extern struct { xs: u32, ys: u32, dim: u32, eps: f32 }; + g.go(.m3_rmsnorm, .{ rows, 1, 1 }, 256, &.{ x, w, y }, A{ .xs = u(xs), .ys = u(ys), .dim = H, .eps = eps }); +} + +pub fn add(g: *Gpu, x: u64, b: u64, n: usize) void { + g.flat(.m3_add, n, &.{ x, b }, u(n)); +} + +pub fn swiglu(g: *Gpu, gu: u64, y: u64, width: usize, rows: usize) void { + const A = extern struct { width: u32, rows: u32 }; + g.flat(.m3_swiglu, rows * width, &.{ gu, y }, A{ .width = u(width), .rows = u(rows) }); +} + +/// bf16 rows to int8 with a scale a row (group 0) or a scale a group of `group` inputs. +pub fn quant(g: *Gpu, src: u64, n: usize, k: usize, group: usize, q: u64, sc: u64) void { + g.go(.m3_quant, .{ n, 1, 1 }, 256, &.{ src, q, sc }, [2]u32{ u(k), u(group) }); +} + +pub fn dequant(g: *Gpu, m: wts.Mat, out: u64) void { + g.go(.m3_dequant, .{ (m.k + 255) / 256, m.n, 1 }, 256, &.{ m.w, m.sc, out }, [2]u32{ u(m.k), u(m.group) }); +} + +pub const gemv_sg = 2; // M3_GEMV_SG in ar.metal + +pub const Gemv = struct { + xs: usize = 0, // x row stride (0: K) + glu: bool = false, // gate | up rows: write the SwiGLU of rows n and N / 2 + n at n + y: u64 = 0, + ys: usize = 0, // 0: N (N / 2 with glu) + yf: u64 = 0, + res: u64 = 0, + res_div: usize = 1, +}; + +/// y[m] = W x[m] for m < rows (2 or 4): bf16, int8 a scale a row or a scale a group of 128, by the Mat. +pub fn gemv(g: *Gpu, w: wts.Mat, x: u64, rows: usize, o: Gemv) void { + std.debug.assert(rows == 2 or rows == 4); + std.debug.assert(w.group == 0 or w.group == 128); + const four = rows == 4; + const kind: usize = if (w.group != 0) 2 else if (w.sc != 0) 1 else 0; + const table = [2][3][2]gpu.P{ + .{ .{ .m3_gemv_bf16_2, .m3_gemv_bf16_4 }, .{ .m3_gemv_i8_2, .m3_gemv_i8_4 }, .{ .m3_gemv_g8_2, .m3_gemv_g8_4 } }, + .{ .{ .m3_glu_bf16_2, .m3_glu_bf16_4 }, .{ .m3_glu_i8_2, .m3_glu_i8_4 }, .{ .m3_glu_g8_2, .m3_glu_g8_4 } }, + }; + const outs = if (o.glu) w.n / 2 else w.n; + const A = extern struct { xs: u32, K: u32, N: u32, ys: u32, res_div: u32, has_y: u32, has_yf: u32, has_res: u32 }; + const a: A = .{ .xs = u(if (o.xs != 0) o.xs else w.k), .K = u(w.k), .N = u(w.n), .ys = u(if (o.ys != 0) o.ys else outs), .res_div = u(o.res_div), .has_y = @intFromBool(o.y != 0), .has_yf = @intFromBool(o.yf != 0), .has_res = @intFromBool(o.res != 0) }; + // gemv_sg simdgroups a group: a SwiGLU pair each, else two outputs each + const per: usize = if (o.glu) gemv_sg else 2 * gemv_sg; + g.go(table[@intFromBool(o.glu)][kind][@intFromBool(four)], .{ (outs + per - 1) / per, 1, 1 }, 32 * gemv_sg, &.{ w.w, w.sc, x, o.y, o.yf, o.res }, a); +} + +/// Prompt rows: y [t, N] = x [t, K] W^T in bf16 (fp32 sums); int8 weights dequantized to `tmp` first. +pub fn linearRows(g: *Gpu, w: wts.Mat, x: u64, y: u64, t: usize, tmp: u64) void { + var wp = w.w; + if (w.sc != 0) { + dequant(g, w, tmp); + wp = tmp; + } + linear(g, .m3_linear_b, x, wp, 0, y, .{ .m = t, .n = w.n, .k = w.k }); +} + +pub fn qkRope(g: *Gpu, qkv: u64, qn: u64, kn: u64, inv_freq: u64, pos: u64, t: usize, rows: usize, q: u64, kc: u64, vc: u64, ctx: usize) void { + const A = extern struct { t: u32, ctx: u32, eps: f32 }; + g.go(.m3_qk_rope, .{ rows, 48, 1 }, 128, &.{ qkv, qn, kn, inv_freq, pos, q, kc, vc }, A{ .t = u(t), .ctx = u(ctx), .eps = 1e-6 }); +} + +pub fn attention(g: *Gpu, q: u64, kc: u64, vc: u64, pos: u64, t: usize, rows: usize, ctx: usize, splits: usize, ml: u64, acc: u64, out: u64) void { + const A = extern struct { t: u32, ctx: u32, splits: u32, scale: f32 }; + g.go(.m3_attn_part, .{ 8, rows, splits }, 128, &.{ q, kc, vc, pos, ml, acc }, A{ .t = u(t), .ctx = u(ctx), .splits = u(splits), .scale = @floatCast(1.0 / @sqrt(128.0)) }); + g.go(.m3_attn_merge, .{ rows, 32, 1 }, 128, &.{ ml, acc, out }, u(splits)); +} + +pub fn depthAttention(g: *Gpu, qkv: u64, p0: usize, rows: usize, kc: u64, vc: u64, out: u64) void { + const A = extern struct { p0: u32, B: u32, scale: f32 }; + const a: A = .{ .p0 = u(p0), .B = 2, .scale = 1.0 / 16.0 }; + g.go(.m3_depth_kv, .{ rows, 16, 1 }, 256, &.{ qkv, kc, vc }, a); + g.go(.m3_depth_attn, .{ rows, 16, 1 }, 256, &.{ qkv, kc, vc, out }, a); +} + +pub const Draw = struct { cfg: f32, top_k: i32, seed: u64, step: u64, slot: i32, pick: u64, code: u64 = 0, tokens: u64 = 0, count: u64 = 0 }; + +pub const SampleArgs = extern struct { seed: u64, V: u32, cfg: f32, top_k: i32, rank_cond: i32, slot: i32, has_code: i32, has_tokens: i32, pad: i32 = 0 }; + +pub fn sample(g: *Gpu, logits: u64, v: usize, rank_cond: bool, d: Draw) void { + const a: SampleArgs = .{ .seed = d.seed, .V = u(v), .cfg = d.cfg, .top_k = d.top_k, .rank_cond = @intFromBool(rank_cond), .slot = d.slot, .has_code = @intFromBool(d.code != 0), .has_tokens = @intFromBool(d.tokens != 0) }; + g.go(.m3_sample, .{ 1, 1, 1 }, 1024, &.{ logits, d.step, d.pick, d.code, d.tokens, d.count }, a); +} + +pub fn frameDone(g: *Gpu, pos: u64, step: u64, count: u64) void { + g.go(.m3_frame_done, .{ 1, 1, 1 }, 32, &.{ pos, step, count }, {}); +} + +pub fn statePart(g: *Gpu, src: u64, states: u64, count: u64, part: usize) void { + g.go(.m3_state_part, .{ 1, 1, 1 }, 256, &.{ src, states, count }, u(part)); +} + +pub fn forceCodes(g: *Gpu, forced: u64, count: u64, codes: u64, tokens: u64) void { + g.go(.m3_force_codes, .{ 1, 1, 1 }, 32, &.{ forced, count, codes, tokens }, {}); +} + +// -------------------------------------------------------------------------------------------- GEMMs + +pub const Shape = struct { + m: usize, + n: usize, + k: usize, + ldx: usize = 0, // 0: k + ldy: usize = 0, // 0: n + batch: usize = 1, + sx: usize = 0, // batch strides in elements + sy: usize = 0, + accumulate: bool = false, + cs: u64 = 0, // m3_linear_rope_h: the rope table [Lseq, 16, 2] + lseq: usize = 0, // m3_linear_rope_h: rows a sequence +}; + +/// Y[b] [m, n] = X[b] [m, k] W [n, k]^T (+ bias [n]) (+ Y[b]) on the tensor units; `p` picks the type and epilogue. +pub fn linear(g: *Gpu, p: gpu.P, x: u64, w: u64, bias: u64, y: u64, s: Shape) void { + const a: LinearArgs = .{ .M = @intCast(s.m), .N = @intCast(s.n), .K = @intCast(s.k), .ldx = @intCast(if (s.ldx != 0) s.ldx else s.k), .ldy = @intCast(if (s.ldy != 0) s.ldy else s.n), .has_bias = @intFromBool(bias != 0), .accumulate = @intFromBool(s.accumulate), .pad = @intCast(s.lseq), .sx = @intCast(s.sx), .sy = @intCast(s.sy) }; + g.go(p, .{ (s.n + 127) / 128, (s.m + 63) / 64, s.batch }, 256, &.{ x, w, bias, y, s.cs }, a); +} + +const LinearArgs = extern struct { M: i32, N: i32, K: i32, ldx: i32, ldy: i32, has_bias: i32, accumulate: i32, pad: i32 = 0, sx: i64, sy: i64 }; + +/// fp32 Y [m, n] (+)= X W^T from bf16 halves of both (x = xh + xl at xh, xl; w likewise), no bias. +pub fn linearSplit(g: *Gpu, xh: u64, xl: u64, wh: u64, wl: u64, y: u64, s: Shape) void { + const a: LinearArgs = .{ .M = @intCast(s.m), .N = @intCast(s.n), .K = @intCast(s.k), .ldx = @intCast(if (s.ldx != 0) s.ldx else s.k), .ldy = @intCast(if (s.ldy != 0) s.ldy else s.n), .has_bias = 0, .accumulate = @intFromBool(s.accumulate), .sx = @intCast(s.sx), .sy = @intCast(s.sy) }; + g.go(.m3_linear_s, .{ (s.n + 127) / 128, (s.m + 63) / 64, s.batch }, 256, &.{ xh, xl, wh, wl, y }, a); +} + +/// fp32 x [n] into bf16 halves hi + lo. +pub fn split(g: *Gpu, x: u64, hi: u64, lo: u64, n: usize) void { + g.flat(.m3_split, n, &.{ x, hi, lo }, u(n)); +} + +test "argument structs match the kernels' layouts" { + try std.testing.expectEqual(@as(usize, 40), @sizeOf(SampleArgs)); +} diff --git a/zig/src/families/music3/music3.zig b/zig/src/families/music3/music3.zig new file mode 100644 index 00000000000..0cd29884426 --- /dev/null +++ b/zig/src/families/music3/music3.zig @@ -0,0 +1,25 @@ +//! MiniMax Music 3 (MiniMax-Music3) on one CUDA GPU: the AR LM and depth decoder, the DiT and the DAV. +pub const backend = "cuda"; +pub const config = @import("config.zig"); +pub const common = @import("common.zig"); +pub const prompt = @import("prompt.zig"); +pub const weights = @import("weights.zig"); +pub const kernels = @import("kernels.zig"); +pub const ar = @import("ar.zig"); +pub const dit = @import("dit.zig"); +pub const dav = @import("dav.zig"); +pub const engine = @import("engine.zig"); +pub const npy = @import("npy.zig"); +pub const wav = @import("wav.zig"); +pub const parity = @import("parity.zig"); + +pub const Engine = engine.Engine; +pub const Options = engine.Options; +pub const Song = engine.Song; + +test { + _ = config; + _ = prompt; + _ = wav; + _ = npy; +} diff --git a/zig/src/families/music3/music3_metal.zig b/zig/src/families/music3/music3_metal.zig new file mode 100644 index 00000000000..d69e67e03c9 --- /dev/null +++ b/zig/src/families/music3/music3_metal.zig @@ -0,0 +1,27 @@ +//! MiniMax Music 3 on Metal: music3.zig's family over TensorFold's own Metal runtime, for music3-generate. +pub const backend = "metal"; +pub const config = @import("config.zig"); +pub const common = @import("common.zig"); +pub const prompt = @import("prompt.zig"); +pub const weights = @import("weights.zig"); +pub const npy = @import("npy.zig"); +pub const wav = @import("wav.zig"); +pub const parity = @import("parity.zig"); +pub const gpu = @import("metal/gpu.zig"); +pub const kernels = @import("metal/kernels.zig"); +pub const ar = @import("metal/ar.zig"); +pub const dit = @import("metal/dit.zig"); +pub const dav = @import("metal/dav.zig"); +pub const engine = @import("metal/engine.zig"); + +pub const Engine = engine.Engine; +pub const Options = engine.Options; +pub const Song = engine.Song; + +test { + _ = config; + _ = prompt; + _ = wav; + _ = npy; + _ = kernels; +} diff --git a/zig/src/families/music3/npy.zig b/zig/src/families/music3/npy.zig new file mode 100644 index 00000000000..36e1e2cf6cb --- /dev/null +++ b/zig/src/families/music3/npy.zig @@ -0,0 +1,118 @@ +//! NumPy .npy files for the parity tools: little-endian f4 / f2 / i4 / i8 arrays in C order, version 1 headers. +const std = @import("std"); + +pub const DType = enum { f4, f2, i4, i8 }; + +pub const Array = struct { + dtype: DType, + shape: [4]usize, + rank: usize, + data: []align(8) u8, + + pub fn numel(a: Array) usize { + var n: usize = 1; + for (a.shape[0..a.rank]) |d| n *= d; + return n; + } + + pub fn deinit(a: Array, gpa: std.mem.Allocator) void { + gpa.free(a.data); + } + + /// The values as f32 (f4, f2, i4 or i8 converted); caller frees. + pub fn toF32(a: Array, gpa: std.mem.Allocator) ![]f32 { + const n = a.numel(); + const out = try gpa.alloc(f32, n); + for (out, 0..) |*o, i| o.* = switch (a.dtype) { + .f4 => @bitCast(std.mem.readInt(u32, a.data[i * 4 ..][0..4], .little)), + .f2 => @floatCast(@as(f16, @bitCast(std.mem.readInt(u16, a.data[i * 2 ..][0..2], .little)))), + .i4 => @floatFromInt(std.mem.readInt(i32, a.data[i * 4 ..][0..4], .little)), + .i8 => @floatFromInt(std.mem.readInt(i64, a.data[i * 8 ..][0..8], .little)), + }; + return out; + } + + /// The values as i32 (i4 or i8); caller frees. + pub fn toI32(a: Array, gpa: std.mem.Allocator) ![]i32 { + const n = a.numel(); + const out = try gpa.alloc(i32, n); + for (out, 0..) |*o, i| o.* = switch (a.dtype) { + .i4 => std.mem.readInt(i32, a.data[i * 4 ..][0..4], .little), + .i8 => @intCast(std.mem.readInt(i64, a.data[i * 8 ..][0..8], .little)), + else => return error.NotIntegers, + }; + return out; + } +}; + +pub fn read(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !Array { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(16 << 30)); + defer gpa.free(bytes); + if (bytes.len < 10 or !std.mem.eql(u8, bytes[0..6], "\x93NUMPY")) return error.NotNpy; + const major = bytes[6]; + var hlen: usize = undefined; + var off: usize = undefined; + if (major == 1) { + hlen = std.mem.readInt(u16, bytes[8..10], .little); + off = 10; + } else { + hlen = std.mem.readInt(u32, bytes[8..12], .little); + off = 12; + } + const header = bytes[off .. off + hlen]; + var a: Array = .{ .dtype = .f4, .shape = @splat(1), .rank = 0, .data = undefined }; + if (std.mem.indexOf(u8, header, "' 4, + .f2 => 2, + .i8 => 8, + }; + const body = bytes[off + hlen ..]; + if (body.len < a.numel() * esize) return error.ShortNpy; + a.data = try gpa.alignedAlloc(u8, .@"8", a.numel() * esize); + @memcpy(a.data, body[0 .. a.numel() * esize]); + return a; +} + +/// Writes f32 (or i32) values with the given shape. +pub fn write(gpa: std.mem.Allocator, io: std.Io, path: []const u8, comptime T: type, values: []const T, shape: []const usize) !void { + const descr = switch (T) { + f32 => " " @compileError("npy.write: f32 or i32"), + }; + var hb: [256]u8 = undefined; + var sb: [128]u8 = undefined; + var sl: usize = 0; + for (shape, 0..) |d, i| { + const w = try std.fmt.bufPrint(sb[sl..], "{d}{s}", .{ d, if (shape.len == 1 or i + 1 < shape.len) "," else "" }); + sl += w.len; + } + const dict = try std.fmt.bufPrint(&hb, "{{'descr': '{s}', 'fortran_order': False, 'shape': ({s}), }}", .{ descr, sb[0..sl] }); + var total = 10 + dict.len + 1; + const pad = (64 - total % 64) % 64; + total += pad; + var head: [512]u8 = undefined; + @memcpy(head[0..6], "\x93NUMPY"); + head[6] = 1; + head[7] = 0; + std.mem.writeInt(u16, head[8..10], @intCast(total - 10), .little); + @memcpy(head[10..][0..dict.len], dict); + @memset(head[10 + dict.len ..][0..pad], ' '); + head[total - 1] = '\n'; + const bytes = std.mem.sliceAsBytes(values); + const all = try gpa.alloc(u8, total + bytes.len); + defer gpa.free(all); + @memcpy(all[0..total], head[0..total]); + @memcpy(all[total..], bytes); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = all }); +} diff --git a/zig/src/families/music3/parity.zig b/zig/src/families/music3/parity.zig new file mode 100644 index 00000000000..57e3aec965b --- /dev/null +++ b/zig/src/families/music3/parity.zig @@ -0,0 +1,152 @@ +//! Parity dumps vs a ComfyUI reference run (REF) as .npy in OUT for tools/music3/parity.py. +const std = @import("std"); +const common = @import("common.zig"); +const npy = @import("npy.zig"); +const cfg = @import("config.zig"); + +pub const Opts = struct { + ar: ?[]const u8 = null, + dit: ?[]const u8 = null, + probe: ?[]const u8 = null, + dav: ?[]const u8 = null, + out: []const u8, + caption: []const u8 = "", + lyrics: []const u8 = "", + frames: usize = 0, + steps: usize = 30, + dit_cfg: f32 = 1.7, +}; + +fn path(a: std.mem.Allocator, dir: []const u8, name: []const u8) ![]const u8 { + return std.fs.path.join(a, &.{ dir, name }); +} + +fn bf16of(x: f32) u16 { + const u: u32 = @bitCast(x); + const r = u + 0x7FFF + ((u >> 16) & 1); + return @intCast(r >> 16); +} + +fn bf16to(x: u16) f32 { + return @bitCast(@as(u32, x) << 16); +} + +/// [C, L] (or [1, C, L]) -> [L, C]. +fn transpose(gpa: std.mem.Allocator, src: []const f32, C: usize, L: usize) ![]f32 { + const out = try gpa.alloc(f32, src.len); + for (0..C) |c| for (0..L) |t| { + out[t * C + c] = src[c * L + t]; + }; + return out; +} + +/// `e`: either backend's engine (ids, ar.run, dit().denoise, dav().decode). +pub fn run(gpa: std.mem.Allocator, io: std.Io, e: anytype, o: Opts) !u8 { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + std.Io.Dir.cwd().createDirPath(io, o.out) catch {}; + if (o.ar) |ref| { + const pr = try e.ids(o.caption, o.lyrics); + defer gpa.free(pr.cond); + defer gpa.free(pr.unc); + const js = try std.json.Stringify.valueAlloc(a, .{ .ids = pr.cond }, .{}); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try path(a, o.out, "ids.json"), .data = js }); + const codes_np = try npy.read(gpa, io, try path(a, ref, "codes.npy")); + defer codes_np.deinit(gpa); + const flat = try codes_np.toI32(a); + const nf = codes_np.shape[0]; + const codes: []const [8]i32 = @as([*]const [8]i32, @ptrCast(flat.ptr))[0..nf]; + var frames = if (o.frames > 0) o.frames else nf - 1; + frames = @min(frames, nf - 1); + var tr: common.Trace = .{}; + defer tr.c0.deinit(gpa); + defer tr.depth.deinit(gpa); + const t0 = common.nowNs(io); + const r = try e.ar.?.run(io, pr.cond, pr.unc, .{}, frames, false, 1, codes[0 .. frames + 1], &tr, null); + defer gpa.free(r.states); + const secs = common.ms(t0, common.nowNs(io)) / 1000; + const nlog = tr.c0.items.len / (2 * (cfg.c0_codes + 1)); + try npy.write(gpa, io, try path(a, o.out, "c0_logits.npy"), f32, tr.c0.items, &.{ nlog, 2, cfg.c0_codes + 1 }); + try npy.write(gpa, io, try path(a, o.out, "depth_logits.npy"), f32, tr.depth.items, &.{ nlog, 7, 2, cfg.codebook_size }); + const sf = try gpa.alloc(f32, r.states.len); + defer gpa.free(sf); + for (sf, r.states) |*d, s| d.* = bf16to(s); + try npy.write(gpa, io, try path(a, o.out, "states.npy"), f32, sf, &.{ r.frames, 8 * cfg.hidden }); + std.debug.print("[music3] parity ar: {d} forced frames, {d} kept, {d:.1}s\n", .{ nlog, r.frames, secs }); + } + if (o.dit) |ref| { + const hid = try npy.read(gpa, io, try path(a, ref, "hidden.npy")); + defer hid.deinit(gpa); + const hf = try hid.toF32(a); + const frames = hid.shape[0]; + const states = try a.alloc(u16, hf.len); + for (states, hf) |*d, x| d.* = bf16of(x); + const nz = try npy.read(gpa, io, try path(a, ref, "noise.npy")); + defer nz.deinit(gpa); + const L = nz.shape[nz.rank - 1]; + if (L != cfg.framesToLatents(frames)) return error.NoiseLength; + const noise = try transpose(a, try nz.toF32(a), 128, L); + var d = e.dit(); + const t0 = common.nowNs(io); + const lat = try d.denoise(states, frames, o.steps, o.dit_cfg, 0, noise, null, null); + defer gpa.free(lat); + const secs = common.ms(t0, common.nowNs(io)) / 1000; + const back = try transpose(a, lat, L, 128); // [L, 128] -> [128, L] + try npy.write(gpa, io, try path(a, o.out, "latent.npy"), f32, back, &.{ 1, 128, L }); + std.debug.print("[music3] parity dit: {d} latent rows, {d:.1}s\n", .{ L, secs }); + } + if (o.probe) |ref| { + const hid = try npy.read(gpa, io, try path(a, ref, "probe_hidden.npy")); + defer hid.deinit(gpa); + const hf = try hid.toF32(a); + const frames = hid.shape[0]; + const states = try a.alloc(u16, hf.len); + for (states, hf) |*d, x| d.* = bf16of(x); + const px = try npy.read(gpa, io, try path(a, ref, "probe_x.npy")); + defer px.deinit(gpa); + const L = px.shape[px.rank - 1]; + if (L != cfg.framesToLatents(frames)) return error.ProbeLength; + // the reference casts x to the DiT dtype first + const xs = try transpose(a, try px.toF32(a), 128, L); + for (xs) |*v| v.* = @floatCast(@as(f16, @floatCast(v.*))); + var d = e.dit(); + for ([_]f32{ 1.0, 0.5, 0.1 }) |sigma| { + for ([_]f32{ 1.0, 0.0 }, [_][]const u8{ "cond", "uncond" }) |g, name| { + const out = try d.denoise(states, frames, 1, 1.0, 0, xs, .{ .cfg = g, .t = 1.0 - sigma }, null); + defer gpa.free(out); + const back = try transpose(a, out, L, 128); + const fname = try std.fmt.allocPrint(a, "probe_{s}_{d:.1}.npy", .{ name, sigma }); + try npy.write(gpa, io, try path(a, o.out, fname), f32, back, &.{ 128, L }); + } + } + std.debug.print("[music3] parity probe: {d} latent rows\n", .{L}); + } + if (o.dav) |ref| { + var v = e.dav(); + const lp = try path(a, ref, "latent.npy"); + if (npy.read(gpa, io, lp)) |lat| { + defer lat.deinit(gpa); + const L = lat.shape[lat.rank - 1]; + const x = try transpose(a, try lat.toF32(a), 128, L); + const t0 = common.nowNs(io); + const audio = try v.decode(x, L); + defer gpa.free(audio); + const secs = common.ms(t0, common.nowNs(io)) / 1000; + try npy.write(gpa, io, try path(a, o.out, "audio.npy"), f32, audio, &.{ 2, L * 512 }); + std.debug.print("[music3] parity dav: {d} latent rows, {d:.2}s\n", .{ L, secs }); + } else |_| {} + if (npy.read(gpa, io, try path(a, ref, "probe_latent.npy"))) |lat| { + defer lat.deinit(gpa); + const L = lat.shape[lat.rank - 1]; + const x = try transpose(a, try lat.toF32(a), 128, L); + v.o.chunk = L; + v.o.context = 0; + v.o.level = false; + const audio = try v.decode(x, L); + defer gpa.free(audio); + try npy.write(gpa, io, try path(a, o.out, "probe_dav.npy"), f32, audio, &.{ 2, L * 512 }); + } else |_| {} + } + return 0; +} diff --git a/zig/src/families/music3/prompt.zig b/zig/src/families/music3/prompt.zig new file mode 100644 index 00000000000..e06aeb5edc5 --- /dev/null +++ b/zig/src/families/music3/prompt.zig @@ -0,0 +1,349 @@ +//! Caption and lyrics to the AR's prompt ids, as ComfyUI's comfy/ldm/minimax_music/prompt.py builds them, by hand. +const std = @import("std"); +const core = @import("core"); + +const Tokenizer = core.tokenizer.Tokenizer; +const List = std.ArrayList(u8); + +pub const audio_cfg: u32 = 151654; +pub const specials = [_]struct { []const u8, u32 }{ + .{ "<|im_start|>", 151644 }, .{ "<|im_end|>", 151645 }, .{ "<|audio_cfg|>", 151654 }, + .{ "<|audio_start|>", 151669 }, .{ "<|audio_end|>", 151670 }, .{ "<|caption_start|>", 151671 }, + .{ "<|caption_end|>", 151672 }, .{ "<|lyrics_start|>", 151673 }, .{ "<|lyrics_end|>", 151674 }, +}; + +/// Python's str.isspace(). +fn isSpaceCp(cp: u21) bool { + return (cp >= 0x9 and cp <= 0xD) or (cp >= 0x1C and cp <= 0x20) or cp == 0x85 or cp == 0xA0 or cp == 0x1680 or + (cp >= 0x2000 and cp <= 0x200A) or cp == 0x2028 or cp == 0x2029 or cp == 0x202F or cp == 0x205F or cp == 0x3000; +} + +/// The code point at s[i] and its byte length (invalid bytes read as one byte, never space). +fn at(s: []const u8, i: usize) struct { cp: u21, n: usize } { + const n = std.unicode.utf8ByteSequenceLength(s[i]) catch return .{ .cp = 0xFFFD, .n = 1 }; + if (i + n > s.len) return .{ .cp = 0xFFFD, .n = 1 }; + const cp = std.unicode.utf8Decode(s[i..][0..n]) catch return .{ .cp = 0xFFFD, .n = 1 }; + return .{ .cp = cp, .n = n }; +} + +fn spaceLen(s: []const u8, i: usize) usize { + if (i >= s.len) return 0; + const c = at(s, i); + return if (isSpaceCp(c.cp)) c.n else 0; +} + +/// End of the run of white space at i. +fn skipSpace(s: []const u8, from: usize) usize { + var i = from; + while (true) { + const n = spaceLen(s, i); + if (n == 0) return i; + i += n; + } +} + +fn strip(s: []const u8) []const u8 { + const a = skipSpace(s, 0); + var b = s.len; + while (b > a) { + var c = b - 1; + while (c > a and s[c] & 0xC0 == 0x80) c -= 1; + if (spaceLen(s, c) == 0) break; + b = c; + } + return s[a..b]; +} + +fn rstrip(s: []const u8) []const u8 { + var b = s.len; + while (b > 0) { + var c = b - 1; + while (c > 0 and s[c] & 0xC0 == 0x80) c -= 1; + if (spaceLen(s, c) == 0) break; + b = c; + } + return s[0..b]; +} + +/// `<\|([^|]*)\|>` -> "a is b" (inner split once on white space) or the stripped inner. +fn tagWords(a: std.mem.Allocator, text: []const u8, out: *List) !void { + var i: usize = 0; + while (i < text.len) { + if (std.mem.startsWith(u8, text[i..], "<|")) { + var j = i + 2; + while (j < text.len and text[j] != '|') j += 1; + if (j + 1 < text.len and text[j + 1] == '>') { + const inner = strip(text[i + 2 .. j]); + var k: usize = 0; + while (k < inner.len and spaceLen(inner, k) == 0) k += at(inner, k).n; + if (k < inner.len) { + const rest = inner[skipSpace(inner, k)..]; + try out.appendSlice(a, inner[0..k]); + try out.appendSlice(a, " is "); + try out.appendSlice(a, rest); + } else try out.appendSlice(a, inner); + i = j + 2; + continue; + } + } + try out.append(a, text[i]); + i += 1; + } +} + +/// Python's str.splitlines() boundaries: \n \r \r\n \v \f \x1c \x1d \x1e \x85 
 
. +fn lineBreak(s: []const u8, i: usize) usize { + switch (s[i]) { + '\n', 0x0B, 0x0C, 0x1C, 0x1D, 0x1E => return 1, + '\r' => return if (i + 1 < s.len and s[i + 1] == '\n') 2 else 1, + else => {}, + } + const c = at(s, i); + return if (c.cp == 0x85 or c.cp == 0x2028 or c.cp == 0x2029) c.n else 0; +} + +/// One line without its heading marks, bullet, bold and italic stars, right-stripped. +fn plainLine(a: std.mem.Allocator, line0: []const u8, out: *List) !void { + var line = line0; + // ^\s{0,3}#{1,6}\s+ + { + var i: usize = 0; + var ws: usize = 0; + while (ws < 3) : (ws += 1) { + const n = spaceLen(line, i); + if (n == 0) break; + i += n; + } + var h: usize = 0; + while (i + h < line.len and line[i + h] == '#') h += 1; + if (h >= 1 and h <= 6 and spaceLen(line, i + h) > 0) line = line[skipSpace(line, i + h)..]; + } + // ^\s*[*+-]\s+ + { + const i = skipSpace(line, 0); + if (i < line.len and (line[i] == '*' or line[i] == '+' or line[i] == '-') and spaceLen(line, i + 1) > 0) line = line[skipSpace(line, i + 1)..]; + } + var cur: List = .empty; + try cur.appendSlice(a, line); + // while "**" in line: \*\*([^*]+)\*\* -> \1 until nothing changes + while (std.mem.indexOf(u8, cur.items, "**") != null) { + var next: List = .empty; + var i: usize = 0; + var changed = false; + const s = cur.items; + while (i < s.len) { + if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') { + var j = i + 2; + while (j < s.len and s[j] != '*') j += 1; + if (j > i + 2 and j + 1 < s.len and s[j + 1] == '*') { + try next.appendSlice(a, s[i + 2 .. j]); + i = j + 2; + changed = true; + continue; + } + } + try next.append(a, s[i]); + i += 1; + } + cur = next; + if (!changed) break; + } + // (? \1 + { + const s = cur.items; + var i: usize = 0; + while (i < s.len) { + if (s[i] == '*' and (i == 0 or s[i - 1] != '*')) { + var j = i + 1; + while (j < s.len and s[j] != '*' and s[j] != '\n') j += 1; + if (j > i + 1 and j < s.len and s[j] == '*' and (j + 1 >= s.len or s[j + 1] != '*')) { + try out.appendSlice(a, s[i + 1 .. j]); + i = j + 1; + continue; + } + } + try out.append(a, s[i]); + i += 1; + } + } +} + +fn isDash(c: u8) bool { + return c == '-' or c == '*' or c == '_'; +} + +/// re.sub(r"^\s*[-*_]{3,}\s*$", "", text, flags=re.MULTILINE). +fn dropRules(a: std.mem.Allocator, s: []const u8, out: *List) !void { + var i: usize = 0; + while (i <= s.len) { + const line_start = i == 0 or s[i - 1] == '\n'; + if (line_start) { + const k = skipSpace(s, i); + var r: usize = 0; + while (k + r < s.len and isDash(s[k + r])) r += 1; + if (r >= 3) { + const m = k + r; + const e = skipSpace(s, m); + // greedy \s* then $ (end, or before a newline): the last such position in [m, e] + var p = e; + var found = false; + while (true) { + if (p == s.len or s[p] == '\n') { + found = true; + break; + } + if (p == m) break; + p -= 1; + while (p > m and s[p] & 0xC0 == 0x80) p -= 1; + } + if (found) { + i = p; // the next search starts where this match ended (a match is never empty) + continue; + } + } + } + if (i == s.len) break; + try out.append(a, s[i]); + i += 1; + } +} + +fn replaceAll(a: std.mem.Allocator, s: []const u8, from: []const u8, to: []const u8) ![]u8 { + var out: List = .empty; + var i: usize = 0; + while (i < s.len) { + if (std.mem.startsWith(u8, s[i..], from)) { + try out.appendSlice(a, to); + i += from.len; + } else { + try out.append(a, s[i]); + i += 1; + } + } + return out.toOwnedSlice(a); +} + +/// clean_caption: tags to words, markdown off, rules dropped, bullets and 4-space indents off, blank lines merged. +pub fn cleanCaption(a: std.mem.Allocator, caption: []const u8) ![]u8 { + var tagged: List = .empty; + try tagWords(a, caption, &tagged); + var joined: List = .empty; + const t = tagged.items; + var i: usize = 0; + var first = true; + while (i < t.len) { + var j = i; + while (j < t.len and lineBreak(t, j) == 0) j += 1; + if (!first) try joined.append(a, '\n'); + first = false; + var line: List = .empty; + try plainLine(a, t[i..j], &line); + try joined.appendSlice(a, rstrip(line.items)); + if (j >= t.len) break; + i = j + lineBreak(t, j); + } + var ruled: List = .empty; + try dropRules(a, joined.items, &ruled); + const b = try replaceAll(a, ruled.items, "\u{2022} ", ""); + const c = try replaceAll(a, b, " ", ""); + var out: List = .empty; + var k: usize = 0; + while (k < c.len) { + if (c[k] == '\n') { + var e = k; + while (e < c.len and c[e] == '\n') e += 1; + try out.append(a, '\n'); + k = e; + continue; + } + try out.append(a, c[k]); + k += 1; + } + return out.toOwnedSlice(a); +} + +/// normalize_lyrics: split on `\s*(\[[^\]]+\])\s*`, tags lower-cased (ASCII), pieces on lines, " ^ " a line break. +pub fn normalizeLyrics(a: std.mem.Allocator, lyrics: []const u8) ![]u8 { + var parts: std.ArrayList([]const u8) = .empty; + var last: usize = 0; + var i: usize = 0; + while (i < lyrics.len) { + const k = skipSpace(lyrics, i); + if (k < lyrics.len and lyrics[k] == '[') { + var j = k + 1; + while (j < lyrics.len and lyrics[j] != ']') j += 1; + if (j > k + 1 and j < lyrics.len) { + try parts.append(a, lyrics[last..i]); + try parts.append(a, lyrics[k .. j + 1]); + const e = skipSpace(lyrics, j + 1); + last = e; + i = e; + continue; + } + } + i += at(lyrics, i).n; + } + try parts.append(a, lyrics[last..]); + var joined: List = .empty; + var n: usize = 0; + for (parts.items) |p| { + if (p.len == 0) continue; + if (n > 0) try joined.append(a, '\n'); + n += 1; + if (p[0] == '[') { + for (p) |c| try joined.append(a, std.ascii.toLower(c)); + } else try joined.appendSlice(a, p); + } + const body = try replaceAll(a, joined.items, " ^ ", "\n"); + return std.mem.concat(a, u8, &.{ "[start]\n", body }); +} + +pub fn promptText(a: std.mem.Allocator, caption: []const u8, lyrics: []const u8) ![]u8 { + return std.mem.concat(a, u8, &.{ "<|im_start|><|caption_start|>", try cleanCaption(a, caption), "<|caption_end|><|lyrics_start|>", try normalizeLyrics(a, lyrics), "<|lyrics_end|><|im_end|><|audio_start|>" }); +} + +/// The special tokens must have the reference's ids. +pub fn checkTokenizer(tok: *const Tokenizer) !void { + for (specials) |s| { + const id = tok.specialTokenId(s[0]) orelse return error.TokenizerMismatch; + if (id != s[1]) { + std.log.err("music3: tokenizer {s} is {d}, not {d}", .{ s[0], id, s[1] }); + return error.TokenizerMismatch; + } + } +} + +/// The conditional prompt's ids (caller frees with gpa). +pub fn encode(gpa: std.mem.Allocator, tok: *const Tokenizer, caption: []const u8, lyrics: []const u8) ![]u32 { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const text = try promptText(arena.allocator(), caption, lyrics); + const ids = try tok.encode(gpa, text); + if (ids.len > 5000) { + gpa.free(ids); + return error.PromptTooLong; + } + if (ids.len < 4) { + gpa.free(ids); + return error.PromptTooShort; + } + return ids; +} + +/// The unconditional row: first token, audio_cfg for the middle, the last two. +pub fn unconditional(gpa: std.mem.Allocator, ids: []const u32) ![]u32 { + const out = try gpa.dupe(u32, ids); + for (out[1 .. out.len - 2]) |*x| x.* = audio_cfg; + return out; +} + +test "caption and lyrics cleanup" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqualStrings("tempo is 92 bpm\nbold and it", try cleanCaption(a, "<| tempo 92 bpm |>\n\n## **bold** and *it*")); + try std.testing.expectEqualStrings("a\nb", try cleanCaption(a, "a\n---\nb")); + try std.testing.expectEqualStrings("item one\nx", try cleanCaption(a, "- item one \n x")); + try std.testing.expectEqualStrings("[start]\n[verse]\nhello world\n[chorus]\nla la", try normalizeLyrics(a, "[Verse] hello world\n\n[CHORUS]\nla la")); + try std.testing.expectEqualStrings("[start]\nline one\nline two", try normalizeLyrics(a, "line one ^ line two")); +} diff --git a/zig/src/families/music3/store.zig b/zig/src/families/music3/store.zig new file mode 100644 index 00000000000..33976a5e9e8 --- /dev/null +++ b/zig/src/families/music3/store.zig @@ -0,0 +1,46 @@ +//! The CUDA weight store weights.zig's loaders fill: device buffers for the engine's life, one staging buffer. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const Store = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: usize = 0, + d: *const cuda.Driver, + staging: ?cuda.DeviceBuffer = null, + + const staging_bytes: usize = 24576 * 4096 * 2; + + pub fn alloc(s: *Store, bytes: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(s.d, @max(bytes, 256)); + try s.bufs.append(s.gpa, b); + s.bytes += bytes; + return b.ptr; + } + + pub fn upload(s: *Store, bytes: []const u8) !u64 { + const p = try s.alloc(bytes.len); + var b = s.bufs.items[s.bufs.items.len - 1]; + try b.upload(0, bytes); + return p; + } + + /// `bytes` in the staging buffer (made on first use), for the quantizer to read. + pub fn stage(s: *Store, bytes: []const u8) !u64 { + if (bytes.len > staging_bytes) return error.StagingTooSmall; + if (s.staging == null) s.staging = try cuda.DeviceBuffer.alloc(s.d, staging_bytes); + try s.staging.?.upload(0, bytes); + return s.staging.?.ptr; + } + + pub fn unstage(s: *Store) void { + if (s.staging) |*b| b.free(); + s.staging = null; + } + + pub fn deinit(s: *Store) void { + s.unstage(); + for (s.bufs.items) |*b| b.free(); + s.bufs.deinit(s.gpa); + } +}; diff --git a/zig/src/families/music3/wav.zig b/zig/src/families/music3/wav.zig new file mode 100644 index 00000000000..1c640b15935 --- /dev/null +++ b/zig/src/families/music3/wav.zig @@ -0,0 +1,35 @@ +//! 16-bit PCM WAV out: channels [C, N] float audio, round(clamp(x, -1, 1) 32767), interleaved. +const std = @import("std"); + +pub fn encode(gpa: std.mem.Allocator, audio: []const f32, channels: usize, rate: u32) ![]u8 { + const n = audio.len / channels; + const data_len = n * channels * 2; + const out = try gpa.alloc(u8, 44 + data_len); + @memcpy(out[0..4], "RIFF"); + std.mem.writeInt(u32, out[4..8], @intCast(36 + data_len), .little); + @memcpy(out[8..16], "WAVEfmt "); + std.mem.writeInt(u32, out[16..20], 16, .little); + std.mem.writeInt(u16, out[20..22], 1, .little); + std.mem.writeInt(u16, out[22..24], @intCast(channels), .little); + std.mem.writeInt(u32, out[24..28], rate, .little); + std.mem.writeInt(u32, out[28..32], rate * @as(u32, @intCast(channels)) * 2, .little); + std.mem.writeInt(u16, out[32..34], @intCast(channels * 2), .little); + std.mem.writeInt(u16, out[34..36], 16, .little); + @memcpy(out[36..40], "data"); + std.mem.writeInt(u32, out[40..44], @intCast(data_len), .little); + for (0..n) |i| for (0..channels) |c| { + const v: i16 = @intFromFloat(@round(std.math.clamp(audio[c * n + i], -1.0, 1.0) * 32767.0)); + std.mem.writeInt(i16, out[44 + (i * channels + c) * 2 ..][0..2], v, .little); + }; + return out; +} + +test "a stereo header and samples" { + const gpa = std.testing.allocator; + const b = try encode(gpa, &.{ 0.0, 1.0, -1.0, 0.5 }, 2, 44100); + defer gpa.free(b); + try std.testing.expectEqual(@as(usize, 44 + 8), b.len); + try std.testing.expectEqual(@as(i16, 0), std.mem.readInt(i16, b[44..46], .little)); + try std.testing.expectEqual(@as(i16, -32767), std.mem.readInt(i16, b[46..48], .little)); + try std.testing.expectEqual(@as(i16, 32767), std.mem.readInt(i16, b[48..50], .little)); +} diff --git a/zig/src/families/music3/weights.zig b/zig/src/families/music3/weights.zig new file mode 100644 index 00000000000..22a646002b5 --- /dev/null +++ b/zig/src/families/music3/weights.zig @@ -0,0 +1,346 @@ +//! The three Comfy-Org files into any store with alloc / upload / stage / unstage: the AR (bf16 or int8), DiT, DAV. +const std = @import("std"); +const builtin = @import("builtin"); +const core = @import("core"); +const cfg = @import("config.zig"); + +const st = core.safetensors; +const H = cfg.hidden; + +pub const text_encoder = "text_encoders/minimax_music3_text_encoder_pruned_bf16.safetensors"; +pub const diffusion = "diffusion_models/minimax_music3_dit_fp16.safetensors"; +pub const decoder = "vae/minimax_music3_dav.safetensors"; + +pub const Format = enum { bf16, int8 }; + +/// A projection W [n, k]: bf16 rows, or int8 rows with fp32 scales (sc != 0). +pub const Mat = struct { w: u64, sc: u64 = 0, n: usize, k: usize, group: usize = 0 }; // group: inputs a scale (0: a row) + +pub const BodyLayer = struct { in_norm: u64, post_norm: u64, q_norm: u64, k_norm: u64, qkv: Mat, o: Mat, gate_up: Mat, down: Mat }; +pub const DepthLayer = struct { in_norm: u64, post_norm: u64, qkv: Mat, o: Mat, gate_up: Mat, down: Mat }; + +pub const Ar = struct { + format: Format, + embed_prefill: u64, // [151675, 4096] + embed_audio: u64, // [16384, 4096] + extra: u64, // [7168, 4096] + body: [cfg.layers]BodyLayer, + norm: u64, + lm_head: Mat, // [16385, 4096] + projection: Mat, + pos_emb: u64, // [16, 4096] + depth: [cfg.depth_layers]DepthLayer, + depth_norm: u64, + heads: [cfg.codebooks - 1]Mat, // [1024, 4096] + inv_freq: u64, // f32 [64] + tokenizer_json: []u8, +}; + +pub const DitBlock = struct { pre_g: u64, pre_b: u64, ff_g: u64, ff_b: u64, qkv: u64, out: u64, ff_in: u64, ff_in_b: u64, ff_out: u64, ff_out_b: u64 }; + +pub const Dit = struct { + cond_w8: [8]f32, // softmax(cond_layer_logits) rounded to fp16 + cond_scale: f32, + cond_conv: u64, // fp16 [2048, 3 * 4096] (taps outer) + cond_bias: u64, // fp16 [2048] + pre: u64, // [2304, 2304] + post: u64, // [128, 128] + time_features: u64, // [128] + time_in: u64, + time_in_b: u64, + time_out: u64, + time_out_b: u64, + project_in: u64, // [2048, 2304] + project_out: u64, // [128, 2048] + inv_freq: [16]f32, + blocks: [cfg.dit_blocks]DitBlock, +}; + +/// A DAV conv: taps [K][Cout][Cin] fp32, bias [Cout]; transposed convs keep [K][Cout][Cin] of W[Cin][Cout][K]. +pub const Conv = struct { w: u64, b: u64, cin: usize, cout: usize, k: usize }; +pub const ResUnit = struct { a1: u64, c1: Conv, a2: u64, c2: Conv, dilation: usize }; +pub const DavBlock = struct { alpha: u64, up: Conv, stride: usize, res: [3]ResUnit }; +pub const Dav = struct { in_proj: Conv, conv0: Conv, blocks: [4]DavBlock, alpha_out: u64, conv_out: Conv }; + +fn need(f: *const st.File, name: []const u8, dtype: st.DType, shape: []const usize) !st.Tensor { + const t = f.get(name) orelse { + std.log.err("music3: {s} has no {s}", .{ f.path, name }); + return error.MissingTensor; + }; + if (!t.is(dtype, shape)) { + std.log.err("music3: {s} is {s} {any}, expected {s} {any}", .{ name, @tagName(t.dtype), t.shape[0..t.rank], @tagName(dtype), shape }); + return error.BadTensor; + } + return t; +} + +/// Drop a tensor's pages from the page cache once it is on the device (unified memory holds both otherwise). +fn drop(f: *const st.File, name: []const u8) void { + const e = f.names.get(name) orelse return; + if (builtin.os.tag == .linux) { + _ = std.os.linux.fadvise(f.file.handle, @intCast(f.data + e.begin), @intCast(e.end - e.begin), std.os.linux.POSIX_FADV.DONTNEED); + } +} + +/// The quantizer the AR loader calls for int8 projections: bf16 rows staged on the device, int8 + scales out. +pub const Quantizer = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, src: u64, n: usize, k: usize, group: usize, q: u64, sc: u64) anyerror!void, +}; + +fn ArLoader(comptime S: type) type { + return struct { + s: S, + f: *const st.File, + format: Format, + quant: ?Quantizer, + + const L = @This(); + + fn plain(l: *L, name: []const u8, shape: []const usize) !u64 { + const t = try need(l.f, name, .bf16, shape); + const p = try l.s.upload(t.bytes); + drop(l.f, name); + return p; + } + + fn mat(l: *L, name: []const u8, n: usize, k: usize) !Mat { + return l.matG(name, n, k, 0); + } + + /// `group` inputs a scale (int8 only; 0 is a scale a row). + fn matG(l: *L, name: []const u8, n: usize, k: usize, group: usize) !Mat { + const t = try need(l.f, name, .bf16, &.{ n, k }); + defer drop(l.f, name); + if (l.format == .bf16) return .{ .w = try l.s.upload(t.bytes), .n = n, .k = k }; + const src = try l.s.stage(t.bytes); + const q = try l.s.alloc(n * k); + const sc = try l.s.alloc(n * (if (group > 0) k / group else 1) * 4); + try l.quant.?.f(l.quant.?.ctx, src, n, k, group, q, sc); + return .{ .w = q, .sc = sc, .n = n, .k = k, .group = group }; + } + }; +} + +/// `depth_group`: int8 groups of that many inputs a scale for the depth decoder and its heads (0: a scale a row). +pub fn loadAr(gpa: std.mem.Allocator, io: std.Io, s: anytype, dir: []const u8, format: Format, depth_group: usize, quant: ?Quantizer, log: bool) !Ar { + var nb: [8][160]u8 = undefined; + const path = try std.fs.path.join(gpa, &.{ dir, text_encoder }); + defer gpa.free(path); + var f = try st.File.open(gpa, io, path); + defer f.close(io); + var a: Ar = undefined; + a.format = format; + const tj = f.get("tokenizer_json") orelse return error.NoTokenizer; + a.tokenizer_json = try gpa.dupe(u8, tj.bytes); + defer s.unstage(); + var l: ArLoader(@TypeOf(s)) = .{ .s = s, .f = &f, .format = format, .quant = quant }; + a.embed_prefill = try l.plain("model.embed_tokens_prefill.weight", &.{ cfg.prompt_vocab, H }); + a.embed_audio = try l.plain("model.embed_tokens_audio.weight", &.{ cfg.c0_codes, H }); + a.extra = try l.plain("model.audio_extra_embedding.weight", &.{ cfg.codebook_size * (cfg.codebooks - 1), H }); + for (0..cfg.layers) |i| { + const p = "model.layers.{d}."; + a.body[i] = .{ + .in_norm = try l.plain(try std.fmt.bufPrint(&nb[0], p ++ "input_layernorm.weight", .{i}), &.{H}), + .post_norm = try l.plain(try std.fmt.bufPrint(&nb[1], p ++ "post_attention_layernorm.weight", .{i}), &.{H}), + .q_norm = try l.plain(try std.fmt.bufPrint(&nb[2], p ++ "self_attn.q_norm.weight", .{i}), &.{cfg.head_dim}), + .k_norm = try l.plain(try std.fmt.bufPrint(&nb[3], p ++ "self_attn.k_norm.weight", .{i}), &.{cfg.head_dim}), + .qkv = try l.mat(try std.fmt.bufPrint(&nb[4], p ++ "self_attn.qkv_proj.weight", .{i}), cfg.qkv_width, H), + .o = try l.mat(try std.fmt.bufPrint(&nb[5], p ++ "self_attn.o_proj.weight", .{i}), H, H), + .gate_up = try l.mat(try std.fmt.bufPrint(&nb[6], p ++ "mlp.gate_up_proj.weight", .{i}), 2 * cfg.mlp, H), + .down = try l.mat(try std.fmt.bufPrint(&nb[7], p ++ "mlp.down_proj.weight", .{i}), H, cfg.mlp), + }; + if (log and i % 9 == 8) std.log.info("music3: AR layer {d} loaded ({d:.1} GB on the device)", .{ i, @as(f64, @floatFromInt(s.bytes)) / 1e9 }); + } + a.norm = try l.plain("model.norm.weight", &.{H}); + a.lm_head = try l.mat("model.lm_head_pruned.weight", cfg.c0_codes + 1, H); + a.projection = try l.matG("model.audio_decoder.projection.weight", H, H, depth_group); + a.pos_emb = try l.plain("model.audio_decoder.pos_embedding.weight", &.{ 16, H }); + for (0..cfg.depth_layers) |i| { + const p = "model.audio_decoder.layers.{d}."; + a.depth[i] = .{ + .in_norm = try l.plain(try std.fmt.bufPrint(&nb[0], p ++ "input_layernorm.weight", .{i}), &.{H}), + .post_norm = try l.plain(try std.fmt.bufPrint(&nb[1], p ++ "post_attention_layernorm.weight", .{i}), &.{H}), + .qkv = try l.matG(try std.fmt.bufPrint(&nb[2], p ++ "self_attn.qkv_proj.weight", .{i}), 3 * H, H, depth_group), + .o = try l.matG(try std.fmt.bufPrint(&nb[3], p ++ "self_attn.o_proj.weight", .{i}), H, H, depth_group), + .gate_up = try l.matG(try std.fmt.bufPrint(&nb[4], p ++ "mlp.gate_up_proj.weight", .{i}), 2 * cfg.depth_mlp, H, depth_group), + .down = try l.matG(try std.fmt.bufPrint(&nb[5], p ++ "mlp.down_proj.weight", .{i}), H, cfg.depth_mlp, depth_group), + }; + } + a.depth_norm = try l.plain("model.audio_decoder.norm.weight", &.{H}); + for (0..cfg.codebooks - 1) |i| a.heads[i] = try l.matG(try std.fmt.bufPrint(&nb[0], "model.audio_decoder.audio_heads.{d}.weight", .{i}), cfg.codebook_size, H, depth_group); + // rope: inv_freq_i = 1 / theta^(2i / 128) in float32, as ComfyUI's precompute_freqs_cis + var inv: [64]f32 = undefined; + for (&inv, 0..) |*v, i| v.* = 1.0 / std.math.pow(f32, cfg.rope_theta, @as(f32, @floatFromInt(2 * i)) / 128.0); + a.inv_freq = try s.upload(std.mem.sliceAsBytes(&inv)); + if (log) std.log.info("music3: AR weights on the device: {d:.2} GB ({s})", .{ @as(f64, @floatFromInt(s.bytes)) / 1e9, @tagName(format) }); + return a; +} + +fn f16v(t: st.Tensor, i: usize) f32 { + return @floatCast(@as(f16, @bitCast(std.mem.readInt(u16, t.bytes[i * 2 ..][0..2], .little)))); +} + +pub fn loadDit(gpa: std.mem.Allocator, io: std.Io, s: anytype, dir: []const u8, log: bool) !Dit { + const path = try std.fs.path.join(gpa, &.{ dir, diffusion }); + defer gpa.free(path); + var f = try st.File.open(gpa, io, path); + defer f.close(io); + var d: Dit = undefined; + const P = struct { + fn up(sto: anytype, file: *const st.File, name: []const u8, shape: []const usize) !u64 { + const t = try need(file, name, .f16, shape); + const p = try sto.upload(t.bytes); + drop(file, name); + return p; + } + }; + { + const t = try need(&f, "cond_layer_logits", .f16, &.{8}); + var m: f32 = -std.math.inf(f32); + var v: [8]f32 = undefined; + for (&v, 0..) |*x, i| { + x.* = f16v(t, i); + m = @max(m, x.*); + } + var sum: f32 = 0; + for (&v) |*x| { + x.* = @exp(x.* - m); + sum += x.*; + } + for (&d.cond_w8, v) |*o, x| o.* = @floatCast(@as(f16, @floatCast(x / sum))); + const sc = try need(&f, "cond_layer_scale", .f16, &.{1}); + d.cond_scale = f16v(sc, 0); + } + { + // latent_conditioners.0: [2048, 4096, 3] -> [2048][3][4096] for the im2col GEMM + const t = try need(&f, "latent_conditioners.0.weight", .f16, &.{ 2048, 4096, 3 }); + const host = try gpa.alloc(u16, 2048 * 3 * 4096); + defer gpa.free(host); + const src = std.mem.bytesAsSlice(u16, t.bytes); + for (0..2048) |o| for (0..4096) |c| for (0..3) |k| { + host[(o * 3 + k) * 4096 + c] = std.mem.littleToNative(u16, src[(o * 4096 + c) * 3 + k]); + }; + d.cond_conv = try s.upload(std.mem.sliceAsBytes(host)); + drop(&f, "latent_conditioners.0.weight"); + d.cond_bias = try P.up(s, &f, "latent_conditioners.0.bias", &.{2048}); + } + const pre = "diffusion_transformer."; + d.pre = try P.up(s, &f, pre ++ "preprocess_conv.weight", &.{ 2304, 2304, 1 }); + d.post = try P.up(s, &f, pre ++ "postprocess_conv.weight", &.{ 128, 128, 1 }); + d.time_features = try P.up(s, &f, pre ++ "timestep_features.weight", &.{ 128, 1 }); + d.time_in = try P.up(s, &f, pre ++ "to_timestep_embed.0.weight", &.{ 2048, 256 }); + d.time_in_b = try P.up(s, &f, pre ++ "to_timestep_embed.0.bias", &.{2048}); + d.time_out = try P.up(s, &f, pre ++ "to_timestep_embed.2.weight", &.{ 2048, 2048 }); + d.time_out_b = try P.up(s, &f, pre ++ "to_timestep_embed.2.bias", &.{2048}); + d.project_in = try P.up(s, &f, pre ++ "transformer.project_in.weight", &.{ 2048, 2304 }); + d.project_out = try P.up(s, &f, pre ++ "transformer.project_out.weight", &.{ 128, 2048 }); + { + const t = try need(&f, pre ++ "transformer.rotary_pos_emb.inv_freq", .f16, &.{16}); + for (&d.inv_freq, 0..) |*v, i| v.* = f16v(t, i); + } + var nb: [10][160]u8 = undefined; + for (0..cfg.dit_blocks) |i| { + const p = pre ++ "transformer.layers.{d}."; + d.blocks[i] = .{ + .pre_g = try P.up(s, &f, try std.fmt.bufPrint(&nb[0], p ++ "pre_norm.gamma", .{i}), &.{2048}), + .pre_b = try P.up(s, &f, try std.fmt.bufPrint(&nb[1], p ++ "pre_norm.beta", .{i}), &.{2048}), + .ff_g = try P.up(s, &f, try std.fmt.bufPrint(&nb[2], p ++ "ff_norm.gamma", .{i}), &.{2048}), + .ff_b = try P.up(s, &f, try std.fmt.bufPrint(&nb[3], p ++ "ff_norm.beta", .{i}), &.{2048}), + .qkv = try P.up(s, &f, try std.fmt.bufPrint(&nb[4], p ++ "self_attn.to_qkv.weight", .{i}), &.{ 6144, 2048 }), + .out = try P.up(s, &f, try std.fmt.bufPrint(&nb[5], p ++ "self_attn.to_out.weight", .{i}), &.{ 2048, 2048 }), + .ff_in = try P.up(s, &f, try std.fmt.bufPrint(&nb[6], p ++ "ff.ff.0.proj.weight", .{i}), &.{ 16384, 2048 }), + .ff_in_b = try P.up(s, &f, try std.fmt.bufPrint(&nb[7], p ++ "ff.ff.0.proj.bias", .{i}), &.{16384}), + .ff_out = try P.up(s, &f, try std.fmt.bufPrint(&nb[8], p ++ "ff.ff.2.weight", .{i}), &.{ 2048, 8192 }), + .ff_out_b = try P.up(s, &f, try std.fmt.bufPrint(&nb[9], p ++ "ff.ff.2.bias", .{i}), &.{2048}), + }; + } + if (log) std.log.info("music3: DiT on the device (fp16)", .{}); + return d; +} + +/// A weight-normed conv: w = g v / |v| over dims 1, 2 (f64), repacked to [K][Cout][Cin]; transposed v is [I, O, K]. +fn davConv(gpa: std.mem.Allocator, s: anytype, f: *const st.File, base: []const u8, transposed: bool, normed: bool) !Conv { + var nb: [3][200]u8 = undefined; + const vname = try std.fmt.bufPrint(&nb[0], "{s}.{s}", .{ base, if (normed) "weight_v" else "weight" }); + const v = f.get(vname) orelse { + std.log.err("music3: DAV has no {s}", .{vname}); + return error.MissingTensor; + }; + if (v.dtype != .f32 or v.rank != 3) return error.BadTensor; + const d0 = v.shape[0]; + const d1 = v.shape[1]; + const K = v.shape[2]; + const cin = if (transposed) d0 else d1; + const cout = if (transposed) d1 else d0; + const vs = std.mem.bytesAsSlice(f32, v.bytes); + var gs: ?[]align(1) const f32 = null; + if (normed) { + const g = f.get(try std.fmt.bufPrint(&nb[1], "{s}.weight_g", .{base})) orelse return error.MissingTensor; + gs = std.mem.bytesAsSlice(f32, g.bytes); + } + const out = try gpa.alloc(f32, K * cout * cin); + defer gpa.free(out); + for (0..d0) |a| { + var scale: f64 = 1; + if (gs) |g| { + var ss: f64 = 0; + for (0..d1 * K) |j| { + const x: f64 = vs[a * d1 * K + j]; + ss += x * x; + } + scale = @as(f64, g[a]) / @sqrt(ss); + } + for (0..d1) |b| for (0..K) |k| { + const w: f32 = @floatCast(@as(f64, vs[(a * d1 + b) * K + k]) * scale); + const o = if (transposed) b else a; + const i = if (transposed) a else b; + out[(k * cout + o) * cin + i] = w; + }; + } + const bname = try std.fmt.bufPrint(&nb[2], "{s}.bias", .{base}); + const bt = f.get(bname) orelse return error.MissingTensor; + if (bt.dtype != .f32 or bt.numel() != cout) return error.BadTensor; + return .{ .w = try s.upload(std.mem.sliceAsBytes(out)), .b = try s.upload(bt.bytes), .cin = cin, .cout = cout, .k = K }; +} + +pub fn loadDav(gpa: std.mem.Allocator, io: std.Io, s: anytype, dir: []const u8) !Dav { + const path = try std.fs.path.join(gpa, &.{ dir, decoder }); + defer gpa.free(path); + var f = try st.File.open(gpa, io, path); + defer f.close(io); + var d: Dav = undefined; + d.in_proj = try davConv(gpa, s, &f, "dec_in_proj", false, false); + d.conv0 = try davConv(gpa, s, &f, "decoder.model.0", false, true); + const strides = [_]usize{ 8, 8, 4, 2 }; + const dil = [_]usize{ 1, 3, 9 }; + var nb: [6][160]u8 = undefined; + for (0..4) |bi| { + const B = &d.blocks[bi]; + B.stride = strides[bi]; + B.alpha = try alpha(s, &f, try std.fmt.bufPrint(&nb[0], "decoder.model.{d}.block.0.alpha", .{bi + 1})); + B.up = try davConv(gpa, s, &f, try std.fmt.bufPrint(&nb[1], "decoder.model.{d}.block.1", .{bi + 1}), true, true); + for (0..3) |r| { + const p = "decoder.model.{d}.block.{d}.block."; + B.res[r] = .{ + .dilation = dil[r], + .a1 = try alpha(s, &f, try std.fmt.bufPrint(&nb[2], p ++ "0.alpha", .{ bi + 1, r + 2 })), + .c1 = try davConv(gpa, s, &f, try std.fmt.bufPrint(&nb[3], p ++ "1", .{ bi + 1, r + 2 }), false, true), + .a2 = try alpha(s, &f, try std.fmt.bufPrint(&nb[4], p ++ "2.alpha", .{ bi + 1, r + 2 })), + .c2 = try davConv(gpa, s, &f, try std.fmt.bufPrint(&nb[5], p ++ "3", .{ bi + 1, r + 2 }), false, true), + }; + } + } + d.alpha_out = try alpha(s, &f, "decoder.model.5.alpha"); + d.conv_out = try davConv(gpa, s, &f, "decoder.model.6", false, true); + return d; +} + +fn alpha(s: anytype, f: *const st.File, name: []const u8) !u64 { + const t = f.get(name) orelse { + std.log.err("music3: DAV has no {s}", .{name}); + return error.MissingTensor; + }; + if (t.dtype != .f32) return error.BadTensor; + return s.upload(t.bytes); +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 234800b8004..f2895ef39e5 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -31,6 +31,11 @@ fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !La return std.mem.indexOf(u8, s, p) != null; } }.f; + if (std.mem.startsWith(u8, d.name, "music3 ")) { + const m3 = @import("metal_music3.zig"); + const pre = try m3.source(a, d.name, true); + return .{ .decl = d, .function = fun, .here = if (device.tensorUnits()) try m3.source(a, d.name, false) else pre, .pre_m5 = pre }; + } if (std.mem.startsWith(u8, fun, "tf_ctl_")) { text = sources.core_contract_controls; if (has(fun, "big_tg")) head = "#define TF_CTL_BIG_TG 1\n"; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 8426690ae33..f089a5d9aa7 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -8,6 +8,7 @@ const affine_k = @import("metal_affine.zig"); const topk_k = @import("metal_topk.zig"); const tile_k = @import("metal_tile.zig"); const limits_k = @import("metal_limits.zig"); +const music3_k = @import("metal_music3.zig"); const g = contract.gates; const usage = "usage: tf-kernel-contract [--only TEXT] [--no-gates] [--no-limits] [--offline DIR] [--seed N] [--repro]"; @@ -95,6 +96,12 @@ pub fn main(init: std.process.Init) !u8 { try rows_list.append(a, r); try kernels.append(a, r.kernel()); } + var m3norm: ?music3_k.Norm = null; + defer if (m3norm) |*n| n.deinit(); + if (wanted(o, music3_k.spec().name)) { + m3norm = try music3_k.Norm.init(a, device, queue); + try kernels.append(a, m3norm.?.kernel()); + } var topk: ?topk_k.TopK = null; defer if (topk) |*t| t.deinit(); if (wanted(o, topk_k.spec().name)) { diff --git a/zig/tests/contract/metal_music3.zig b/zig/tests/contract/metal_music3.zig new file mode 100644 index 00000000000..bb5d444abda --- /dev/null +++ b/zig/tests/contract/metal_music3.zig @@ -0,0 +1,110 @@ +//! MiniMax Music 3's RMS norm rows on Metal (m3_rmsnorm, plain gamma) under the contract, and its sources for gate 5. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; + +/// A music3 source, includes inlined, by its gate 5 label ("music3 "); `simd`: the pre-M5 text. +pub fn source(a: std.mem.Allocator, label: []const u8, simd: bool) ![]u8 { + const m = sources.music3; + const files = .{ .{ "ar", m.ar }, .{ "attn", m.attn }, .{ "sample", m.sample }, .{ "gemm", m.gemm }, .{ "dit", m.dit }, .{ "dit_attn", m.dit_attn }, .{ "dav", m.dav } }; + var it = std.mem.tokenizeScalar(u8, label, ' '); + _ = it.next(); + const file = it.next() orelse return error.UnknownLaunch; + inline for (files) |f| if (std.mem.eql(u8, file, f[0])) { + const t1 = try std.mem.replaceOwned(u8, a, f[1], "#include \"m3_common.h\"", m.common); + defer a.free(t1); + const t2 = try std.mem.replaceOwned(u8, a, t1, "#include \"../prefill/gemm_nax.metal\"", m.gemm_nax); + defer a.free(t2); + const t3 = try std.mem.replaceOwned(u8, a, t2, "#include \"../nax.h\"", sources.nax); + defer a.free(t3); + return std.mem.concat(a, u8, &.{ if (simd) "#define TF_SIMD_FRAGS 1\n" else "", t3 }); + }; + return error.UnknownLaunch; +} + +/// ceil(k / 256) squares a thread, a simdgroup's tree, then the 8 simdgroups' partials in order. +fn depth(s: c.Shape) usize { + return (s.k + 255) / 256 + 13; +} + +const why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +pub fn spec() c.Spec { + return .{ .name = "metal music3 m3_rmsnorm (bf16 rows, plain gamma)", .accum = .f32, .depth = depth, .ops = 8, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256 } }, .served = &.{ .{ .rows = 2, .n = 4096, .k = 4096 }, .{ .rows = 4, .n = 4096, .k = 4096 }, .{ .rows = 600, .n = 4096, .k = 4096 } }, .sums = .{ .bf16 = 0, .why = why } }; +} + +const Args = extern struct { xs: u32, ys: u32, dim: u32, eps: f32 }; + +pub const Norm = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + r: ?rows.Rows = null, + x: rig_.Ref = undefined, + w: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !Norm { + const src = try source(a, "music3 ar m3_rmsnorm", false); + defer a.free(src); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try rig_.pipeline(device, src, "m3_rmsnorm") }; + } + + pub fn deinit(self: *Norm) void { + if (self.r) |r| r.deinit(); + self.rig.deinit(); + self.pipe.deinit(); + } + + pub fn kernel(self: *Norm) g.Kernel { + return .{ .spec = spec(), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Norm); + + pub fn prepare(self: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != shape.k) return false; + if (self.r) |r| r.deinit(); + self.r = null; + self.rig.reset(); + const r = try rows.Rows.init(self.a, .rms, shape); + self.r = r; + r.fill(fill, seed); + self.x = try self.rig.input(std.mem.sliceAsBytes(r.x)); + self.w = try self.rig.input(std.mem.sliceAsBytes(r.w)); + self.out = try self.rig.output(r.outputs() * c.size(spec().out)); + return true; + } + + pub fn run(self: *Norm) !void { + const r = self.r.?; + const k: u32 = @intCast(r.shape.k); + const p = self.rig.begin(); + const e = p.e; + e.setPipeline(self.pipe); + e.setBuffer(self.x.buf, self.x.off, 0); + e.setBuffer(self.w.buf, self.w.off, 1); + e.setBuffer(self.out.buf, self.out.off, 2); + e.setValue(Args{ .xs = k, .ys = k, .dim = k, .eps = r.eps }, 3); + e.dispatchGroups(mtl.Size.of(r.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try self.rig.finish(p); + } + + pub fn count(self: *Norm) usize { + return self.r.?.outputs(); + } + + pub fn reference(self: *Norm, want: []f64, mag: []f64) !void { + return self.r.?.reference(want, mag); + } + + pub fn simulate(self: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(acc, order, out); + } +}; diff --git a/zig/tests/cuda/contract_music3.zig b/zig/tests/cuda/contract_music3.zig new file mode 100644 index 00000000000..37f8d429866 --- /dev/null +++ b/zig/tests/cuda/contract_music3.zig @@ -0,0 +1,228 @@ +//! MiniMax Music 3's m3_rmsnorm and decode GEMVs (bf16, int8 a scale a row, int8 a scale a group) on CUDA. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const Dense = contract.dense.Dense; + +/// ceil(k / 512) squares a thread, then a warp's tree and the block's tree of 16 warps. +fn normDepth(s: c.Shape) usize { + return (s.k + 511) / 512 + 10; +} + +const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +pub fn normSpec() c.Spec { + return .{ .name = "cuda music3 m3_rmsnorm (bf16 rows, plain gamma)", .accum = .f32, .depth = normDepth, .ops = 8, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 512 } }, .served = &.{ .{ .rows = 2, .n = 4096, .k = 4096 }, .{ .rows = 4, .n = 4096, .k = 4096 }, .{ .rows = 600, .n = 4096, .k = 4096 } }, .sums = .{ .bf16 = 0, .why = norm_why } }; +} + +pub const Norm = struct { + rig: rig_.Rig, + f: cuda.Function, + r: ?rows.Rows = null, + x: u64 = 0, + w: u64 = 0, + out: u64 = 0, + + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module) !Norm { + return .{ .rig = .{ .gpu = gpu, .s = s }, .f = try mod.function("m3_rmsnorm") }; + } + + pub fn deinit(self: *Norm) void { + if (self.r) |r| r.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Norm) g.Kernel { + return .{ .spec = normSpec(), .ctx = self, .vt = &norm_vt }; + } + + const norm_vt = g.hooks(Norm); + + pub fn prepare(self: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != shape.k) return false; + if (self.r) |r| r.deinit(); + self.r = null; + self.rig.reset(); + const r = try rows.Rows.init(self.rig.gpu.gpa, .rms, shape); + self.r = r; + r.fill(fill, seed); + self.x = try self.rig.input(std.mem.sliceAsBytes(r.x)); + self.w = try self.rig.input(std.mem.sliceAsBytes(r.w)); + self.out = try self.rig.output(r.outputs() * c.size(normSpec().out)); + return true; + } + + pub fn run(self: *Norm) !void { + const r = self.r.?; + const k: c_int = @intCast(r.shape.k); + var a: cuda.Args = .{}; + a.add(self.x); + a.add(k); + a.add(self.w); + a.add(self.out); + a.add(k); + a.add(k); + a.add(r.eps); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(r.shape.rows), .y = 1, .z = 1 }, .block = .{ .x = 512 } }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Norm) usize { + return self.r.?.outputs(); + } + + pub fn reference(self: *Norm, want: []f64, mag: []f64) !void { + return self.r.?.reference(want, mag); + } + + pub fn simulate(self: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(acc, order, out); + } +}; + +pub const Kind = enum { bf16, int8, int8_group }; + +/// A lane's fp32 chain over its K / 32 inputs (a group's partial, then a chunk's fma) and the warp's 5-level tree. +fn gemvDepth(s: c.Shape) usize { + return s.k / 32 + 16 + 8; +} + +fn symbol(kind: Kind) [:0]const u8 { + return switch (kind) { + .bf16 => "m3_gemv_bf16_2", + .int8 => "m3_gemv_i8_2", + .int8_group => "m3_gemv_g8_2", + }; +} + +pub fn gemvSpec(kind: Kind) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 2, .n = 4096, .k = 4096 }, .{ .rows = 2, .n = 4096, .k = 12288 }, .{ .rows = 2, .n = 1024, .k = 4096 } }; + const kt: c.Tile = switch (kind) { + .bf16 => .{ .size = 256, .step = 8, .min = 8 }, + .int8 => .{ .size = 512, .step = 16, .min = 16 }, + .int8_group => .{ .size = 512, .step = 128, .min = 128 }, + }; + const name = switch (kind) { + .bf16 => "cuda music3 m3_gemv_bf16_2 (bf16 weights, two rows)", + .int8 => "cuda music3 m3_gemv_i8_2 (int8 weights, a scale a row)", + .int8_group => "cuda music3 m3_gemv_g8_2 (int8 weights, a scale a group of 128)", + }; + return .{ .name = name, .accum = .f32, .depth = gemvDepth, .ops = if (kind == .bf16) 0 else 1, .out = .bf16, .tiles = .{ .{}, .{ .size = 8, .step = 1, .min = 1 }, kt }, .served = served }; +} + +pub const Gemv = struct { + rig: rig_.Rig, + kind: Kind, + f: cuda.Function, + d: ?Dense = null, + x: u64 = 0, + w: u64 = 0, + sc: u64 = 0, + out: u64 = 0, + + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, kind: Kind) !Gemv { + return .{ .rig = .{ .gpu = gpu, .s = s }, .kind = kind, .f = try mod.function(symbol(kind)) }; + } + + pub fn deinit(self: *Gemv) void { + if (self.d) |d| d.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Gemv) g.Kernel { + return .{ .spec = gemvSpec(self.kind), .ctx = self, .vt = &gemv_vt }; + } + + const gemv_vt = g.hooks(Gemv); + + pub fn prepare(self: *Gemv, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const step: usize = switch (self.kind) { + .bf16 => 8, + .int8 => 16, + .int8_group => 128, + }; + if (shape.rows < 2 or shape.n == 0 or shape.k == 0 or shape.k % step != 0) return false; + if (self.d) |d| d.deinit(); + self.d = null; + self.rig.reset(); + const a = self.rig.gpu.gpa; + const n = shape.n; + const k = shape.k; + const d = try Dense.init(a, shape, 1); + self.d = d; + d.fillX(fill, seed, 2); + var prng = std.Random.DefaultPrng.init(seed ^ 0x6d33); + const rng = prng.random(); + const groups = if (self.kind == .int8_group) k / 128 else 1; + const scales = try a.alloc(f32, n * groups); + defer a.free(scales); + // powers of two, so the kernel's scale after the sum equals the scaled terms' sum exactly + for (scales) |*v| v.* = if (fill == .stress or self.kind == .bf16) 1 else std.math.ldexp(@as(f32, 1), -6 - @as(i32, @intCast(rng.uintLessThan(u32, 3)))); + const q = try a.alloc(i8, n * k); + defer a.free(q); + for (0..n) |j| for (0..k) |i| { + const v: i8 = if (fill == .stress) + (if (i < k / 2) @as(i8, @intCast(1 + (i * 7 + j) % 6)) else -@as(i8, @intCast(1 + ((i - k / 2) * 7 + j) % 6))) + else + @as(i8, @intCast(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127)); + q[j * k + i] = v; + const s: f64 = scales[j * groups + (if (self.kind == .int8_group) i / 128 else 0)]; + d.w[j * k + i] = @as(f64, @floatFromInt(v)) * s * @as(f64, if (self.kind == .bf16 and fill != .stress) 1.0 / 128.0 else 1.0); + }; + self.x = try self.rig.input(std.mem.sliceAsBytes(d.x)); + if (self.kind == .bf16) { + const wb = try a.alloc(u16, n * k); + defer a.free(wb); + for (wb, d.w) |*o, v| o.* = c.toBf16(@floatCast(v)); + self.w = try self.rig.input(std.mem.sliceAsBytes(wb)); + self.sc = 0; + } else { + self.w = try self.rig.input(std.mem.sliceAsBytes(q)); + self.sc = try self.rig.input(std.mem.sliceAsBytes(scales)); + } + self.out = try self.rig.output(shape.rows * n * 2); + return true; + } + + /// The two-row kernel over every pair of rows (an odd last row goes with the one before it, written twice alike). + pub fn run(self: *Gemv) !void { + const sh = self.d.?.shape; + var r0: usize = 0; + while (r0 < sh.rows) : (r0 += 2) { + const at = @min(r0, sh.rows - 2); + var a: cuda.Args = .{}; + a.add(self.w); + a.add(self.sc); + a.add(self.x + at * sh.k * 2); + a.add(@as(c_int, @intCast(sh.k))); + a.add(@as(c_int, @intCast(sh.k))); + a.add(@as(c_int, @intCast(sh.n))); + a.add(self.out + at * sh.n * 2); + a.add(@as(c_int, @intCast(sh.n))); + a.add(@as(u64, 0)); + a.add(@as(u64, 0)); + a.add(@as(c_int, 1)); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((sh.n + 7) / 8), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + try self.rig.s.synchronize(); + } + + pub fn count(self: *Gemv) usize { + return self.d.?.outputs(); + } + + pub fn reference(self: *Gemv, want: []f64, mag: []f64) !void { + return self.d.?.reference(want, mag); + } + + pub fn simulate(self: *Gemv, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.d.?.simulate(acc, order, out); + } +}; diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index e87a2e90e51..82555c2fb2c 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -8,6 +8,7 @@ const rows_k = @import("contract_rows.zig"); const router_k = @import("contract_router.zig"); const mm_k = @import("contract_mm.zig"); const rank_k = @import("contract_rank.zig"); +const music3_k = @import("contract_music3.zig"); const contract = core.contract; const g = contract.gates; @@ -21,7 +22,7 @@ const controls = struct { /// The embedded image a registration names (the controls' only when this binary was built with -Dnvcc). fn image(name: []const u8) []const u8 { - inline for (.{ "norms", "nemotron_route", "qmm_group", "lane_gemv", "prompt16", "qmmf", "rank_sum", "prefill_attention", "vit" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "norms", "nemotron_route", "qmm_group", "lane_gemv", "prompt16", "qmmf", "rank_sum", "prefill_attention", "vit", "music3" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); return if (options.controls) &controls.bytes else &.{}; } @@ -89,6 +90,15 @@ pub fn run(gpu: check.Gpu) !void { var rank = rank_k.Rank{ .rig = .{ .gpu = gpu, .s = s }, .sum = &rank_sum }; defer rank.deinit(); try kernels.append(a, rank.kernel()); + var m3_mod = try cuda.Module.load(gpu.d, kk.music3); + defer m3_mod.unload(); + var m3_norm = try music3_k.Norm.init(gpu, s, m3_mod); + defer m3_norm.deinit(); + try kernels.append(a, m3_norm.kernel()); + var m3_gemv: [3]music3_k.Gemv = undefined; + for (&m3_gemv, std.enums.values(music3_k.Kind)) |*m, kind| m.* = try music3_k.Gemv.init(gpu, s, m3_mod, kind); + defer for (&m3_gemv) |*m| m.deinit(); + for (&m3_gemv) |*m| try kernels.append(a, m.kernel()); var t: g.Tally = .{}; const t0 = check.now(gpu.io); try g.runAll(a, kernels.items, 0x6b63, &t);