Skip to content

hy4_flash: CUDA text path for EXL3 routed-expert checkpoints - #4004

Closed
shantanugoel wants to merge 19 commits into
ashhart:hy4-flash-metalfrom
shantanugoel:hy4-flash-cuda
Closed

shantanugoel wants to merge 19 commits into
ashhart:hy4-flash-metalfrom
shantanugoel:hy4-flash-cuda

Conversation

@shantanugoel

@shantanugoel shantanugoel commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #3941 (base hy4-flash-metal). The first commit is #4003 and drops out once that merges.

Summary

This adds Hy4-flash CUDA pieces that exist only on Metal so far, plus a whole-model greedy runner for EXL3 routed-expert checkpoints. Experts are mul1; everything else is BF16, as in LibertAIDAI/Hy4-flash-EXL3-4bpw 811866b. Engram tables stay BF16 on disk.

zig/kernels/cuda/hy4_flash/
├── engram.cu          # new: Engram lookup (stock FP8 round trip optional) + apply
└── indexpool.cu       # + tf_hy4_index_groups: FP32 value/gate pooling + key_norm
zig/src/families/hy4_flash/
├── exl3_weights.zig   # new: split mul1 experts (trellis/suh/svh/mul1)
├── moe_exl3_cuda.zig  # new: routed experts, sigmoid router + bias, top-16, combine
├── bf16_rows.zig      # new: O_DIRECT Engram row gather + prefetch worker (+ host tests)
├── index_cuda.zig     # new: compressed indexer (token keys, group pool/rope, recall)
├── engram_cuda.zig    # new: Engram branch (lookup, 5 BF16 GEMMs, apply)
├── cuda_model.zig     # new: whole text model on one sequence
└── cuda_generate.zig  # new: tf-hy4-cuda-generate (prefill + greedy decode)
zig/build/hy4_cuda.zig # new: hy4-cuda-generate step (embedded kernels)
cuda_model.pass(tokens)
  embed -> 4 streams
  42 layers:
    Engram (layers 1, 11, 21, 31; rows by direct I/O)
    iHC -> q/kv/gate GEMMs -> gated MLA (causal <= 2,048 keys; 512-key window on sliding layers) -> o_proj -> iHC add
    iHC -> dense MLP (layer 0) | latent MoE: router top-16 + 512 mul1 experts + shared expert -> iHC add
  hyper head -> norm -> LM head

Checkpoint shape this reads. Written against LibertAIDAI/Hy4-flash-EXL3-4bpw at 811866b: routed experts as mul1 trellis, everything else BF16, Engram tables as BF16 rows inside the trunk shards, one model.safetensors.index.json. Packs that deviate are refused at load rather than misread — e.g. vcruz305/Hy4-Flash-SAGE-REXL3-4.84bpw (a published 4.84 bpw pack) fails on four counts: its Engram lives in a second index (MissingHy4EngramTable), its Engram table is E4M3 with a BF16 row scale (BadTable), six tensor classes are stored F16 (BadHy4CheckpointTensor), and 247 dense groups including lm_head are trellis-only (BadHy4CheckpointTensor). I'll open a separate PR for that.

Evidence

  • Whole model on GB10, 34-token chat prompt (no_think), greedy, 32 tokens:

    ExLlamaV3 (LibertAIDAI fork 1af65c4) this PR
    load 41.6 s 150.6 s
    device weights 89.0 GB allocator peak 85.38 GiB
    prefill, 34 tokens 455 ms 884 ms
    decode 117 ms/token 98.6 ms/token
    Sunlight enters Earth's atmosphere and hits tiny gas molecules, which scatter shorter blue wavelengths much more strongly than longer red ones. This scattered blue light reaches our
    
  • Components vs FP64/torch references on real layer slices (relative L2), from local fixtures not included here because they need staged weight ranges:

    component result
    compressed indexer, 2,304 keys 511-of-575 recall identical on 4/4 rows; scores 6.2e-4
    32-head MLA over recalled slots 3.4e-3
    Engram, strict BF16 / stock FP8 4.9e-3 / 4.3e-3
    layer 1 (Engram, iHC, MLA, routed MoE) 7.0e-3
    dense layer 0 / 64-head sliding layer 2 6.4e-3 / 7.3e-3
    KV, index and Engram rollback after a rejected draft byte-exact
  • Build and tests: zig build hy4-cuda-generate test-hy4-flash-host test-exl3-cuda-host -Dnvcc=… → 142/142 steps; 1,071 tests passed, 10 skipped.

  • Load-time table validation: the Engram table's row count must equal the config's per-layer count, or load fails with RowCountMismatch. The four released tables differ by 14,562 rows (0.0088%), so a shard read for the wrong layer would otherwise stay in range for almost every lookup and address rows silently — audible only as a small quality loss. The new test fails without the check (26 pass, 1 fail) and passes with it.

