Skip to content

model : add hy_v4_flash on the DSA iSWA cache - #32960

Merged
ngxson merged 12 commits into
masterfrom
pascal/hy-v4-flash
Nov 25, 2026
Merged

ngxson merged 12 commits into
masterfrom
pascal/hy-v4-flash

Conversation

@ServeurpersoCom

@ServeurpersoCom ServeurpersoCom commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Adds Tencent Hy4 flash (220B, 12B active), text and vision. This is a simplified take on #32517, meant as a baseline that is easy to review and merge: it leaves the memory API alone. There is no new KV cache type, the model runs on the existing llama_kv_cache_dsa_iswa like dots3note.

The indexer pools of 4 tokens are rebuilt from the cache cells at each ubatch instead of being stored, so sequence edits, checkpoints and state save/restore need nothing special. Several sequences share a unified KV cache: a split cache with several sequences now switches to it with a warning instead of hitting an assert. The converter is the one from #32517, with the Engram tables streamed to the GGUF so the conversion fits in less than 100 GB of RAM.

Additional information

Tested with a Q2_K_XL quant, Engram kept in RAM with -ot per_layer_token_embd=CPU. Results match #32517 on the same GGUF within its own noise between f16 and q8_0 KV caches, and vision works end to end. MTP comes later.

The CUDA lightning indexer now supports 16 heads. Its kernels only covered 4, 32 and 64 heads, so this model's indexer ran on the CPU backend. #32517 has the same limitation, and its numbers below were measured with this fix applied to it.

Rebuilding the pools costs decode speed at long context: 70.6 / 36.2 / 17.1 t/s at 8k / 32k / 107k, against 90.3 / 85.5 / 73.6 for #32517 on the same hardware. This PR explores the route that leaves the memory API alone, and #32517 the one that stores the pools, so the two can be compared on real numbers. General ops and kernels that any model can use later already get most of the gap back on CUDA: 89.4 / 80.1 / 61.7 t/s, that is 99 / 94 / 84 % of #32517 (details in the comment below).

Requirements

Tencent Hy4 flash is a hy_v4 trunk (iHC, gated MLA, sinks) with
sparse and sliding-window MLA layers, sandwich norms, latent routed
experts and deepseek41 Engram tables.

The sparse layers select their context with a pooled indexer: the
keys of 4 consecutive tokens are pooled by a per-channel softmax of a
gate plus a position bias, normed, and rotated at the position of the
first token. A token attends to the best scored pools of its sequence
plus its own pool.

The model runs on llama_kv_cache_dsa_iswa as dots3note does. The
indexer cache holds the projected value and gate of each token, and
the pools are rebuilt from the cells for every ubatch by
llama_kv_cache::set_input_kpool(), so there is no pooled state to
keep in sync with sequence edits, checkpoints or state save/restore.
The selection goes through ggml_top_k_mask with the pool members as
blocks and the token's own pool as extra cells.

Not covered yet: the MTP block (its tensors are skipped), the vision
tower, multiple KV streams, and backends without GGML_OP_TOP_K_MASK.
@ServeurpersoCom
ServeurpersoCom requested review from a team and CISC as code owners November 24, 2026 16:02
@ServeurpersoCom
ServeurpersoCom marked this pull request as draft November 24, 2026 16:02
The converter of the hy_v4_flash model, without the vision parts.

The four Engram tables are written as one per_layer_token_embd
tensor of about 127 GB in BF16. Concatenating them with torch.cat
materializes the whole tensor at write time, so they are streamed one
table at a time in row chunks through the _StreamedBytes path of
deepseek41, which keeps the conversion within 100 GB of RAM.
A 4 layer fixture that alternates sparse and sliding-window layers,
with hyper-connections, one Engram module, an indexer on the sparse
layers and a latent width distinct from the expert width, so that a
transposed routed_down or routed_up is caught.
@ServeurpersoCom
ServeurpersoCom marked this pull request as ready for review November 24, 2026 16:21
The pooled indexer of hy_v4_flash caches the value and the gate of
each token, without a position: the pooled key is rotated in the
graph. A K-shift rotated these rows as if they were roped keys, which
broke the pooled keys after a context shift.
@github-actions github-actions Bot added model Model specific testing Everything test related conversion labels Nov 24, 2026
The vision tower of hy_v4_flash, with its projector in mtmd and its
converter.

The published files carry M-RoPE sections, so the text model runs the
interleaved M-RoPE path: the rope rows keep their reference order and
are reordered to NeoX halves in the graph. The tokens of an image share
their position, so the indexer pools now group consecutive tokens in
sequence order instead of consecutive positions, and a pooled key is
rotated at the four positions of its first member.

Without a backend that runs GGML_OP_TOP_K_MASK, the picked pools are
expanded to their cells and go through build_top_k_mask.
@ServeurpersoCom
ServeurpersoCom requested a review from a team as a code owner November 24, 2026 19:19
@github-actions github-actions Bot added the mtmd Related to multimodal functionality (video/image/audio) label Nov 24, 2026
hy_v4_flash scores its pools with 16 indexer heads, which the CUDA
backend did not support, so the scheduler ran the 12 sparse layers'
indexers on the CPU at every step. Both kernels already handle 16
heads: the mma kernel needs a multiple of 16 and the vector kernel
splits the heads in 4 passes.
@ServeurpersoCom
ServeurpersoCom requested a review from a team as a code owner November 24, 2026 19:46
@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Nov 24, 2026
With the gathers after build_inp_embd, the mixed embedding DUP and SET_ROWS
sat between two host nodes and stayed on the CPU. Those ops use every thread,
so all the CPU workers woke up on each decoded token for a 12K copy.
Gathering first lets the scheduler put them on the GPU, as in qwen4exp, and
leaves only small single threaded lookups on the host.
set_input_kpool deduplicated the pools through a map keyed by vectors even
with a single sequence, sorted cells that are already in order and scanned
every pool owner for each token. Dedup only when the ubatch has several
sequences, skip the sort when the cells are ordered and mark the earlier
pools of the token's sequence directly. At 129k cells the host cost of a
decode step drops from 4.0 ms to 0.5 ms, the logits are unchanged.

@am17an am17an left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this approach be extended to dsv4.1 flash? Currently the dsv4.1 flash model does not use unified kv-cache, wondering if this can help change that

The pools gather their members from a single KV stream, so a split cache
with several sequences hit an assert in the graph. Switch to the unified
cache with a warning, the sequences then share n_ctx.
@ServeurpersoCom

Copy link
Copy Markdown
Contributor Author

can this approach be extended to dsv4.1 flash? Currently the dsv4.1 flash model does not use unified kv-cache, wondering if this can help change that

The grouping by rank carries over, the stateless rebuild doesn't. In Hy4 every token's pooling inputs (value and gate) stay in the cache, so even the incomplete tail pool is rebuilt from cells and no state is needed. DSV4.1 keeps its compressor inputs (the wkv and wgate projections) only for the group in progress, and keeping them for every token would cost several times its whole KV cache, which is what the design avoids. So a unified DSV4.1 cache is doable, but its compressed entries would have to be written once, when a group is complete, and stored in a unified cell array next to a per-sequence comp state. That's the memory API change #32517 makes, and this PR stays away from it.

@ServeurpersoCom

ServeurpersoCom commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

I explored CUDA optimizations to see how far this model can be pushed without questioning the memory API.

The pools are rebuilt from the cache at every step, so at long context each sparse layer works on every pool of the sequence. That work turned out to be cheap in bytes but slow in a few kernels:

  1. CUDA: one thread per row for soft_max and sum_rows on short rows. Pooling softmaxes and sums millions of rows of 4 values. Both kernels gave each row a whole warp, so 28 of 32 threads sat idle. Short rows now get one thread each: soft_max goes from 1550 to 24 µs and sum_rows from 1549 to 11 µs on the 107k shape. Decode: 17.1 → 47.3 t/s at 107k, 36.2 → 70.2 t/s at 32k.
  2. CUDA: tiled transpose copy for strided sources. The value half of each cached row was transposed with the slow scalar copy, because the fast tiled copy only took fully contiguous sources. It now follows the source strides: 195 → 68 µs per layer. Decode: 47.3 → 49.7 t/s at 107k.
  3. ggml : add ggml_softmax_pool. The pooling itself (add the bias, softmax over the members, weighted sum of the values) took six passes over every pool. It is now one op that reads each value once. glm5-next and DeepSeek V4/V4.1 build the same pattern, so they can reuse it. Decode: 49.7 → 59.2 t/s at 107k, 73.0 → 79.6 t/s at 32k.
  4. Reorder the indexer channels when they are cached. M-RoPE needs the rotated channels in neox order, and that reorder ran on every pooled key at every step. Since pooling works per channel, the channels are now reordered once, when a token is written to the cache. Decode: 59.2 → 61.7 t/s at 107k.

Decode on the same hardware and the same Q2_K_XL (#32517 with the CUDA 16-head fix applied too):

Context This PR This PR + the four changes #32517 With the changes vs #32517
8k 70.6 t/s 89.4 t/s 90.3 t/s 99 %
32k 36.2 t/s 80.1 t/s 85.5 t/s 94 %
107k 17.1 t/s 61.7 t/s 73.6 t/s 84 %

Prefill is slightly faster than #32517 in both cases, for example 2897 vs 2799 t/s at 107k with the changes.

So with the changes, decode is on par at short context, and the gap grows with the context: #32517 keeps the pools in the cache, this PR rebuilds them, and what is left of that cost is the gather of the pool members and the norm and rope on every pool.

This PR is the baseline: the model, with no new op and no memory API change. The four changes are follow-up work that builds on it, split by where the code lives:

  • CUDA (one PR each, generic, not tied to this model): the short-row soft_max/sum_rows path and the strided tiled transpose copy.
  • ggml: ggml_softmax_pool, with the CPU reference and CUDA first, then one PR per backend (Metal, Vulkan, …). Hy4 flash switches to it once the backends it runs on have the op, otherwise the op would fall back to the CPU. glm5-next and DeepSeek V4/V4.1 can switch the same way.
  • This model: caching the indexer channels in neox order is model-only, so it can go in this PR.

Other backends may also need their own short-row and strided-copy fixes. I only measured CUDA.

@ServeurpersoCom

Copy link
Copy Markdown
Contributor Author

The ROCm test-llama-context failure comes from a gap in the CUDA flash attention tile kernel (DKQ 576 with a GQA ratio of 2), which this fixture hits on RDNA. Fixed separately in #33045.

@ngxson
ngxson merged commit c943331 into master Nov 25, 2026
43 of 46 checks passed
Mr-J-369 pushed a commit to Mr-J-369/llama.cpp-Android that referenced this pull request Nov 26, 2026
* model : add hy_v4_flash on the DSA iSWA cache

Tencent Hy4 flash is a hy_v4 trunk (iHC, gated MLA, sinks) with
sparse and sliding-window MLA layers, sandwich norms, latent routed
experts and deepseek41 Engram tables.

The sparse layers select their context with a pooled indexer: the
keys of 4 consecutive tokens are pooled by a per-channel softmax of a
gate plus a position bias, normed, and rotated at the position of the
first token. A token attends to the best scored pools of its sequence
plus its own pool.

The model runs on llama_kv_cache_dsa_iswa as dots3note does. The
indexer cache holds the projected value and gate of each token, and
the pools are rebuilt from the cells for every ubatch by
llama_kv_cache::set_input_kpool(), so there is no pooled state to
keep in sync with sequence edits, checkpoints or state save/restore.
The selection goes through ggml_top_k_mask with the pool members as
blocks and the token's own pool as extra cells.

Not covered yet: the MTP block (its tensors are skipped), the vision
tower, multiple KV streams, and backends without GGML_OP_TOP_K_MASK.

* convert : add hy_v4_flash

The converter of the hy_v4_flash model, without the vision parts.

The four Engram tables are written as one per_layer_token_embd
tensor of about 127 GB in BF16. Concatenating them with torch.cat
materializes the whole tensor at write time, so they are streamed one
table at a time in row chunks through the _StreamedBytes path of
deepseek41, which keeps the conversion within 100 GB of RAM.

* tests : add hy_v4_flash to test-llama-archs

A 4 layer fixture that alternates sparse and sliding-window layers,
with hyper-connections, one Engram module, an indexer on the sparse
layers and a latent width distinct from the expert width, so that a
transposed routed_down or routed_up is caught.

* kv-cache : do not shift the pooled indexer cache

The pooled indexer of hy_v4_flash caches the value and the gate of
each token, without a position: the pooled key is rotated in the
graph. A K-shift rotated these rows as if they were roped keys, which
broke the pooled keys after a context shift.

* tests : add the hy_v4_flash Metal fusion baseline

* model, mtmd : add hy_v4_flash vision

The vision tower of hy_v4_flash, with its projector in mtmd and its
converter.

The published files carry M-RoPE sections, so the text model runs the
interleaved M-RoPE path: the rope rows keep their reference order and
are reordered to NeoX halves in the graph. The tokens of an image share
their position, so the indexer pools now group consecutive tokens in
sequence order instead of consecutive positions, and a pooled key is
rotated at the four positions of its first member.

Without a backend that runs GGML_OP_TOP_K_MASK, the picked pools are
expanded to their cells and go through build_top_k_mask.

* CUDA: lightning indexer for 16 heads

hy_v4_flash scores its pools with 16 indexer heads, which the CUDA
backend did not support, so the scheduler ran the 12 sparse layers'
indexers on the CPU at every step. Both kernels already handle 16
heads: the mma kernel needs a multiple of 16 and the vector kernel
splits the heads in 4 passes.

* model : move the Hy4 flash Engram gathers before the token embeddings

With the gathers after build_inp_embd, the mixed embedding DUP and SET_ROWS
sat between two host nodes and stayed on the CPU. Those ops use every thread,
so all the CPU workers woke up on each decoded token for a 12K copy.
Gathering first lets the scheduler put them on the GPU, as in qwen4exp, and
leaves only small single threaded lookups on the host.

* llama : speed up the Hy4 flash pool inputs on long contexts

set_input_kpool deduplicated the pools through a map keyed by vectors even
with a single sequence, sorted cells that are already in order and scanned
every pool owner for each token. Dedup only when the ubatch has several
sequences, skip the sort when the cells are ordered and mark the earlier
pools of the token's sequence directly. At 129k cells the host cost of a
decode step drops from 4.0 ms to 0.5 ms, the logits are unchanged.

* llama : use a unified KV cache for Hy4 flash

The pools gather their members from a single KV stream, so a split cache
with several sequences hit an assert in the graph. Switch to the unified
cache with a warning, the sequences then share n_ctx.

* rm redundant code in mtmd

* clean up comments

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conversion CUDA Related to the CUDA backend ggml changes relating to the ggml tensor library for machine learning model Model specific mtmd Related to multimodal functionality (video/image/audio) testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants