Repository navigation
GDN: use replay instead of rollback - #31669
Conversation
|
How come recomputation is faster? |
|
we're trading more compute for less data movement (same principle as flash attention) |
|
as a pleasant side-effect, this can also allow us to get rid of this transpose + concat llama.cpp/src/models/qwen4exp.cpp Lines 1424 to 1425 in efbf6e8 |
d18aa71 to
f46cacf
Compare
|
Tested on Qwen3.8-27B and Flash-Next with MTP: replay gives the exact same output and drafts as the snapshots, on both the fused and the graph path, and the recurrent memory goes from 2394 to 653 MiB at -np 4. Decode is on par, prefill is about 1.7% slower on a 4k prompt. One thing to add: find_slot moves cells around between the ubatches of a batch (the swap and the empty_cell copy) but rs_max does not follow, so a seq that just verified its drafts loses its rollback window and the next seq_rm fails. That's #31656, and the snapshot path has it too. With replay the rollback state lives in the cell row and moves with it, so carrying rs_max in both places fixes it: 0 aborts over 128 requests at -np 4, while 3 of 6 snapshot runs aborted. |
|
Same thing on your DFlash2 setup (Qwen3.8-27B + DFlash2 Q8_0, -np 8, n-max 7): the snapshot path aborts within seconds in 3 runs out of 3, while replay with rs_max carried ran 77 requests with no abort. The recurrent memory there goes from 9576 to 1414 MiB. With replay, this diff fixes #31656 (it does not help the snapshot path, whose rollback slots stay at the old cell): Looks like the right direction to me, the memory win is big and the output stays bit identical. Do you plan to make it the default and drop the env var, and move the other recurrent archs (glm5-next, kimi, mamba2, lfm) to replay too? |
|
@ServeurpersoCom thanks, should be fixed. It is a bug in master as well. I left out the The snapshot path is worse than the abort. If the cell the seq moves into already has a large enough
The logits are off by up to ~12, with no error. So in snapshot mode the moved seq now gets |
…ped, 3 RDNA3 PRs in
…ped, 3 RDNA3 PRs in
|
@ggml-org/maintainers feel free to ask your agent to push to this branch with the implementation of the GDN replay |
|
@am17an while writing the Metal replay kernel I ran into a problem with the graph replay fallback, so the first commit I push removes it. The fallback copies the committed state from the replay gdn when keep, and from the main gdn otherwise. That is fine on CUDA, whose graph_optimize only fuses, but Metal reorders the graph, so keep and non keep ubatches end up with a different node order for the same node count and the scheduler reallocates on every switch. On the current head, Metal has no replay in its gdn op yet, so LLAMA_RS_REPLAY=1 takes this fallback and test-llama-context aborts with "unexpected graph reallocation" under GGML_SCHED_DEBUG_REALLOC for qwen35, qwen35moe and qwen4exp. It passes as soon as GGML_METAL_GRAPH_OPTIMIZE_DISABLE=1 is set. Vulkan reorders its graph too. With this commit there is a single path: the replay always runs in the gdn op. CUDA already took that path, so nothing changes there: same graph, same outputs and drafts as snapshots on Qwen3.8-27B MTP and Qwen3.8-Flash-Next MTP, same speed. A backend without the replay in its gdn op now leaves that op to the CPU through the scheduler, like any unsupported op. It stays correct (test-llama-context 142/142 on Metal, Qwen3.8-27B MTP output identical to snapshots), but it is slower until the backend gets its kernel, about 20% on Metal decode. Since the replay is still opt-in, nobody hits this without asking for it. So the price is that each backend needs its own kernel to be fast, which you said is a small change per backend. The Metal one follows in the next commit, then Vulkan. |
|
Sounds good @ServeurpersoCom, I would prefer this as one change too. |
|
@am17an Metal, Vulkan and WebGPU now have the replay in their gdn op. On each of them test-backend-ops passes the replay cases, test-llama-context passes under GGML_SCHED_DEBUG_REALLOC, and Qwen3.8-27B MTP gives the same outputs and drafts as snapshots. The WebGPU commit also fixes the format job. SYCL, OpenCL, Hexagon, OpenVINO and ET still reject the replay, so their gdn op runs on the CPU when it is enabled. While measuring Vulkan I found an optimization to make, but it touches your design. After the gdn op, each layer runs 4 small cpys to keep the k, v, g and beta inputs of the new tokens as pending, so that the next ubatch can replay them. CUDA recognizes these 4 cpys in the graph and has its gdn kernel write the pending rows directly, so it never runs them. The other backends run them as 4 separate ops per layer. On a fast model this becomes visible. With Qwen3.8-Flash-Next MTP on Vulkan, the 4 cpys add about 13k dispatches for the same number of gdn calls, and decode ends up 3% slower than snapshots, while Qwen3.8-27B is still 1% faster. Copying the CUDA fusion to the other backends does not work well. Vulkan reorders its graph: the gdn is followed by the state cpy and the k, v and g cpys, then unrelated ops, and the beta cpy, which writes into the same cache as g, comes 8 nodes later, so it cannot be fused as a run of nodes. Having the gdn op write the pending rows itself would not fit ggml either, since an op only writes its dst. So I think the clean way is to have fewer pending cpys in the graph itself, for example g and beta already share a cache and could be stored together. How would you like to lay out the pending inputs? |
|
@ServeurpersoCom yes I think that's the better design, as we can then remove the fusion code from CUDA too. |
…ckerfiles from last round)
|
Folks, I'm going to merge this now otherwise we'll keep getting merge conflicts. |
* GDN: use replay instead of rollback [WIP] * memory : move rs_max with the sequence when find_slot swaps cells find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the way, but not rs_max, so that sequence inherited the rollback depth of the cell's previous owner. A smaller value made seq_rm refuse the rollback (ggml-org#31656), a larger one made snapshot mode restore the previous owner's snapshots. With rs_replay the pending columns are copied along with the state, so rs_max follows the sequence. Without it only the final state is copied and the snapshots stay behind, so the moved sequence gets rs_max 0. * delta_net: drop the graph replay fallback The graph fallback ran the replay as two gdn ops and copied the committed state from the replay gdn when keep, from the main gdn otherwise. Backends whose graph_optimize reorders nodes (Metal, Vulkan) then give keep and non keep ubatches a different node order for the same node count, and the scheduler reallocates on every switch (abort under GGML_SCHED_DEBUG_REALLOC). The replay now always runs in the gdn op. A device without the replay in its gdn op leaves the op to the CPU through the scheduler, as for any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe, rs_replay_fused and the rep_mask input. * metal: replay the pending gated delta net tokens in the kernel The gated delta net kernel replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a function constant of the pipeline, keep is a kernel argument as on CUDA. The pending buffers fall back to src0 when the op has no replay. * vulkan: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a specialization constant of the pipeline, keep is a push constant as on CUDA. The pending buffers bind q when the op has no replay. The result checker clones the op with its replay sources. * webgpu: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a define of the pipeline, keep is a param as on CUDA. The replay count goes through workgroupUniformLoad, so that the loop around the workgroup barriers stays uniform. * delta_net: share the replay conv window views across layers Each replay layer took its own view of the rs_rep_cols input. The scheduler copies every view of a host input as a separate split input, so a verify graph uploaded one copy per layer. The views of the delta net and the PLE conv windows are now built once per graph, like the s_copy views. * vulkan: clamp the gated delta net replay count to n_pend The replay count comes from a buffer, so the shader bounds it to the pending rows before looping over them. The pipeline array comment now names the replay index next to the other ones. Address review from 0cc4m. * hex-gdn: add support for replay Enable replay in HVX path Enable replay in HMX path * gdn: fix rebase conflicts (missing cparams, etc) * llama : drop the fused GDN probes brought back by the rebase il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn was always false), so restore master's version of that code. * delta_net : replay for the KDA models and Clover-MoE Clover-MoE has the Qwen 3.5 layout and only needs the arch gate. Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv windows one after the other in a row. With replay the row holds three channels-first histories [d_inner, window + pending]: build_conv_state_replay takes the gathered rows of the layer and the block index. The pending gate rows hold S_v gates per head (KDA). GLM5-Next gets the -sm tensor split rules for the replay rows. Tested with test-llama-archs models: logits match snapshots bit for bit with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and test-llama-context passes in both modes. * cuda : same KDA update in the gated delta net main and replay loops The KDA main loop called expf(g) twice inline, the replay loop reads g from registers. On sm_89 nvcc fused the two loops differently, so a replayed state was a few ulp off the state of the first pass. Compute g into registers in the main loop too: replay matches snapshots bit for bit on sm_89, and the sm_120 output does not change. * opencl: support replay in GDN * llama : replay inputs for the hybrid iswa rel memory input build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and cparams to build_rs_inp_impl and fill the replay inputs in set_input, like the other hybrid inputs. * webgpu: keep the gated delta net replay within the storage buffer limit * delta_net : add ggml_gated_delta_net_ext, replay is the only rollback ggml_gated_delta_net_ext takes the optional replay inputs and always outputs one state. ggml_gated_delta_net(..., K) is back to its master signature and is deprecated; both build the same op, so the backends are unchanged. The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the KDA models) now always replay the kept tokens when n_rs_seq > 0. The LLAMA_RS_REPLAY env flag and the snapshot branch of build_recurrent_attn are removed. test-backend-ops drops the K > 1 snapshot cases and the K parameter of the gated delta net tests. The cache fusion test copies the single state. * ggml-cpu : spacemit: leave the gdn replay to the generic kernel The RVV gated delta net kernel does not read the replay inputs. Return false when op param 1 (n_pend) is set, so that the generic kernel runs the op. * vulkan : fill views at any offset ggml_vk_fill bound dst without allowing a misaligned offset, so a fill of a view whose offset is not a multiple of minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in build_rs hits this with the wider replay conv rows on devices with a 64-byte alignment. Bind dst from the aligned offset below it and pass the element offset in KY. test_fill gets an offset to fill a view in place. --------- Co-authored-by: Pascal <[email protected]> Co-authored-by: Max Krasnyansky <[email protected]> Co-authored-by: Li He <[email protected]>
…mpling std::setlocale was resolved only through a transitive include that the GDN replay sync (upstream ggml-org#31669) no longer pulls in. Include it directly. Co-authored-by: Qwen-Coder <[email protected]>
…of upstream #31669) Port of ggml-org/llama.cpp#31669 (merge d35dc4d9e). A delta-net layer keeps one recurrent state plus the k, v, gate and beta inputs of the last ubatch. After seq_rm drops rejected drafts, the next gdn op replays the kept tokens before the new ones, so the n_rs_seq state snapshots are gone. - ggml: ggml_gated_delta_net_ext with the optional replay inputs; the K snapshot form stays as the deprecated ggml_gated_delta_net - CPU, Vulkan: replay in the kernel. Vulkan REPLAY is spec constant 4 (this fork has no PACKED_ROWS). Vulkan fill works on views at any offset - Metal, WebGPU: upstream code, applied cleanly, not built here - CUDA, OpenCL, Hexagon, SYCL, OpenVINO, ET: reject the op when it carries a replay, the scheduler runs it on the CPU (fork kernels not ported) - recurrent memory: rs_max / rs_pend / rs_rep per cell, spk / spv / spgb pending rows, conv rows hold window + pending columns; rs_replay passed through hybrid, hybrid-idx and hybrid-iswa - qwen35, qwen35moe, qwen4exp, kimi-k3, bailingmoe3 use replay when n_rs_seq > 0; the qwen4exp A7 op turns off under replay - tests: upstream replay and fill-offset cases added to test-backend-ops Tested on RX 9070 XT (Vulkan): test-backend-ops GATED_DELTA_NET 61/61 and FILL 6/6. DaisyRose-27B QSA, 262K, MTP 2 drafts: greedy output byte-identical to the snapshot build with the same draft acceptance, VRAM 14641 vs 14919 MiB, decode 89.1 vs 84.2 tok/s (code) and 82.1 vs 78.9 tok/s (prose). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in ggml/src/ggml-cuda/gated_delta_net.cu: upstream ggml-org#31669 gave launch_gated_delta_net a replay template parameter and a gdn_replay_args argument, where the colthread hook sits at the top of the body. Took upstream's signature and gated the hook on !replay: a replay launch carries pending-token inputs the colthread kernel does not implement, and a replay-free call always has an empty rep because those inputs only exist when dst->src[6] does. Everything else merged automatically, including the repack buft selection in llama-model.cpp, the meta backend whitelist and the d2d work in ggml-cuda.cu. Verified: pp512 2473, pp2048 ub 2048 3027, pp4096 ub 4096 2876, tg128 82.0, PPL c=512 3.5956 (colthread 3.5956 against 3.5833 with the hook off, greedy output identical). The pre-merge PPL of 3.5779 is not comparable: the corpus is generated from the repo docs, which this merge changed. Assisted-by: DeepSeek V4.1 Flash 1017
Prefill cost on a pre-Volta (P40) box — data pointThanks for this — the recurrent-state savings are real and measurable on my side. One trade-off worth knowing about: on a hybrid GDN model (Qwen3.5-9B, Setup: Tesla P40 (sm_61, 24 GiB), Windows / MSVC 19.44 / CUDA 12.6.85, master
So: −1.7% prefill, +192 MiB saved on this model. Generation is flat (difference is within run-to-run noise), and short-context prefill without MTP is unaffected (pp512 864.7 vs 864.7, pp4096 827.2 vs 827.2 on both builds) — the delta shows up only on long prompts, which is where the replay copies land per ubatch on the recurrent layers. Not a complaint — 192 MiB is worth a lot when packing 2×256k of q8_0 KV into 24 GiB, and I'm keeping it in my build. Just flagging the shape of the cost in case someone is profiling prefill on hybrids. If it's cheap to make replay skip no-op steps for layers whose state didn't change (or to only replay the layers actually touched by the draft rollback), that's likely where the 1.7% sits. Repro notes: the revert has to be src-only ( |
49 upstream commits past b12674. Conflicts in 7 files (20 hunks): the recurrent-state memory, its graph input, the delta-net layer, the GDN CUDA kernel, ggml.c and the fused norm+rope kernel. Each keeps both sides; three upstream default changes go behind switches so that every release file runs as measured: - LLAMA_RS_REPLAY=1: upstream's replay rollback for the delta-net models (ggml-org#31669). Unset, a rollback restores one of n_rs_seq + 1 state snapshots, as before (Flash-Next's MTP draft). The fork's pipe state groups stay; the replay rows are allocated only with the switch. The fork's in-place GDN state read stays off for the replay form. - GGML_CUDA_NORM_ROPE_MROPE=1: the fused RMS_NORM + MUL + ROPE also for M-RoPE and IMROPE (ggml-org#32500; Qwen3.5/3.6, Ornith, Qwen3.8). Unset, those run three launches, as before. - GGML_CUDA_NORM_ROPE_BS=1: ggml-org#32500's block sizes. Unset, 256 threads a row below 1,024 columns, as before. The one-token attention block (GGML_CUDA_ATTN_BLOCK) never takes an M-RoPE row: its epilogue has no sections. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fork's conv-window op reads a history of d_conv - 1 columns per rollback slot; upstream's replay (ggml-org#31669) keeps the window and the pending columns in one row, which only build_conv_state_at reads. With the switch on, Flash-Next's graph asserted in ggml_gdn_conv. Unset (the default) the graph is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Under -sm tensor every context checkpoint save or restore makes views of the recurrent cache tensors. The meta backend frees them only when it rebuilds a graph that uses the buffer, and with upstream ggml-org#31669 the target graph is stable, so the compute view pool overflowed with 8+ slots. An external view identical to one already in the container now shares its per-device slices. Assisted-by: Claude Opus 5.5
OpenCL: x2ue's gated_delta_net kernel takes upstream's replay (ggml_gated_delta_net_ext, ggml-org#31669) as a -DREPLAY build, on top of its cache-fused state input/output and chunked prefill (which is not used with replay). xielu, compact FA bias (indexed bias declined), softplus and async input copies come from upstream. Upstream's coop-k c8 verify GEMMs (ggml-org#32716, ggml-org#32909) are not taken: x2ue keeps its cok8 GEMMs. ggml-org#33013 (E17 quirks off by default) does not apply to x2ue's E17 handling. The coopmat GEMM and MoE kernels (ggml-org#32686, ggml-org#32971) and the GDN QK offset fix (ggml-org#32747) were already in x2ue. speculative.cpp keeps x2ue's single DFlash implementation. GDN tests follow upstream (no snapshot K); x2ue's verify-width perf cases now compare replay and plain.
* GDN: use replay instead of rollback [WIP] * memory : move rs_max with the sequence when find_slot swaps cells find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the way, but not rs_max, so that sequence inherited the rollback depth of the cell's previous owner. A smaller value made seq_rm refuse the rollback (ggml-org#31656), a larger one made snapshot mode restore the previous owner's snapshots. With rs_replay the pending columns are copied along with the state, so rs_max follows the sequence. Without it only the final state is copied and the snapshots stay behind, so the moved sequence gets rs_max 0. * delta_net: drop the graph replay fallback The graph fallback ran the replay as two gdn ops and copied the committed state from the replay gdn when keep, from the main gdn otherwise. Backends whose graph_optimize reorders nodes (Metal, Vulkan) then give keep and non keep ubatches a different node order for the same node count, and the scheduler reallocates on every switch (abort under GGML_SCHED_DEBUG_REALLOC). The replay now always runs in the gdn op. A device without the replay in its gdn op leaves the op to the CPU through the scheduler, as for any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe, rs_replay_fused and the rep_mask input. * metal: replay the pending gated delta net tokens in the kernel The gated delta net kernel replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a function constant of the pipeline, keep is a kernel argument as on CUDA. The pending buffers fall back to src0 when the op has no replay. * vulkan: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a specialization constant of the pipeline, keep is a push constant as on CUDA. The pending buffers bind q when the op has no replay. The result checker clones the op with its replay sources. * webgpu: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a define of the pipeline, keep is a param as on CUDA. The replay count goes through workgroupUniformLoad, so that the loop around the workgroup barriers stays uniform. * delta_net: share the replay conv window views across layers Each replay layer took its own view of the rs_rep_cols input. The scheduler copies every view of a host input as a separate split input, so a verify graph uploaded one copy per layer. The views of the delta net and the PLE conv windows are now built once per graph, like the s_copy views. * vulkan: clamp the gated delta net replay count to n_pend The replay count comes from a buffer, so the shader bounds it to the pending rows before looping over them. The pipeline array comment now names the replay index next to the other ones. Address review from 0cc4m. * hex-gdn: add support for replay Enable replay in HVX path Enable replay in HMX path * gdn: fix rebase conflicts (missing cparams, etc) * llama : drop the fused GDN probes brought back by the rebase il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn was always false), so restore master's version of that code. * delta_net : replay for the KDA models and Clover-MoE Clover-MoE has the Qwen 3.5 layout and only needs the arch gate. Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv windows one after the other in a row. With replay the row holds three channels-first histories [d_inner, window + pending]: build_conv_state_replay takes the gathered rows of the layer and the block index. The pending gate rows hold S_v gates per head (KDA). GLM5-Next gets the -sm tensor split rules for the replay rows. Tested with test-llama-archs models: logits match snapshots bit for bit with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and test-llama-context passes in both modes. * cuda : same KDA update in the gated delta net main and replay loops The KDA main loop called expf(g) twice inline, the replay loop reads g from registers. On sm_89 nvcc fused the two loops differently, so a replayed state was a few ulp off the state of the first pass. Compute g into registers in the main loop too: replay matches snapshots bit for bit on sm_89, and the sm_120 output does not change. * opencl: support replay in GDN * llama : replay inputs for the hybrid iswa rel memory input build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and cparams to build_rs_inp_impl and fill the replay inputs in set_input, like the other hybrid inputs. * webgpu: keep the gated delta net replay within the storage buffer limit * delta_net : add ggml_gated_delta_net_ext, replay is the only rollback ggml_gated_delta_net_ext takes the optional replay inputs and always outputs one state. ggml_gated_delta_net(..., K) is back to its master signature and is deprecated; both build the same op, so the backends are unchanged. The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the KDA models) now always replay the kept tokens when n_rs_seq > 0. The LLAMA_RS_REPLAY env flag and the snapshot branch of build_recurrent_attn are removed. test-backend-ops drops the K > 1 snapshot cases and the K parameter of the gated delta net tests. The cache fusion test copies the single state. * ggml-cpu : spacemit: leave the gdn replay to the generic kernel The RVV gated delta net kernel does not read the replay inputs. Return false when op param 1 (n_pend) is set, so that the generic kernel runs the op. * vulkan : fill views at any offset ggml_vk_fill bound dst without allowing a misaligned offset, so a fill of a view whose offset is not a multiple of minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in build_rs hits this with the wider replay conv rows on devices with a 64-byte alignment. Bind dst from the aligned offset below it and pass the element offset in KY. test_fill gets an offset to fill a view in place. --------- Co-authored-by: Pascal <[email protected]> Co-authored-by: Max Krasnyansky <[email protected]> Co-authored-by: Li He <[email protected]>
Overview
Remove the rollback from GDN, ideally this should be coordinated amongst backends to just remove all the rollback machinery in one go since per backend the change is not large.
TODO implementations:
the basic idea is in this diagram:
Additional information
GDN replay vs snapshot rollback
Measured on an RTX PRO 6000 with Qwen3.8-27B Q8_0 unless noted. Positive % means replay is faster.
Memory savings (recurrent state per sequence)
n_rs_seqWith 32 sequences at
n_rs_seq7, this is 37.4 GiB vs 5.5 GiB.Speed
n_rs_seq7n_rs_seq3Requirements