Not in this PR:

  • the indexer recall inside the runner past 2,048 keys;
  • lane serving and the cuda_families registry entry;
  • vision and DFly2 on CUDA;
  • hiding Engram reads behind compute. A cold direct-I/O gather takes about 37 ms per Engram layer, while one layer's GPU pass takes 0.28 ms.

Merge Danger

Door: two-way

Everything is new files or new functions, plus one tool target. No existing serving path calls this code.

Blast Radius: additive

Nothing that ships changes behaviour, apart from #4003's uploader changes, which come in with the first commit. The build gains one kernel image (hy4_engram) and one executable (tf-hy4-cuda-generate) on CUDA builds.

…, MLA, iHC, Engram, indexer kernels, DFly2 drafter, host tests)
…eed work; compressed indexer past 2,048 keys

- Serving: the lane host with one stream, 512-row prompt chunks, DFly2 verify windows of up to six rows drawn on the host with the stream's sampler, the last stream's caches reused for a prompt that starts with their tokens, and every buffer in one residency set. Hy4's :opensource marker tokens read as the GLM spellings the server already parses.
- Long context: past 2,048 keys each sparse layer recalls its 511 best closed four-token groups plus its own (the reference's compressed indexer); token keys cached each pass, touched groups re-pooled in fp32. An fp64 check of the recall matches at 6K, and 6K-token NLL equals full attention.
- Decode: IHC collapse and seams over threadgroups, row and tensor projections, decode GEMVs for 1-2 rows, expert pair GEMVs, split-key decode attention, rank-based router select, 512-row prompt chunks.
- Probe: tf-hy4-speed (greedy ids and their hash, ms a token, per-stage GPU profile, NLL over a text).
…e and a resumed prompt equals a fresh one

Every pass takes the kernels a prompt chunk takes, so a row's bits never depend on how many rows share its pass:
- dense projections on the tensor units' lane projection at every row count (no 1-2 row GEMVs);
- routed experts on the tensor gathers at every row count (no pair GEMVs);
- MLA absorb and expand on the BF16 copies at every row count (no 1-row GEMVs over kv_b's codes);
- flash attention unsplit (a split count from the pass's widest row changed the other rows' sums);
- a pass across 2,048 keys attends its earlier rows over their whole range, as any other pass would, and only
  its later rows over the recalled lists.

Greedy tokens on the probe's prompts: plain, DFly2 (4 rows) and prompt chunks of 1, 37 and 512 rows give the same
ids at 4- and 8-bit, at short context, at 3,000 tokens and across the 2,048-key boundary.
…asses of 8 rows or fewer, and 8-bit codes reach the tensor units through registers

- Small passes skip the sums dispatch and its barrier: each split adds its (group, row) sums up front with the sums pass's own loop, one chain a lane, so the words are the same.
- 8-bit layouts take the reg path: the codes in the 4-bit reg order a byte each, unpacked as fp16 integers into the tensor op's right input; the same words as the 8-bit tensor layout.

Same greedy tokens as before at 4- and 8-bit (plain, DFly2, 512-row chunks). 4-bit one row 17.19 -> 16.54 ms, four rows 22.97 -> 22.45; 8-bit one row 24.13 -> 22.36 ms, four rows 34.75 -> 33.15, 512 rows 305 ms.
…vironment.zig, no dead decode paths, files under 600 lines

- TF_HY4_ENGRAM (nvme, ram or gpu) and TF_HY4_DRAFT_BITS (4, 8 or 16) are read through the environment module.
- The 1-2 row dense GEMVs, the expert pair and group GEMVs, the 1-row MLA GEMVs over kv_b's codes and their kernels go, with the diagnostic switches that chose them; every pass already took the prompt chunks' kernels.
- The speed probe leaves the tree; Linears, Rows and Scratch move out of metal_dense.zig, residency and drafting out of serve_metal.zig, and the Hy4 marker spellings out of hf_text.zig into hf_hy4.zig (with a test).
…UDA serving pins take the Hy4-flash images

- The family files import core/row_projection.zig, lane_projection.zig and moe_route.zig by path; the re-export modules made tensorfold.zig the root of a second module in the Metal runtime source tests.
- gradient-serving.tsv: kernels.zig with the Hy4-flash fatbin images registered and root.zig with cuda.affine_experts exported, as earlier families' registrations were recorded.
@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thanks @shantanugoel for bringing up the Hunyuan 4 Flash CUDA text path and the direct-I/O BF16 Engram reader!

We reviewed the additions over #3941 (and the carried #4003 commit): the new CUDA kernels (engram.cu, the index-groups kernel in indexpool.cu), the O_DIRECT Engram reader (bf16_rows.zig + tests), the .mul1 expert loader/runner (exl3_weights.zig, moe_exl3_cuda.zig), cuda_model.zig, cuda_generate.zig, and the the family files build wiring all look solid, match your description, and stay under the 600-line per-file limit (cuda_model.zig is at 596 lines).

Because this PR is stacked on #3941 and also depends on #4003 (which needs the small upload-failure drain fix noted there), it needs #3941 and #4003 to merge first and a rebase onto main so #4003's commit drops out. Once those are in, we will build and run the host tests and whole-model check on our GB10 (sm_121) before landing.

  • Synthena

…uploads

On GB10 each cuMemAlloc is rounded to 2 MiB: 2,000 x 1.18 MB uploads took
4.04 GiB against 2.24 GiB for one block of the same size (1.84x). A
512-expert EXL3 checkpoint has ~63k such tensors, so an 85 GiB pack needed
~150 GB and ran the machine out of memory.

Uploader.slab (opt-in) carves uploads up to half its size, 256-byte
aligned, from shared blocks; rollback forgets a released slab. pointers()
reuses the device copy when projections name the same trellis bytes.
Unset slab keeps the old behavior.
exl3_weights reads split mul1 experts (trellis/suh/svh/mul1) and rejects
affine or mixed markers; moe_exl3_cuda runs them on the shared EXL3 kernels
with Hy4's sigmoid router, correction bias, top-16 and scaled combine.
bf16_rows gathers 192-byte Engram rows with aligned O_DIRECT reads and a
prefetch worker (Linux host tests). mla_weights exposes splitBf16.
tf_hy4_index_groups pools a closed group's four token keys through the FP32
value/gate projections with intra_group_ape, then key_norm. index_cuda caches
token keys, pools and rotates closed groups, and scores and recalls with the
draft's rotate and recall kernels. Against an FP64 oracle on layer 1 over 2,304
keys: recall of 511 of 575 groups identical on 4/4 rows, scores 6.2e-4 relative
L2, draft rollback byte-exact.
hy4_engram mirrors engram.metal's rounding: lookup (optional stock FP8 round
trip, per-head RMSNorm) and apply (key/query norms, signed-sqrt gate, per-stream
scales), with the reference nn.RMSNorm epsilon (2^-23). On real layer-1 rows:
strict BF16 4.9e-3 and stock FP8 4.3e-3 relative L2 vs the torch reference.
cuda_model loads the BF16 trunk and 512 mul1 experts per sparse layer (slab
uploads, per-layer page release, TF_HY4_MEM_FLOOR_GIB guard) and runs embedding,
four streams, 42 layers, hyper head and LM head on one sequence: causal keys to
2,048, the 512-key window on sliding layers. tf-hy4-cuda-generate prefills and
decodes greedily. LibertAIDAI Hy4-flash-EXL3-4bpw on GB10: 85.38 GiB, 34-token
prefill 884 ms, 98.6 ms/token; all 32 greedy tokens equal ExLlamaV3's.
…t copy

carve() returned straight from a failed b.upload, so rollback() or deinit()
could free the slab while the copy was still writing it, and a newly opened
empty slab stayed in bufs/slab_at/bytes. It now drains as
DeviceBuffer.fromHost does, and a new slab is registered only once its first
upload succeeds (else drained and freed). Wait-failure tests with slab != 0
check bad_frees == 0.
openDirect took whatever row count the shard's header declared and rowOffset
bounds-checked against it, so a table read for the wrong layer, or one repacked
or truncated by another tool, loaded cleanly. The four released tables hold
164,994,380 / 164,999,008 / 165,004,086 / 165,008,942 rows: a wrong shard stays
inside the count for almost every lookup and addresses rows silently, which is
audible only as a small quality loss. The Metal path already derives the count
from the config (engram_rows.zig, weights.zig); this gives the CUDA reader the
same rule, as RowCountMismatch at load rather than BadTable mid-forward.

The test fails with TestUnexpectedResult without the check (26 pass, 1 fail) and
passes with it.
@AIFlowML

Copy link
Copy Markdown
Contributor

I built 1da00aa2f on Linux x86_64 with Zig 0.17.0 and nvcc 13.1. zig build hy4-cuda-generate test-hy4-flash-host test-exl3-cuda-host -Dnvcc=/usr/local/cuda/bin/nvcc -Dsm=120 -Dfixed-cpu -j5 --summary all passed 1,075 tests with 10 skips, including all 27 Hy4 host tests. I rebuilt the generator with -Dsm=121 for the GB10 target and verified the Engram image contains an sm_121 cubin. The no-argument invocation printed the expected usage and returned BadArgs. Whole-model inference still needs the GB10 run.

On the stack, #4003 has landed and git cherry 124052c97 1da00aa2f marks the three carried slab commits as patch-equivalent. #3941's current head 523acfc36 trial-merges cleanly into that main. Layering #4004 over that result still conflicts in nine paths, including indexpool.cu, the kernel registrations and the serving pins. Rebasing the CUDA changes onto the current #3941 tree while dropping the already-landed slab commits is the next step.

Igor Lessio - AIFLOW LABS

@ashhart
ashhart deleted the branch ashhart:hy4-flash-metal November 20, 2026 15:28
@ashhart ashhart closed this Nov 20, 2026
@shantanugoel

Copy link
Copy Markdown
Contributor Author

@ashhart I think the cuda changes got merged along with the metal right? Or do you need me to do anything else for them.

@ashhart

ashhart commented Nov 20, 2026

Copy link
Copy Markdown
Owner

@shantanugoel, thank you again for this. #4259 carries your eight commits onto today's main with your authorship, and it lands this PR once its device run passes.

For that run we are fetching LibertAIDAI/Hy4-flash-EXL3-4bpw at 811866b onto a GB10 to repeat your whole-model greedy check with the PR's CUDA generate tool. Could you post the 34 prompt token ids you used (the no_think chat prompt), or attach your prompt.u32, plus the 32 greedy token ids you got? Then we can compare token for token rather than by text.

  • Synthena

@ashhart

ashhart commented Nov 21, 2026

Copy link
Copy Markdown
Owner

@shantanugoel, your CUDA path is on main now: #4259 landed it at e3efa80 with your eight commits under your name, so nothing more is needed from you. To your earlier question: the Metal family went in first, and these CUDA changes needed their own rebase onto it.

On a GB10 the whole model loads at 85.38 GiB of device weights, as you measured, and decodes at 93.0 ms/token with coherent text. The token-for-token check against your 34-token run still waits on your prompt ids, if you can post them.

Thank you for this. It will be in the next release's notes with your name.

  • Synthena

@shantanugoel

Copy link
Copy Markdown
Contributor Author

Thanks! Here are the exact IDs from my GB10 run with LibertAIDAI/Hy4-flash-EXL3-4bpw at 811866b. The user turn was “Explain in two sentences why the sky is blue.” I used the checkpoint’s chat template with reasoning_effort="no_think" and add_generation_prompt=True. The same IDs also came out of an exllamav3 fork reference run on the same prompt, so TF cuda and exl3 agree token for token.

Prompt IDs (34)

[120000, 13251, 120001, 120039, 59785, 287, 62, 4138, 506, 25,
3202, 32980, 1121, 120025, 120000, 3717, 120001, 56908, 297, 1404,
21969, 4064, 269, 20663, 341, 9629, 13, 120025, 120000, 611,
10372, 120001, 120029, 120030]

Greedy output IDs (32, in generation order)

[28506, 4860, 29561, 10927, 683, 82, 14988, 303, 25817, 21136,
5244, 10229, 11, 819, 14845, 22072, 9629, 42014, 2353, 984,
15211, 1257, 6634, 4180, 7761, 13, 1124, 36374, 9629, 3218,
22083, 1525]

The original prompt file is the 34 IDs packed as little-endian unsigned 32-bit integers (136 bytes). I had to rename it to prompt-sky.u32.txt because gh doesnt allow uploading .u32 file prompt-sky.u32.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants