Commit d35dc4d9e for llama.cpp
commit d35dc4d9e6827db8e08426a2340d8a71ea863cd9
Author: Aman Gupta <amangupta052@gmail.com>
Date: Tue Nov 24 07:06:02 2026 +0800
GDN: use replay instead of rollback (#31669)
* 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
(#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 <admin@serveurperso.com>
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
Co-authored-by: Li He <lih@qti.qualcomm.com>
diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h
index 161e8e0ce..0007fa18f 100644
--- a/ggml/include/ggml.h
+++ b/ggml/include/ggml.h
@@ -2435,11 +2435,17 @@ extern "C" {
// beta : [1, H_v, n_tokens, n_seqs]
// state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0
//
- // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state
- // snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1
- // keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written.
- // when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
- GGML_API struct ggml_tensor * ggml_gated_delta_net(
+ // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs]
+ //
+ // replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the
+ // previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot
+ // pend_k : [S_k, H_k, n_pend, n_seqs]
+ // pend_v : [S_v, H_v, n_pend, n_seqs]
+ // pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0)
+ // n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend)
+ // the state output is the state after the replay if keep is true, else the final state.
+ // op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set
+ GGML_API struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -2447,7 +2453,25 @@ extern "C" {
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
- int64_t K);
+ struct ggml_tensor * pend_k,
+ struct ggml_tensor * pend_v,
+ struct ggml_tensor * pend_gb,
+ struct ggml_tensor * n_rep,
+ bool keep);
+
+ // the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state,
+ // slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only
+ // slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
+ GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net(
+ struct ggml_context * ctx,
+ struct ggml_tensor * q,
+ struct ggml_tensor * k,
+ struct ggml_tensor * v,
+ struct ggml_tensor * g,
+ struct ggml_tensor * beta,
+ struct ggml_tensor * state,
+ int64_t K),
+ "use ggml_gated_delta_net_ext instead");
// DSA lightning indexer
//
diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp
index 9aed3b780..42a4b4479 100644
--- a/ggml/src/ggml-backend-meta.cpp
+++ b/ggml/src/ggml-backend-meta.cpp
@@ -875,11 +875,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_gated_delta_net = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
+ // replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq
+ const bool replay = tensor->src[6] != nullptr;
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
+ for (int i = 6; replay && i < 10; i++) {
+ GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
+ }
return src_ss[0];
}
+ if (replay) {
+ GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1);
+ GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1);
+ GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1);
+ GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
+ }
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1);
diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c
index ba075ff8d..dc0c95bf4 100644
--- a/ggml/src/ggml-cpu/ggml-cpu.c
+++ b/ggml/src/ggml-cpu/ggml-cpu.c
@@ -3068,9 +3068,10 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_GATED_DELTA_NET:
{
- const int64_t S_v = node->src[2]->ne[0];
- const int64_t K = ggml_get_op_params_i32(node, 0);
- const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
+ const int64_t S_v = node->src[2]->ne[0];
+ const int64_t K = ggml_get_op_params_i32(node, 0);
+ const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0;
+ const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
cur = per_thread * sizeof(float) * n_tasks;
} break;
case GGML_OP_COUNT:
diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp
index 26b4a01c9..72dd3e691 100644
--- a/ggml/src/ggml-cpu/ops.cpp
+++ b/ggml/src/ggml-cpu/ops.cpp
@@ -11313,11 +11313,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// per-seq stride in floats (seq s starts at state + s * seq_stride)
const int64_t state_seq_stride = src_state->nb[3] / sizeof(float);
- const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
+ // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
+ const ggml_tensor * src_pk = dst->src[6];
+ const ggml_tensor * src_pv = dst->src[7];
+ const ggml_tensor * src_pgb = dst->src[8];
+ const ggml_tensor * src_n_rep = dst->src[9];
+ const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0;
+ const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0;
+
+ const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
const int ith = params->ith;
float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32;
- float * state_work = K > 1 ? (delta + S_v) : nullptr;
+ float * state_work = K > 1 || keep ? (delta + S_v) : nullptr;
// output layout: [attn_scores | new_states]
// attn_scores: S_v * H * n_tokens * n_seqs floats
@@ -11351,7 +11359,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// For K=1, write directly to the single output slot to avoid an extra memcpy at the end.
// For K>1, work in scratch and copy out per-token when the slot is in range.
- float * s_out = (K > 1)
+ float * s_out = (K > 1 || keep)
? state_work
: state_out_base + (iv3 * H + iv1) * S_v * S_v;
@@ -11360,6 +11368,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v;
memcpy(s_out, s_in, S_v * S_v * sizeof(float));
+ if (src_pk) {
+ const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3];
+ GGML_ASSERT(n_r >= 0 && n_r <= n_pend);
+
+ const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1];
+ const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1];
+ const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1];
+
+ for (int64_t t = 0; t < n_r; t++) {
+ const float * k_d = (const float *) (pk + t*src_pk->nb[2]);
+ const float * v_d = (const float *) (pv + t*src_pv->nb[2]);
+ const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]);
+ const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]);
+
+ if (kda) {
+ for (int64_t i = 0; i < S_v; ++i) {
+ delta[i] = expf(g_d[i]);
+ }
+ for (int64_t j = 0; j < S_v; ++j) {
+ ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta);
+ }
+ } else {
+ ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0]));
+ }
+
+ for (int64_t j = 0; j < S_v; ++j) {
+ float sum = 0.0f;
+ ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1);
+ delta[j] = (v_d[j] - sum) * beta_val;
+ }
+
+ for (int64_t j = 0; j < S_v; ++j) {
+ ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]);
+ }
+ }
+
+ // the committed state, the new tokens go on in the scratch
+ if (keep) {
+ memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float));
+ }
+ }
+
// attn output pointer for first token of this (head, seq)
float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v;
diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp
index 0794c115d..a23e70bc4 100644
--- a/ggml/src/ggml-cpu/spacemit/ime.cpp
+++ b/ggml/src/ggml-cpu/spacemit/ime.cpp
@@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base {
}
return true;
case GGML_OP_GATED_DELTA_NET:
- if (params->use_ref) {
+ // the generic kernel does the replay of pending tokens (op param 1)
+ if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) {
return false;
}
switch (op->src[0]->type) {
diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cu b/ggml/src/ggml-cuda/gated-delta-net-mma.cu
index 427a33474..8fdb1edd4 100644
--- a/ggml/src/ggml-cuda/gated-delta-net-mma.cu
+++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cu
@@ -485,6 +485,10 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a
} // namespace
using namespace ggml_cuda_gated_delta_net_mma;
+bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & a) {
+ return a.state_out && select_gdn_mma_path(device, a) != gdn_path::ar;
+}
+
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & a, cudaStream_t stream) {
if (!a.state_out) {
return false;
diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh
index 8eb7c4f33..8659d9ffb 100644
--- a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh
+++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh
@@ -32,4 +32,6 @@ struct ggml_cuda_gdn_mma_args {
bool eligible;
};
+// true when ggml_cuda_gdn_mma_launch would run the chunked kernel for these args
+bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & args);
bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & args, cudaStream_t stream);
diff --git a/ggml/src/ggml-cuda/gated_delta_net.cu b/ggml/src/ggml-cuda/gated_delta_net.cu
index ae2374cbc..526030007 100644
--- a/ggml/src/ggml-cuda/gated_delta_net.cu
+++ b/ggml/src/ggml-cuda/gated_delta_net.cu
@@ -6,7 +6,25 @@
constexpr int gdn_cols_per_warp = 4;
-template <int S_v, bool KDA, bool keep_rs_t, int cols_per_warp = gdn_cols_per_warp>
+// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
+struct gdn_replay_args {
+ const float * pk; // [S_v, H_k, n_pend, n_seqs]
+ const float * pv; // [S_v, H, n_pend, n_seqs]
+ const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
+ const int32_t * n_rep; // [n_seqs]
+ int64_t sk1, sk2, sk3; // head, token and seq strides in floats
+ int64_t sv1, sv2, sv3;
+ int64_t sg1, sg2, sg3;
+ int n_pend;
+ bool keep; // write the state after the replay, not the final one
+
+ // optional: store the k, v, g, beta inputs of the new tokens (fused cpys)
+ float * st[4];
+ int64_t st2[4]; // token stride in floats
+ int64_t st3[4]; // seq stride in floats
+};
+
+template <int S_v, bool KDA, bool keep_rs_t, bool replay = false, int cols_per_warp = gdn_cols_per_warp>
__global__ void __launch_bounds__((ggml_cuda_get_physical_warp_size() < S_v ? ggml_cuda_get_physical_warp_size() : S_v) * 4, 2)
gated_delta_net_cuda(const float * q,
const float * k,
@@ -32,7 +50,8 @@ gated_delta_net_cuda(const float * q,
const uint3 rq3_magic,
float scale,
int64_t state_slot_stride,
- int K) {
+ int K,
+ const gdn_replay_args rep) {
const uint32_t h_idx = blockIdx.x;
const uint32_t sequence = blockIdx.y;
@@ -72,6 +91,53 @@ gated_delta_net_cuda(const float * q,
s_shard[r] = curr_state[i];
}
+ if constexpr (replay) {
+ const int n_r = rep.n_rep[sequence];
+ const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1;
+ const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1;
+ const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
+
+ for (int t = 0; t < n_r; t++) {
+ const float * k_t = pk + t * rep.sk2;
+ const float v_col = pv[t * rep.sv2 + col];
+ const float * g_t = pgb + t * rep.sg2;
+ const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
+
+ float k_reg[rows_per_lane];
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ k_reg[r] = k_t[r * lanes_per_col + lane_in_col];
+ }
+
+ float g_reg[rows_per_lane];
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ g_reg[r] = expf(KDA ? g_t[r * lanes_per_col + lane_in_col] : g_t[0]);
+ }
+
+ // same update as below, without the attention output
+ float kv_shard = 0.0f;
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ kv_shard += (KDA ? g_reg[r] : 1.0f) * s_shard[r] * k_reg[r];
+ }
+ const float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
+ const float delta_col = (v_col - (KDA ? 1.0f : g_reg[0]) * kv_col) * beta_val;
+
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
+ }
+ }
+
+ if (rep.keep) {
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ state[col * S_v + r * lanes_per_col + lane_in_col] = s_shard[r];
+ }
+ }
+ }
+
for (int t = 0; t < n_tokens; t++) {
const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1;
const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1;
@@ -93,6 +159,27 @@ gated_delta_net_cuda(const float * q,
q_reg[r] = q_t[i];
}
+ if constexpr (replay && !KDA) {
+ if (rep.st[0] != nullptr) {
+ // keep the inputs of this token pending: one CTA per k head writes k, each column its v
+ const bool first = blockIdx.z == 0 && threadIdx.y == 0 && col_in_warp == 0;
+ if (first && h_idx < neqk1_magic.z) {
+ float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v;
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ dk[r * lanes_per_col + lane_in_col] = k_reg[r];
+ }
+ }
+ if (lane_in_col == 0) {
+ rep.st[1][sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col] = v_t[col];
+ }
+ if (first && lane_in_col == 0) {
+ rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
+ rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
+ }
+ }
+ }
+
if constexpr (!KDA) {
const float g_val = expf(*g_t);
@@ -122,12 +209,18 @@ gated_delta_net_cuda(const float * q,
attn_data[col] = attn_col * scale;
}
} else {
+ // same arithmetic as the replay loop, so that a replayed state matches bit for bit
+ float g_reg[rows_per_lane];
+#pragma unroll
+ for (int r = 0; r < rows_per_lane; r++) {
+ g_reg[r] = expf(g_t[r * lanes_per_col + lane_in_col]);
+ }
+
// kv[col] = sum_i g[i] * S[i][col] * k[i]
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
- const int i = r * lanes_per_col + lane_in_col;
- kv_shard += expf(g_t[i]) * s_shard[r] * k_reg[r];
+ kv_shard += g_reg[r] * s_shard[r] * k_reg[r];
}
float kv_col = warp_reduce_sum<lanes_per_col>(kv_shard);
@@ -140,8 +233,7 @@ gated_delta_net_cuda(const float * q,
float attn_partial = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
- const int i = r * lanes_per_col + lane_in_col;
- s_shard[r] = expf(g_t[i]) * s_shard[r] + k_reg[r] * delta_col;
+ s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col;
attn_partial += s_shard[r] * q_reg[r];
}
@@ -170,6 +262,9 @@ gated_delta_net_cuda(const float * q,
}
if constexpr (!keep_rs_t) {
+ if (replay && rep.keep) {
+ return;
+ }
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
const int i = r * lanes_per_col + lane_in_col;
@@ -178,7 +273,7 @@ gated_delta_net_cuda(const float * q,
}
}
-template <bool KDA, bool keep_rs_t>
+template <bool KDA, bool keep_rs_t, bool replay = false>
static void launch_gated_delta_net(
const float * q_d, const float * k_d, const float * v_d,
const float * g_d, const float * b_d, const float * s_d,
@@ -188,7 +283,7 @@ static void launch_gated_delta_net(
int64_t sv1, int64_t sv2, int64_t sv3,
int64_t sb1, int64_t sb2, int64_t sb3,
int64_t neqk1, int64_t rq3,
- float scale, int64_t state_slot_stride, int K, cudaStream_t stream) {
+ float scale, int64_t state_slot_stride, int K, const gdn_replay_args & rep, cudaStream_t stream) {
//TODO: Add chunked kernel for even faster pre-fill
const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
// four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave
@@ -209,29 +304,29 @@ static void launch_gated_delta_net(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream);
switch (S_v) {
case 16:
- ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params,
+ ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
+ sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 32:
- ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params,
+ ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
+ sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
case 64: {
- ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params,
+ ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
+ sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
case 128: {
- ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params,
+ ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t, replay>, launch_params,
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H,
n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
+ sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
break;
}
default:
@@ -353,34 +448,85 @@ static void ggml_cuda_op_gated_delta_net_impl(
state_slot_stride = cache->slot_stride;
}
- {
+ const ggml_tensor * src_pend = dst->src[6];
+
+ gdn_replay_args rep = {};
+ if (src_pend) {
+ const ggml_tensor * src_pv = dst->src[7];
+ const ggml_tensor * src_pgb = dst->src[8];
+
+ GGML_ASSERT(K == 1);
+ rep.pk = (const float *) src_pend->data;
+ rep.pv = (const float *) src_pv->data;
+ rep.pgb = (const float *) src_pgb->data;
+ rep.n_rep = (const int32_t *) dst->src[9]->data;
+ rep.sk1 = src_pend->nb[1] / sizeof(float);
+ rep.sk2 = src_pend->nb[2] / sizeof(float);
+ rep.sk3 = src_pend->nb[3] / sizeof(float);
+ rep.sv1 = src_pv->nb[1] / sizeof(float);
+ rep.sv2 = src_pv->nb[2] / sizeof(float);
+ rep.sv3 = src_pv->nb[3] / sizeof(float);
+ rep.sg1 = src_pgb->nb[1] / sizeof(float);
+ rep.sg2 = src_pgb->nb[2] / sizeof(float);
+ rep.sg3 = src_pgb->nb[3] / sizeof(float);
+ rep.n_pend = ggml_get_op_params_i32(dst, 1);
+ rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
+ if (cache != nullptr) {
+ for (int i = 0; i < 4; ++i) {
+ rep.st[i] = cache->in_dst[i];
+ rep.st2[i] = cache->in_nb2[i];
+ rep.st3[i] = cache->in_nb3[i];
+ }
+ }
+ }
+
+#define GDN_LAUNCH_N(KDA, KEEP, REPLAY, N_TOKENS, REP) \
+ launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, \
+ S_v, H, N_TOKENS, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, \
+ sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, REP, stream)
+#define GDN_LAUNCH(KDA, KEEP, REPLAY) GDN_LAUNCH_N(KDA, KEEP, REPLAY, n_tokens, rep)
+
+ if (!src_pend) {
ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
args.state_out = state_d;
if (ggml_cuda_gdn_mma_launch(ctx.device, args, stream)) {
return;
}
+ } else if (!rep.keep && rep.st[0] == nullptr) {
+ // the chunked kernels (not KDA) do not replay: replay the pending tokens into the state output, then
+ // run the new tokens from there in place (each thread reads and writes the same state elements)
+ ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst);
+ args.state = state_d;
+ args.state_out = state_d;
+ if (ggml_cuda_gdn_mma_supported(ctx.device, args)) {
+ gdn_replay_args rep_only = rep;
+ rep_only.keep = true;
+ GDN_LAUNCH_N(false, false, true, 0, rep_only);
+ ggml_cuda_gdn_mma_launch(ctx.device, args, stream);
+ return;
+ }
}
+
if (kda) {
if (keep_rs) {
- launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
- S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
+ GDN_LAUNCH(true, true, false);
+ } else if (src_pend) {
+ GDN_LAUNCH(true, false, true);
} else {
- launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
- S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
+ GDN_LAUNCH(true, false, false);
}
} else {
if (keep_rs) {
- launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
- S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
+ GDN_LAUNCH(false, true, false);
+ } else if (src_pend) {
+ GDN_LAUNCH(false, false, true);
} else {
- launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
- S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
- sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
+ GDN_LAUNCH(false, false, false);
}
}
+
+#undef GDN_LAUNCH
+#undef GDN_LAUNCH_N
}
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
diff --git a/ggml/src/ggml-cuda/gated_delta_net.cuh b/ggml/src/ggml-cuda/gated_delta_net.cuh
index f9bf43706..97c3e0963 100644
--- a/ggml/src/ggml-cuda/gated_delta_net.cuh
+++ b/ggml/src/ggml-cuda/gated_delta_net.cuh
@@ -5,6 +5,11 @@
struct ggml_cuda_gated_delta_net_fused_cache {
float * data; // rollback slot 0
int64_t slot_stride; // between rollback slots (0 when K==1)
+
+ // rs_replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
+ float * in_dst[4] = {};
+ int64_t in_nb2[4] = {}; // token stride in elements
+ int64_t in_nb3[4] = {}; // seq stride in elements
};
void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu
index 3e1f167e9..a07e9a622 100644
--- a/ggml/src/ggml-cuda/ggml-cuda.cu
+++ b/ggml/src/ggml-cuda/ggml-cuda.cu
@@ -3647,6 +3647,47 @@ static int ggml_cuda_try_gdn_cache_fusion(
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
+
+ // rs_replay: the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
+ if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
+ int j = node_idx + skip + 1;
+ int skip_in = skip;
+ float * in_dst[4];
+ int64_t in_nb2[4];
+ int64_t in_nb3[4];
+ int i = 0;
+ for (; i < 4 && j < cgraph->n_nodes; ++j) {
+ const ggml_tensor * n = cgraph->nodes[j];
+ if (ggml_cuda_is_view_or_noop(n)) {
+ continue;
+ }
+ const ggml_tensor * in = gdn->src[1 + i];
+ const ggml_tensor * d = n->src[1];
+ // the cpy reads the whole input, directly or through a view of the same data
+ const ggml_tensor * s0 = n->src[0];
+ const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
+ ggml_are_same_stride(s0, in));
+ if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
+ d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
+ d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) || d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float)) {
+ break;
+ }
+ in_dst[i] = (float *) d->data;
+ in_nb2[i] = d->nb[2] / sizeof(float);
+ in_nb3[i] = d->nb[3] / sizeof(float);
+ skip_in = j - node_idx;
+ ++i;
+ }
+ if (i == 4) {
+ for (int c = 0; c < 4; ++c) {
+ fused_state_cpy.in_dst[c] = in_dst[c];
+ fused_state_cpy.in_nb2[c] = in_nb2[c];
+ fused_state_cpy.in_nb3[c] = in_nb3[c];
+ }
+ skip = skip_in;
+ }
+ }
+
return skip;
}
diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp
index e575ee78b..42aa72279 100644
--- a/ggml/src/ggml-et/ggml-et.cpp
+++ b/ggml/src/ggml-et/ggml-et.cpp
@@ -1537,7 +1537,8 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
op->src[4]->ne[0] == 1 && // beta is scalar per position
et_ggml_is_row_contiguous(op->src[0]) && et_ggml_is_row_contiguous(op->src[1]) &&
et_ggml_is_row_contiguous(op->src[2]) && ggml_is_contiguous(op->src[3]) &&
- ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5])) {
+ ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5]) &&
+ ggml_get_op_params_i32(op, 1) == 0) { // no replay of pending tokens
supported = true;
} else {
supported = false;
diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp
index 4e3c5cb8d..122d6aee8 100644
--- a/ggml/src/ggml-hexagon/htp-kparams.cpp
+++ b/ggml/src/ggml-hexagon/htp-kparams.cpp
@@ -514,7 +514,12 @@ static bool htp_kparams_solve_gated_delta_net(
const struct ggml_tensor * g = op->src[3];
const struct ggml_tensor * beta = op->src[4];
const struct ggml_tensor * state = op->src[5];
+ const struct ggml_tensor * pend_k = op->src[6];
+ const struct ggml_tensor * pend_v = op->src[7];
+ const struct ggml_tensor * pend_gb = op->src[8];
+ const struct ggml_tensor * n_rep = op->src[9];
const struct ggml_tensor * dst = op;
+ const bool replay = pend_k != nullptr;
if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 ||
g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 ||
@@ -552,6 +557,22 @@ static bool htp_kparams_solve_gated_delta_net(
dst->ne[2] != 1 || dst->ne[3] != 1) {
return false;
}
+ if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) {
+ return false;
+ }
+ if (replay) {
+ const int64_t n_pend = ggml_get_op_params_i32(op, 1);
+
+ if (K != 1 || n_pend < 0 || pend_k->type != GGML_TYPE_F32 || pend_v->type != GGML_TYPE_F32 ||
+ pend_gb->type != GGML_TYPE_F32 || n_rep->type != GGML_TYPE_I32 ||
+ pend_k->nb[0] != sizeof(float) || pend_v->nb[0] != sizeof(float) || pend_gb->nb[0] != sizeof(float) ||
+ pend_k->ne[0] != k->ne[0] || pend_k->ne[1] != k->ne[1] || pend_k->ne[2] != n_pend || pend_k->ne[3] != n_seqs ||
+ pend_v->ne[0] != S_v || pend_v->ne[1] != H || pend_v->ne[2] != n_pend || pend_v->ne[3] != n_seqs ||
+ pend_gb->ne[0] != g->ne[0] || pend_gb->ne[1] != H || pend_gb->ne[2] != 2*n_pend || pend_gb->ne[3] != n_seqs ||
+ !ggml_is_contiguous(n_rep) || ggml_nelements(n_rep) != n_seqs) {
+ return false;
+ }
+ }
const uint32_t rq3 = (uint32_t) (n_seqs / q->ne[3]);
const uint32_t rk3 = (uint32_t) (n_seqs / k->ne[3]);
diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
index 0280f99a4..68b9c1d47 100644
--- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
+++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c
@@ -574,7 +574,7 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float *
return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16));
}
-static inline void gdn_step_kda_f32(
+static __attribute__((noinline)) void gdn_step_kda_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -662,7 +662,7 @@ static inline void gdn_step_kda_f32(
}
}
-static inline void gdn_step_scalar_f32(
+static __attribute__((noinline)) void gdn_step_scalar_f32(
float * restrict s_work,
float * restrict attn_out,
const float * restrict q_t,
@@ -748,6 +748,48 @@ static inline void gdn_step_scalar_f32(
}
}
+static inline void gdn_replay_f32(
+ const struct htp_ops_context * octx,
+ float * restrict s_work,
+ uint32_t ik1,
+ uint32_t iv1,
+ uint32_t iv3,
+ bool kda,
+ float scale,
+ uint32_t S_v
+) {
+ const struct htp_tensor * pend_k = octx->src[6];
+ const struct htp_tensor * pend_v = octx->src[7];
+ const struct htp_tensor * pend_gb = octx->src[8];
+ const struct htp_tensor * n_rep = octx->src[9];
+
+ if (!pend_k) {
+ return;
+ }
+
+ const uint32_t n_pend = (uint32_t) octx->op_params[1];
+ const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3];
+ const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend);
+ float unused_attn[128] __attribute__((aligned(128)));
+
+ const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1];
+ const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1];
+ const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1];
+
+ for (uint32_t t = 0; t < n_steps; ++t) {
+ const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]);
+ const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]);
+ const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]);
+ const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]);
+
+ if (kda) {
+ gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
+ } else {
+ gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v);
+ }
+ }
+}
+
static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) {
struct htp_gdn_context * gctx = (struct htp_gdn_context *) data;
struct htp_ops_context * octx = gctx->octx;
@@ -792,6 +834,7 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float));
+ const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -838,6 +881,10 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
+ if (keep) {
+ hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
+ }
for (uint32_t t = 0; t < n_tokens; ++t) {
const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data +
(uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]);
@@ -868,10 +915,9 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- // Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), S_v);
+ S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -932,6 +978,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
const uint32_t state_seq_stride = kparams->state_seq_stride;
const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float));
+ const bool keep = octx->src[6] && octx->op_params[2] != 0;
uint32_t ir_prefetch = gctx->row_start + ith;
int spad_idx = 0;
@@ -989,6 +1036,10 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
(uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]);
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
+ gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v);
+ if (keep) {
+ hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v);
+ }
if (kparams->kda) {
gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v);
} else {
@@ -996,10 +1047,9 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int
}
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir);
- // Push real write-back
dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr),
S_v * sizeof(float), S_v * sizeof(float),
- S_v * sizeof(float), S_v);
+ S_v * sizeof(float), keep ? 0 : S_v);
// Prefetch next block (if any)
if (ir_prefetch < row_end) {
@@ -1654,13 +1704,15 @@ struct htp_gdn_batch_context {
const struct htp_gdn_kernel_params * kparams;
};
-static void gdn_hvx_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
+static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) {
(void) n;
struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data;
struct htp_thread_trace * tr = th->trace;
htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0);
struct htp_gdn_head_ptrs * head = &bctx->heads[i];
+ gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3,
+ bctx->kparams->kda, bctx->scale, bctx->S_v);
gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v);
htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0);
@@ -2038,6 +2090,7 @@ static int gated_delta_net_f32_hmx_chunked(
const uint32_t chunk_size = kparams->chunk_size;
const uint32_t n_chunks = kparams->n_chunks;
const uint32_t n_sv_tiles = S_v / 32;
+ const bool keep = octx->src[6] && octx->op_params[2] != 0;
struct htp_gdn_hmx_vtcm_layout L;
htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0);
@@ -2101,7 +2154,17 @@ static int gated_delta_net_f32_hmx_chunked(
}
if (n_chunks > 0) {
- work_queue_run(wp, gdn_hvx_init_state_worker, &bctx, n_batch);
+ work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch);
+
+ if (keep) {
+ for (uint32_t h = 0; h < n_batch; ++h) {
+ dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
+ S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
+ }
+ for (uint32_t h = 0; h < n_batch; ++h) {
+ dma_queue_pop(dma_q);
+ }
+ }
const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens);
for (uint32_t h = 0; h < n_batch; ++h) {
@@ -2254,12 +2317,14 @@ static int gated_delta_net_f32_hmx_chunked(
}
}
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
- S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
- }
- for (uint32_t h = 0; h < n_batch; ++h) {
- dma_queue_pop(dma_q);
+ if (!keep) {
+ for (uint32_t h = 0; h < n_batch; ++h) {
+ dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state),
+ S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v);
+ }
+ for (uint32_t h = 0; h < n_batch; ++h) {
+ dma_queue_pop(dma_q);
+ }
}
}
@@ -2270,7 +2335,7 @@ static int gated_delta_net_f32_hmx_chunked(
int op_gated_delta_net(struct htp_ops_context * octx) {
const struct htp_tensor * dst = octx->dst;
- for (int i = 0; i < 6; i++) {
+ for (int i = 0; i < 10; i++) {
if (htp_tensor_is_extended(octx->src[i])) {
return HTP_STATUS_NO_SUPPORT;
}
@@ -2308,9 +2373,6 @@ int op_gated_delta_net(struct htp_ops_context * octx) {
);
row_start = range.start;
nrows = range.count;
- } else if (octx->op_params[1] != 0) {
- row_start = octx->op_params[1];
- nrows = octx->op_params[2];
}
if (nrows == 0) {
diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp
index 7a732e29e..c4e6ded8b 100644
--- a/ggml/src/ggml-metal/ggml-metal-device.cpp
+++ b/ggml/src/ggml-metal/ggml-metal-device.cpp
@@ -752,6 +752,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net(
const int ne30 = op->src[3]->ne[0]; // G
// state is src[5], 4D [S_v, S_v, H_v, n_seqs] (s0 only); K is op param 0.
const int K = ggml_get_op_params_i32(op, 0);
+ // replay of pending tokens, see ggml_gated_delta_net_ext
+ const bool replay = op->src[6] != nullptr;
const int nsg = op->src[2]->ne[0]/32;
@@ -760,15 +762,16 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net(
GGML_ASSERT(ne20 % 32 == 0);
snprintf(base, 256, "kernel_gated_delta_net_%s_%d", ggml_type_name(op->src[0]->type), nsg);
- snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d", base, ne20, ne30, K);
+ snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d_rep=%d", base, ne20, ne30, K, replay ? 1 : 0);
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
if (!res.pipeline) {
ggml_metal_cv_t cv = ggml_metal_cv_init();
- ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0);
- ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1);
- ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2);
+ ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0);
+ ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1);
+ ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2);
+ ggml_metal_cv_set_bool (cv, replay, FC_GATED_DELTA_NET + 3);
res = ggml_metal_library_compile_pipeline(lib, base, name, cv);
diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h
index 4e28b2cb9..c0042a8c1 100644
--- a/ggml/src/ggml-metal/ggml-metal-impl.h
+++ b/ggml/src/ggml-metal/ggml-metal-impl.h
@@ -1037,6 +1037,17 @@ typedef struct {
uint64_t nb2;
uint64_t nb3;
uint64_t nb_out; // 0 => snapshots are appended after the attn scores (unfused)
+ int32_t n_pend; // replay: pending tokens per seq in pend_k, pend_v and pend_gb
+ int32_t keep; // replay: write the state after the replay, not the final one
+ uint64_t nb61; // pend_k
+ uint64_t nb62;
+ uint64_t nb63;
+ uint64_t nb71; // pend_v
+ uint64_t nb72;
+ uint64_t nb73;
+ uint64_t nb81; // pend_gb
+ uint64_t nb82;
+ uint64_t nb83;
} ggml_metal_kargs_gated_delta_net;
typedef struct {
diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp
index a7a1ef61e..e1f8610c5 100644
--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp
+++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp
@@ -2104,6 +2104,12 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
}
}
+ // replay of pending tokens, see ggml_gated_delta_net_ext
+ const ggml_tensor * pk = op->src[6];
+ const ggml_tensor * pv = op->src[7];
+ const ggml_tensor * pgb = op->src[8];
+ const ggml_tensor * rep = op->src[9];
+
int ida = 0;
ggml_metal_kargs_gated_delta_net args = {
@@ -2143,6 +2149,17 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
/*.nb2 =*/ nb2,
/*.nb3 =*/ nb3,
/*.nb_out =*/ nb_out,
+ /*.n_pend =*/ pk ? ggml_get_op_params_i32(op, 1) : 0,
+ /*.keep =*/ pk ? ggml_get_op_params_i32(op, 2) : 0,
+ /*.nb61 =*/ pk ? pk->nb[1] : 0,
+ /*.nb62 =*/ pk ? pk->nb[2] : 0,
+ /*.nb63 =*/ pk ? pk->nb[3] : 0,
+ /*.nb71 =*/ pv ? pv->nb[1] : 0,
+ /*.nb72 =*/ pv ? pv->nb[2] : 0,
+ /*.nb73 =*/ pv ? pv->nb[3] : 0,
+ /*.nb81 =*/ pgb ? pgb->nb[1] : 0,
+ /*.nb82 =*/ pgb ? pgb->nb[2] : 0,
+ /*.nb83 =*/ pgb ? pgb->nb[3] : 0,
};
ggml_metal_encoder_set_pipeline(enc, pipeline);
@@ -2155,6 +2172,10 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[5]), ida++); // state
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), ida++); // dst (attn)
ggml_metal_encoder_set_buffer (enc, bid_out, ida++); // state_out
+ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pk ? pk : op->src[0]), ida++); // pend_k
+ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pv ? pv : op->src[0]), ida++); // pend_v
+ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pgb ? pgb : op->src[0]), ida++); // pend_gb
+ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(rep ? rep : op->src[0]), ida++); // n_rep
const int nsg = pipeline.nsg;
diff --git a/ggml/src/ggml-metal/kernels/gated_delta_net.metal b/ggml/src/ggml-metal/kernels/gated_delta_net.metal
index 5e4861ece..8e8e04963 100644
--- a/ggml/src/ggml-metal/kernels/gated_delta_net.metal
+++ b/ggml/src/ggml-metal/kernels/gated_delta_net.metal
@@ -3,6 +3,7 @@
constant short FC_gated_delta_net_ne20 [[function_constant(FC_GATED_DELTA_NET + 0)]];
constant short FC_gated_delta_net_ne30 [[function_constant(FC_GATED_DELTA_NET + 1)]];
constant short FC_gated_delta_net_K [[function_constant(FC_GATED_DELTA_NET + 2)]];
+constant bool FC_gated_delta_net_rep [[function_constant(FC_GATED_DELTA_NET + 3)]];
#if 1
template<short NSG>
@@ -16,6 +17,10 @@ kernel void kernel_gated_delta_net_impl(
device const char * s,
device char * dst,
device char * dst_fuse,
+ device const char * pk,
+ device const char * pv,
+ device const char * pgb,
+ device const char * n_rep,
uint3 tgpig[[threadgroup_position_in_grid]],
uint3 tpitg[[thread_position_in_threadgroup]],
uint3 ntg[[threads_per_threadgroup]]) {
@@ -72,6 +77,62 @@ kernel void kernel_gated_delta_net_impl(
const device float * state_out = fused ? (device float *)dst_fuse : (device float *)dst + attn_size;
const uint slot_stride = fused ? (uint)args.nb_out : state_size_per_snap;
+ // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
+ if (FC_gated_delta_net_rep) {
+ const int n_r = ((device const int32_t *) n_rep)[i23];
+
+ device const char * pk_ptr = pk + i23*args.nb63 + i11*args.nb61;
+ device const char * pv_ptr = pv + i23*args.nb73 + i21*args.nb71;
+ device const char * pgb_ptr = pgb + i23*args.nb83 + i21*args.nb81;
+
+ for (int t = 0; t < n_r; t++) {
+ device const float * k_t = (device const float *) (pk_ptr + t*args.nb62);
+ device const float * g_t = (device const float *) (pgb_ptr + t*args.nb82);
+
+ const float v_t = ((device const float *) (pv_ptr + t*args.nb72))[i20];
+ const float beta_t = *(device const float *) (pgb_ptr + (args.n_pend + t)*args.nb82);
+
+ // same update as below, without the attention output
+ float s_k = 0.0f;
+
+ if (G == 1) {
+ const float g_exp = exp(g_t[0]);
+
+ FOR_UNROLL (short j = 0; j < NSG; j++) {
+ const short is = tx*NSG + j;
+ ls[j] *= g_exp;
+
+ s_k += ls[j]*k_t[is];
+ }
+ } else {
+ // KDA
+ FOR_UNROLL (short j = 0; j < NSG; j++) {
+ const short is = tx*NSG + j;
+ ls[j] *= exp(g_t[is]);
+
+ s_k += ls[j]*k_t[is];
+ }
+ }
+
+ s_k = simd_sum(s_k);
+
+ const float d = (v_t - s_k)*beta_t;
+
+ FOR_UNROLL (short j = 0; j < NSG; j++) {
+ const short is = tx*NSG + j;
+ ls[j] += k_t[is]*d;
+ }
+ }
+
+ if (args.keep) {
+ device float * dst_state = (device float *)state_out + state_out_base;
+ FOR_UNROLL (short j = 0; j < NSG; j++) {
+ const short is = tx*NSG + j;
+ dst_state[is] = ls[j];
+ }
+ }
+ }
+
for (short t = 0; t < args.ne22; t++) {
float s_k = 0.0f;
@@ -132,7 +193,8 @@ kernel void kernel_gated_delta_net_impl(
}
}
- if (K == 1) {
+ // replay with keep: the state output is the state after the replay
+ if (K == 1 && !(FC_gated_delta_net_rep && args.keep)) {
device float * dst_state = (device float *)state_out + state_out_base;
FOR_UNROLL (short j = 0; j < NSG; j++) {
const short is = tx*NSG + j;
diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp
index 2a3f709a2..54038a503 100644
--- a/ggml/src/ggml-opencl/ggml-opencl.cpp
+++ b/ggml/src/ggml-opencl/ggml-opencl.cpp
@@ -1181,9 +1181,9 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_conv_2d_f16_f32;
cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32;
cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4;
- // [size_idx][kda][tgpp] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
+ // [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1.
// tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4).
- cl_kernel kernel_gated_delta_net_f32[4][2][2] = {};
+ cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {};
cl_kernel kernel_ssm_scan_f32 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr;
cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr;
@@ -5170,7 +5170,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
GGML_LOG_CONT(".");
}
- // gated_delta_net: one kernel per (S_V, KDA, tgpp) triple.
+ // gated_delta_net: one kernel per (S_V, KDA, tgpp, replay).
{
#ifdef GGML_OPENCL_EMBED_KERNELS
const std::string kernel_src {
@@ -5238,11 +5238,14 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
// Please remember to implement code to handle it.
opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw);
- cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts);
+ for (int replay = 0; replay < 2; replay++) {
+ const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay);
+ cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep);
- CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp] =
- clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
- CL_CHECK(clReleaseProgram(prog));
+ CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] =
+ clCreateKernel(prog, "kernel_gated_delta_net", &err), err));
+ CL_CHECK(clReleaseProgram(prog));
+ }
}
}
}
@@ -40476,6 +40479,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
const cl_uint n_tokens = (cl_uint) src_v->ne[2];
const cl_uint n_seqs = (cl_uint) src_v->ne[3];
const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0);
+ const bool replay = dst->src[6] != nullptr;
+ const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0;
+ const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0;
int si;
switch (S_v) {
@@ -40509,7 +40515,7 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
// spw needs adjustment when S_v != 128
const int spw = (tgpp == 0) ? 1 : 1;
- cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp];
+ cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay];
GGML_ASSERT(kernel != nullptr);
const cl_uint s_off = S_v * H_v * n_tokens * n_seqs;
@@ -40576,7 +40582,59 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) {
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3));
CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale));
- CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
+
+ if (replay) {
+ const ggml_tensor * src_pk = dst->src[6];
+ const ggml_tensor * src_pv = dst->src[7];
+ const ggml_tensor * src_pgb = dst->src[8];
+ const ggml_tensor * src_rep = dst->src[9];
+
+ GGML_ASSERT(src_pk && src_pk->extra);
+ GGML_ASSERT(src_pv && src_pv->extra);
+ GGML_ASSERT(src_pgb && src_pgb->extra);
+ GGML_ASSERT(src_rep && src_rep->extra);
+
+ const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra;
+ const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra;
+ const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra;
+ const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra;
+
+ const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs;
+ const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs;
+ const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs;
+ const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs;
+
+ const cl_ulong spk1 = src_pk->nb[1] / sizeof(float);
+ const cl_ulong spk2 = src_pk->nb[2] / sizeof(float);
+ const cl_ulong spk3 = src_pk->nb[3] / sizeof(float);
+ const cl_ulong spv1 = src_pv->nb[1] / sizeof(float);
+ const cl_ulong spv2 = src_pv->nb[2] / sizeof(float);
+ const cl_ulong spv3 = src_pv->nb[3] / sizeof(float);
+ const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float);
+ const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float);
+ const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float);
+
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device));
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep));
+ }
+ CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K));
// Subgroup size is 64 for Adreno and 32 for Intel
const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1;
diff --git a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl
index 319c98295..78b807cfd 100644
--- a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl
+++ b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl
@@ -18,6 +18,9 @@
#ifndef KDA
#define KDA 0
#endif
+#ifndef REPLAY
+#define REPLAY 0
+#endif
#ifndef SUBGROUP_SIZE
#define SUBGROUP_SIZE 64
#endif
@@ -97,6 +100,13 @@ kernel void kernel_gated_delta_net(
uint H_k,
uint rq3,
float scale,
+#if REPLAY
+ uint n_pend, uint keep,
+ global const char * pk_buf, ulong off_pk, ulong spk1, ulong spk2, ulong spk3,
+ global const char * pv_buf, ulong off_pv, ulong spv1, ulong spv2, ulong spv3,
+ global const char * pgb_buf, ulong off_pgb, ulong spg1, ulong spg2, ulong spg3,
+ global const char * rep_buf, ulong off_rep,
+#endif
uint K) {
global const float * data_q = (global const float *)(q_buf + off_q);
@@ -144,6 +154,77 @@ kernel void kernel_gated_delta_net(
}
}
+#if REPLAY
+ global const float * data_pk = (global const float *)(pk_buf + off_pk);
+ global const float * data_pv = (global const float *)(pv_buf + off_pv);
+ global const float * data_pgb = (global const float *)(pgb_buf + off_pgb);
+ global const int * data_n_rep = (global const int *)(rep_buf + off_rep);
+ const uint n_r = (uint)clamp(data_n_rep[seq_id], 0, (int)n_pend);
+
+ for (uint t = 0; t < n_r; t++) {
+ const ulong k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
+ const ulong v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
+ const ulong g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
+ const float beta_val = data_pgb[g_off + n_pend * spg2];
+
+ float k_reg[ROWS_PER_LANE];
+ #pragma unroll
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ k_reg[r] = data_pk[k_off + r * LANES_PER_COLUMN + lane];
+ }
+
+#if KDA
+ float g_exp[ROWS_PER_LANE];
+ #pragma unroll
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ g_exp[r] = exp(data_pgb[g_off + r * LANES_PER_COLUMN + lane]);
+ }
+#else
+ const float g_val = exp(data_pgb[g_off]);
+#endif
+
+ // Same state update as the main loop, without the attention output.
+ #pragma unroll
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
+ float kv_shard = 0.0f;
+ #pragma unroll
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
+#if KDA
+ kv_shard += g_exp[r] * s_shard[cg][r] * k_reg[r];
+#else
+ kv_shard += s_shard[cg][r] * k_reg[r];
+#endif
+ }
+#if !KDA
+ kv_shard *= g_val;
+#endif
+ const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid);
+ const float delta_col = (data_pv[v_off + col] - kv_col) * beta_val;
+ #pragma unroll
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
+#if KDA
+ const float gs = g_exp[r] * s_shard[cg][r];
+#else
+ const float gs = g_val * s_shard[cg][r];
+#endif
+ s_shard[cg][r] = gs + k_reg[r] * delta_col;
+ }
+ }
+ }
+
+ if (keep) {
+ #pragma unroll
+ for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
+ const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group;
+ #pragma unroll
+ for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r];
+ }
+ }
+ }
+#endif
+
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V;
@@ -236,6 +317,11 @@ kernel void kernel_gated_delta_net(
}
}
+#if REPLAY
+ if (keep) {
+ return;
+ }
+#endif
if (K == 1u) {
#pragma unroll
for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) {
diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp
index 7e64c03c2..e1ba0baeb 100644
--- a/ggml/src/ggml-openvino/ggml-openvino.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp
@@ -2113,6 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
}
return {false, reason};
}
+ if (((const int32_t *) op->op_params)[1] != 0) {
+ return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"};
+ }
break;
}
case GGML_OP_SSM_SCAN: {
diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp
index 75df12c73..12d1bdfba 100644
--- a/ggml/src/ggml-sycl/ggml-sycl.cpp
+++ b/ggml/src/ggml-sycl/ggml-sycl.cpp
@@ -7709,10 +7709,12 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_RWKV_WKV6:
case GGML_OP_RWKV_WKV7:
case GGML_OP_GATED_LINEAR_ATTN:
- case GGML_OP_GATED_DELTA_NET:
case GGML_OP_OPT_STEP_ADAMW:
case GGML_OP_OPT_STEP_SGD:
return true;
+ case GGML_OP_GATED_DELTA_NET:
+ // replay of pending tokens (op param 1) is not implemented
+ return ggml_get_op_params_i32(op, 1) == 0;
case GGML_OP_SSM_CONV:
return op->type == GGML_TYPE_F32 &&
op->src[0]->type == GGML_TYPE_F32 &&
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
index 79258b871..42f058bd8 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp
@@ -1370,9 +1370,10 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
} else if (tensor->op == GGML_OP_LIGHTNING_INDEXER) {
tensor_clone = ggml_lightning_indexer(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3]);
} else if (tensor->op == GGML_OP_GATED_DELTA_NET) {
- tensor_clone = ggml_gated_delta_net(ggml_ctx, src_clone[0], src_clone[1],
- src_clone[2], src_clone[3], src_clone[4], src_clone[5],
- ggml_get_op_params_i32(tensor, 0));
+ GGML_ASSERT(ggml_get_op_params_i32(tensor, 0) == 1); // K > 1 comes from the deprecated ggml_gated_delta_net
+ tensor_clone = ggml_gated_delta_net_ext(ggml_ctx, src_clone[0], src_clone[1],
+ src_clone[2], src_clone[3], src_clone[4], src_clone[5], src_clone[6], src_clone[7], src_clone[8], src_clone[9],
+ ggml_get_op_params_i32(tensor, 2) != 0);
} else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
src_clone[0]->flags = tensor->src[0]->flags;
tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
index 7a48c08dc..026ad8935 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
@@ -794,6 +794,10 @@ struct vk_op_gated_delta_net_push_constants {
uint32_t neq1, rq3;
float scale;
uint32_t K;
+ uint32_t n_pend, keep; // replay: pending tokens per seq, write the state after the replay
+ uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats
+ uint32_t spv1, spv2, spv3;
+ uint32_t spg1, spg2, spg3;
};
struct vk_op_ssm_scan_push_constants {
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
index 211948ee7..f200b43d3 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
@@ -1013,8 +1013,8 @@ struct vk_device_struct {
vk_pipeline pipeline_rwkv_wkv7_f32;
vk_pipeline pipeline_gated_linear_attn_f32;
vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT];
- // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
- vk_pipeline pipeline_gated_delta_net[4][2];
+ // [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128
+ vk_pipeline pipeline_gated_delta_net[4][2][2];
vk_pipeline pipeline_gated_delta_net_cm;
vk_pipeline pipeline_gated_delta_net_cm_v32;
vk_pipeline pipeline_gated_delta_net_cm_v128;
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
index 0711166f9..88e595f4a 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp
+++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
@@ -4212,9 +4212,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
const std::array<uint32_t, 3> wg_denoms = {1u, 1u, cols_per_wg};
for (uint32_t kda = 0; kda < 2; kda++) {
- ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda],
- gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants),
- wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size);
+ for (uint32_t rep = 0; rep < 2; rep++) {
+ const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : "");
+ ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep],
+ name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants),
+ wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size);
+ }
}
}
@@ -10235,6 +10238,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
const uint32_t S_v = dst->src[2]->ne[0];
const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0;
+ const uint32_t rep = dst->src[6] != nullptr ? 1 : 0;
uint32_t si;
switch (S_v) {
case 16: si = 0; break;
@@ -10243,7 +10247,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const
case 128: si = 3; break;
default: return nullptr;
}
- return ctx->device->pipeline_gated_delta_net[si][kda];
+ return ctx->device->pipeline_gated_delta_net[si][kda][rep];
}
return nullptr;
case GGML_OP_SSM_SCAN:
@@ -11357,7 +11361,8 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr ||
ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) &&
- src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens;
+ src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens &&
+ dst->src[6] == nullptr; // the chunked kernels do not replay
const bool use_cm2 = use_cm && ctx->device->coopmat2;
const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr;
@@ -11389,9 +11394,10 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
- vk_subbuffer src_buf[6] = {};
- for (int i = 0; i < 6; i++) {
- src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
+ vk_subbuffer src_buf[10] = {};
+ for (int i = 0; i < 10; i++) {
+ // the replay sources 6..9 bind q when the op has no replay
+ src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i] ? dst->src[i] : src_q);
}
vk_subbuffer mirror_buf{};
@@ -11409,6 +11415,11 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size };
}
+ // replay of pending tokens, see ggml_gated_delta_net_ext
+ const ggml_tensor * src_pk = dst->src[6];
+ const ggml_tensor * src_pv = dst->src[7];
+ const ggml_tensor * src_pgb = dst->src[8];
+
const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float));
const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float));
const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float));
@@ -11434,7 +11445,18 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
sb1, sb2, sb3,
neq1, rq3,
scale,
- K
+ K,
+ src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u,
+ src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u,
+ src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u,
+ src_pk ? (uint32_t)(src_pk->nb[2] / sizeof(float)) : 0u,
+ src_pk ? (uint32_t)(src_pk->nb[3] / sizeof(float)) : 0u,
+ src_pv ? (uint32_t)(src_pv->nb[1] / sizeof(float)) : 0u,
+ src_pv ? (uint32_t)(src_pv->nb[2] / sizeof(float)) : 0u,
+ src_pv ? (uint32_t)(src_pv->nb[3] / sizeof(float)) : 0u,
+ src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u,
+ src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u,
+ src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u,
};
if (use_v128) {
@@ -11442,10 +11464,15 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf},
pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
ctx->prealloc_x_need_sync = true;
- } else {
+ } else if (use_cm) {
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
- pc, use_cm ? std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H } : std::array<uint32_t, 3>{ H, n_seqs, S_v });
+ pc, std::array<uint32_t, 3>{ S_v / cm_V, n_seqs, H });
+ } else {
+ ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
+ {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf,
+ src_buf[6], src_buf[7], src_buf[8], src_buf[9]},
+ pc, std::array<uint32_t, 3>{ H, n_seqs, S_v });
}
}
@@ -11692,9 +11719,10 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
const uint64_t n = ggml_nelements(dst);
GGML_ASSERT(n > 0);
+ // dst can be a view at any offset: bind from the aligned offset below it, the shader skips KY elements
vk_op_push_constants pc = {
(uint32_t)n,
- 1,
+ get_misalign_bytes(ctx, dst) / (uint32_t)ggml_type_size(dst->type),
ggml_get_op_params_f32(dst, 0),
0.0f,
0.0f, 0.0f,
@@ -11710,7 +11738,7 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor
GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
- vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
+ vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
std::array<uint32_t, 3> elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 };
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp
index b5cc33322..bfae6a3d1 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp
@@ -16,6 +16,6 @@ void main() {
return;
}
- // p.param1 = fill value
- data_d[i] = D_TYPE(p.param1);
+ // p.param1 = fill value, p.KY = element offset of dst in the bound buffer
+ data_d[p.KY + i] = D_TYPE(p.param1);
}
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp
index ad2ced78a..75c32a067 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp
@@ -16,6 +16,7 @@ layout(constant_id = 1) const uint KDA = 0;
layout(constant_id = 2) const uint SUBGROUP_SIZE = 32;
layout(constant_id = 3) const uint LANES_PER_COLUMN = 32;
layout(constant_id = 4) const bool PACKED_ROWS = false;
+layout(constant_id = 5) const uint REPLAY = 0;
const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN;
const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN;
@@ -42,6 +43,10 @@ layout(push_constant) uniform Parameters {
uint neq1, rq3;
float scale;
uint K;
+ uint n_pend, keep;
+ uint spk1, spk2, spk3;
+ uint spv1, spv2, spv3;
+ uint spg1, spg2, spg3;
};
layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; };
@@ -52,6 +57,12 @@ layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; };
layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; };
layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; };
+// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
+layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; };
+layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; };
+layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; };
+layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; };
+
#if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED
shared FLOAT_TYPE temp[SUBGROUP_SIZE];
@@ -123,6 +134,55 @@ void main() {
s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]);
}
+ if (REPLAY != 0) {
+ const uint n_r = uint(clamp(data_n_rep[seq_id], 0, int(n_pend)));
+
+ for (uint t = 0; t < n_r; t++) {
+ const uint k_off = seq_id * spk3 + t * spk2 + iq1 * spk1;
+ const uint v_off = seq_id * spv3 + t * spv2 + head_id * spv1;
+ const uint g_off = seq_id * spg3 + t * spg2 + head_id * spg1;
+ const FLOAT_TYPE beta_val = FLOAT_TYPE(data_pgb[g_off + n_pend * spg2]);
+
+ FLOAT_TYPE k_reg[ROWS_PER_LANE];
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ k_reg[r] = FLOAT_TYPE(data_pk[k_off + row_index(r, lane)]);
+ }
+
+ FLOAT_TYPE g_exp[ROWS_PER_LANE];
+ if (KDA == 0) {
+ const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_pgb[g_off]));
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ g_exp[r] = g_val;
+ }
+ } else {
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ g_exp[r] = exp(FLOAT_TYPE(data_pgb[g_off + row_index(r, lane)]));
+ }
+ }
+
+ const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]);
+
+ // same update as below, without the attention output
+ FLOAT_TYPE kv_shard = 0.0;
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ kv_shard += g_exp[r] * s_shard[r] * k_reg[r];
+ }
+ FLOAT_TYPE kv_col = reduce_partial(kv_shard);
+
+ FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val;
+
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col;
+ }
+ }
+
+ if (keep != 0) {
+ [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
+ data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
+ }
+ }
+ }
+
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K, only slots 0..n_tokens-1 are written; older slots are caller-owned.
@@ -191,7 +251,8 @@ void main() {
}
}
- if (K == 1u) {
+ // replay with keep: the state output is the state after the replay
+ if (K == 1u && !(REPLAY != 0 && keep != 0)) {
[[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) {
data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r];
}
diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
index 8896efb5a..6b618bb16 100644
--- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
+++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp
@@ -450,9 +450,11 @@ struct ggml_webgpu_gated_delta_net_pipeline_key {
int s_v;
int kda;
bool fused_cache;
+ bool replay;
bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const {
- return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache;
+ return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache &&
+ replay == other.replay;
}
};
@@ -462,6 +464,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash {
ggml_webgpu_hash_combine(seed, key.type);
ggml_webgpu_hash_combine(seed, key.s_v);
ggml_webgpu_hash_combine(seed, key.kda);
+ ggml_webgpu_hash_combine(seed, key.replay);
return seed;
}
};
@@ -2015,6 +2018,7 @@ class ggml_webgpu_shader_lib {
key.s_v = (int) context.src2->ne[0];
key.kda = context.src3->ne[0] == context.src2->ne[0];
key.fused_cache = context.dst_fuse != nullptr;
+ key.replay = context.dst->src[6] != nullptr;
auto it = gated_delta_net_pipelines.find(key);
if (it != gated_delta_net_pipelines.end()) {
@@ -2042,6 +2046,11 @@ class ggml_webgpu_shader_lib {
variant += "_fused_cache";
}
+ if (key.replay) {
+ defines.push_back("REPLAY");
+ variant += "_replay";
+ }
+
defines.push_back("S_V=" + std::to_string(key.s_v) + "u");
defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u");
diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
index 4bb43926d..daf83ee83 100644
--- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp
+++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp
@@ -1497,6 +1497,11 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx,
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y);
}
+// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs
+static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) {
+ return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0);
+}
+
static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
ggml_tensor * src0,
ggml_tensor * src1,
@@ -1527,6 +1532,12 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
uint32_t scale_u32;
memcpy(&scale_u32, &scale, sizeof(scale_u32));
+ // replay of pending tokens, see ggml_gated_delta_net_ext
+ ggml_tensor * pend_k = dst->src[6];
+ ggml_tensor * pend_v = dst->src[7];
+ ggml_tensor * pend_gb = dst->src[8];
+ ggml_tensor * n_rep = dst->src[9];
+
std::vector<uint32_t> params = {
h,
n_tokens,
@@ -1551,6 +1562,21 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
scale_u32,
dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0,
dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0,
+
+ pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0,
+ pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0,
+
+ pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0,
+ pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0,
+ pend_k ? (uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)) : 0,
+
+ pend_v ? (uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)) : 0,
+ pend_v ? (uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)) : 0,
+ pend_v ? (uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)) : 0,
+
+ pend_gb ? (uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)) : 0,
+ pend_gb ? (uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)) : 0,
+ pend_gb ? (uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)) : 0,
};
std::vector<wgpu::BindGroupEntry> entries = {
@@ -1564,6 +1590,14 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx,
entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse));
}
+ if (pend_k) {
+ const uint32_t binding = dst_fuse ? 8 : 7;
+ entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k));
+ entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v));
+ entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb));
+ entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep));
+ }
+
return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs);
}
@@ -3728,7 +3762,9 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6],
node);
case GGML_OP_GATED_DELTA_NET:
- if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
+ if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
+ ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
+ ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
@@ -5270,7 +5306,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 &&
op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 &&
s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup &&
- ggml_are_same_stride(src0, src1);
+ ggml_are_same_stride(src0, src1) &&
+ ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <=
+ ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage;
}
break;
case GGML_OP_CLAMP:
diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl
index 6f4b5a31c..1a5b3208b 100644
--- a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl
+++ b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl
@@ -23,10 +23,31 @@ var<storage, read_write> dst: array<f32>;
@group(0) @binding(7)
var<storage, read_write> dst_fuse: array<f32>;
#define DST_SNAP dst_fuse
-#define PARAMS_BINDING 8
+#define NEXT_BINDING 8
#else
#define DST_SNAP dst
-#define PARAMS_BINDING 7
+#define NEXT_BINDING 7
+#endif
+
+#ifdef REPLAY
+// pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
+@group(0) @binding(NEXT_BINDING)
+var<storage, read_write> pend_k: array<f32>;
+
+@group(0) @binding(NEXT_BINDING + 1)
+var<storage, read_write> pend_v: array<f32>;
+
+@group(0) @binding(NEXT_BINDING + 2)
+var<storage, read_write> pend_gb: array<f32>;
+
+@group(0) @binding(NEXT_BINDING + 3)
+var<storage, read_write> n_rep: array<i32>;
+
+var<workgroup> wg_n_rep: u32;
+
+#define PARAMS_BINDING (NEXT_BINDING + 4)
+#else
+#define PARAMS_BINDING NEXT_BINDING
#endif
struct Params {
@@ -53,6 +74,21 @@ struct Params {
scale: f32,
dst_fuse_nb2: u32,
dst_fuse_off: u32,
+
+ n_pend: u32,
+ keep: u32,
+
+ spk1: u32,
+ spk2: u32,
+ spk3: u32,
+
+ spv1: u32,
+ spv2: u32,
+ spv3: u32,
+
+ spg1: u32,
+ spg2: u32,
+ spg3: u32,
};
@group(0) @binding(PARAMS_BINDING)
@@ -92,6 +128,66 @@ fn main(
state[i] = src_state[state_in_base + col * S_V + i];
}
+#ifdef REPLAY
+ if (col == 0u) {
+ wg_n_rep = u32(n_rep[seq_id]);
+ }
+ let n_r = workgroupUniformLoad(&wg_n_rep);
+
+ for (var t = 0u; t < n_r; t++) {
+ let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1;
+ let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1;
+ let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1;
+
+ sh_k[col] = pend_k[k_off + col];
+
+#ifdef KDA
+ sh_g[col] = exp(pend_gb[g_off + col]);
+#endif
+
+ workgroupBarrier();
+
+ let v_val = pend_v[v_off + col];
+ let beta_val = pend_gb[g_off + params.n_pend * params.spg2];
+
+ // same update as below, without the attention output
+ var kv_col = 0.0;
+ var delta_col = 0.0;
+
+#ifdef KDA
+ for (var i = 0u; i < S_V; i++) {
+ kv_col += (sh_g[i] * state[i]) * sh_k[i];
+ }
+
+ delta_col = (v_val - kv_col) * beta_val;
+
+ for (var i = 0u; i < S_V; i++) {
+ state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col;
+ }
+#else
+ let g_val = exp(pend_gb[g_off]);
+
+ for (var i = 0u; i < S_V; i++) {
+ kv_col += state[i] * sh_k[i];
+ }
+
+ delta_col = (v_val - g_val * kv_col) * beta_val;
+
+ for (var i = 0u; i < S_V; i++) {
+ state[i] = g_val * state[i] + sh_k[i] * delta_col;
+ }
+#endif
+
+ workgroupBarrier();
+ }
+
+ if (params.keep != 0u) {
+ for (var i = 0u; i < S_V; i++) {
+ DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
+ }
+ }
+#endif
+
var attn_off = (seq_id * params.n_tokens * params.h + head_id) * S_V;
for (var t = 0u; t < params.n_tokens; t++) {
@@ -160,7 +256,14 @@ fn main(
workgroupBarrier();
}
- if (params.K == 1u) {
+#ifdef REPLAY
+ // replay with keep: the state output is the state after the replay
+ let write_state = params.K == 1u && params.keep == 0u;
+#else
+ let write_state = params.K == 1u;
+#endif
+
+ if (write_state) {
for (var i = 0u; i < S_V; i++) {
DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i];
}
diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
index 947342125..88ade6e8a 100644
--- a/ggml/src/ggml.c
+++ b/ggml/src/ggml.c
@@ -6373,7 +6373,7 @@ struct ggml_tensor * ggml_solve_tri(
// ggml_gated_delta_net
-struct ggml_tensor * ggml_gated_delta_net(
+static struct ggml_tensor * ggml_gated_delta_net_impl(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -6381,7 +6381,12 @@ struct ggml_tensor * ggml_gated_delta_net(
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
- int64_t K) {
+ struct ggml_tensor * pend_k,
+ struct ggml_tensor * pend_v,
+ struct ggml_tensor * pend_gb,
+ struct ggml_tensor * n_rep,
+ int64_t K,
+ bool keep) {
GGML_ASSERT(ggml_is_contiguous_rows(q));
GGML_ASSERT(ggml_is_contiguous_rows(k));
GGML_ASSERT(ggml_is_contiguous_rows(v));
@@ -6425,9 +6430,61 @@ struct ggml_tensor * ggml_gated_delta_net(
result->src[4] = beta;
result->src[5] = state;
+ const bool replay = pend_k != NULL;
+ GGML_ASSERT((pend_v != NULL) == replay && (pend_gb != NULL) == replay && (n_rep != NULL) == replay);
+ GGML_ASSERT(replay || !keep);
+ if (replay) {
+ const int64_t n_pend = pend_k->ne[2];
+
+ GGML_ASSERT(K == 1);
+ GGML_ASSERT(pend_k->type == GGML_TYPE_F32 && pend_v->type == GGML_TYPE_F32 && pend_gb->type == GGML_TYPE_F32);
+ GGML_ASSERT(n_rep->type == GGML_TYPE_I32);
+ GGML_ASSERT(pend_k->nb[0] == sizeof(float) && pend_v->nb[0] == sizeof(float) && pend_gb->nb[0] == sizeof(float));
+ GGML_ASSERT(pend_k->ne[0] == k->ne[0] && pend_k->ne[1] == k->ne[1] && pend_k->ne[3] == n_seqs);
+ GGML_ASSERT(pend_v->ne[0] == S_v && pend_v->ne[1] == H && pend_v->ne[2] == n_pend && pend_v->ne[3] == n_seqs);
+ GGML_ASSERT(pend_gb->ne[0] == g->ne[0] && pend_gb->ne[1] == H && pend_gb->ne[2] == 2*n_pend && pend_gb->ne[3] == n_seqs);
+ GGML_ASSERT(ggml_is_contiguous(n_rep) && ggml_nelements(n_rep) == n_seqs);
+
+ ggml_set_op_params_i32(result, 1, (int32_t) n_pend);
+ ggml_set_op_params_i32(result, 2, keep ? 1 : 0);
+
+ result->src[6] = pend_k;
+ result->src[7] = pend_v;
+ result->src[8] = pend_gb;
+ result->src[9] = n_rep;
+ }
+
return result;
}
+struct ggml_tensor * ggml_gated_delta_net_ext(
+ struct ggml_context * ctx,
+ struct ggml_tensor * q,
+ struct ggml_tensor * k,
+ struct ggml_tensor * v,
+ struct ggml_tensor * g,
+ struct ggml_tensor * beta,
+ struct ggml_tensor * state,
+ struct ggml_tensor * pend_k,
+ struct ggml_tensor * pend_v,
+ struct ggml_tensor * pend_gb,
+ struct ggml_tensor * n_rep,
+ bool keep) {
+ return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, pend_k, pend_v, pend_gb, n_rep, 1, keep);
+}
+
+struct ggml_tensor * ggml_gated_delta_net(
+ struct ggml_context * ctx,
+ struct ggml_tensor * q,
+ struct ggml_tensor * k,
+ struct ggml_tensor * v,
+ struct ggml_tensor * g,
+ struct ggml_tensor * beta,
+ struct ggml_tensor * state,
+ int64_t K) {
+ return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, NULL, NULL, NULL, NULL, K, false);
+}
+
// ggml_lightning_indexer
struct ggml_tensor * ggml_lightning_indexer(
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 07a0dbafc..4caca65f3 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -190,6 +190,14 @@ llama_context::llama_context(
cparams.n_rs_seq = 0;
}
+ // delta-net rollback keeps one state and the inputs of the last ubatch; the gdn op replays the kept tokens before the new ones
+ cparams.rs_replay = cparams.n_rs_seq > 0 && (
+ model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE || model.arch == LLM_ARCH_QWEN4EXP ||
+ model.arch == LLM_ARCH_CLOVER_MOE ||
+ // KDA
+ model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT ||
+ model.arch == LLM_ARCH_BAILINGMOE3);
+
cparams.n_threads = params.n_threads;
cparams.n_threads_batch = params.n_threads_batch;
cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor;
@@ -435,6 +443,7 @@ llama_context::llama_context(
LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
LLAMA_LOG_INFO("%s: n_rs_seq = %u\n", __func__, cparams.n_rs_seq);
+ LLAMA_LOG_INFO("%s: rs_replay = %s\n", __func__, cparams.rs_replay ? "true" : "false");
LLAMA_LOG_INFO("%s: n_outputs_max = %u\n", __func__, cparams.n_outputs_max);
LLAMA_LOG_INFO("%s: n_outputs_max_per_seq = %u\n", __func__, cparams.n_outputs_max_per_seq);
diff --git a/src/llama-cparams.h b/src/llama-cparams.h
index c93494faf..c71582a3c 100644
--- a/src/llama-cparams.h
+++ b/src/llama-cparams.h
@@ -14,6 +14,7 @@ struct llama_cparams {
uint32_t n_ubatch;
uint32_t n_seq_max;
uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback
+ bool rs_replay; // roll back by replaying kept tokens instead of keeping n_rs_seq snapshots
uint32_t n_outputs_max; // max outputs supported by the context
uint32_t n_outputs_max_per_seq;
int32_t n_threads; // number of threads to use for generation
diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp
index 862476a5f..5fef4c421 100644
--- a/src/llama-graph.cpp
+++ b/src/llama-graph.cpp
@@ -527,8 +527,6 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
}
void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
- GGML_UNUSED(ubatch);
-
const int64_t n_rs = mctx->get_n_rs();
if (s_copy) {
@@ -540,6 +538,34 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->s_copy(i);
}
}
+
+ set_input_rep(mctx, ubatch);
+}
+
+void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch) {
+ if (!has_rep) {
+ return;
+ }
+
+ const int64_t n_seqs = ubatch->n_seqs;
+
+ int32_t * reps = (int32_t *) rep_n->data;
+ int32_t * cols = (int32_t *) rep_cols->data;
+
+ GGML_ASSERT(ggml_backend_buffer_is_host(rep_n->buffer));
+ GGML_ASSERT(ggml_backend_buffer_is_host(rep_cols->buffer));
+
+ for (int64_t s = 0; s < n_seqs; ++s) {
+ const int64_t n_rep = mctx->get_rs_rep(s);
+ GGML_ASSERT(n_rep <= n_pend);
+
+ reps[s] = n_rep;
+
+ // the conv history is [window | pending]: the window after the kept tokens
+ for (int64_t c = 0; c < n_conv; ++c) {
+ cols[s*n_conv + c] = n_rep + c;
+ }
+ }
}
bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
@@ -1261,6 +1287,8 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
+
+ inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
@@ -1307,6 +1335,8 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
+
+ inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) {
@@ -1364,6 +1394,8 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) {
data[i] = mctx->get_recr()->s_copy(i);
}
}
+
+ inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) {
@@ -1443,6 +1475,8 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch)
data[i] = mctx->get_recr()->s_copy(i);
}
}
+
+ inp_rs->set_input_rep(mctx->get_recr(), ubatch);
}
bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) {
@@ -4136,6 +4170,8 @@ ggml_tensor * llm_graph_context::build_rs(
static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
ggml_context * ctx0,
const llama_ubatch & ubatch,
+ const llama_hparams & hparams,
+ const llama_cparams & cparams,
const llama_memory_recurrent_context * mctx_cur) {
auto inp = std::make_unique<llm_graph_input_rs>(mctx_cur);
@@ -4153,13 +4189,38 @@ static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
inp->head = mctx_cur->get_head();
inp->rs_z = mctx_cur->get_rs_z();
+ inp->has_rep = mctx_cur->get_rs_replay();
+ if (inp->has_rep) {
+ // the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp)
+ const int64_t n_conv_r = hparams.ssm_d_conv - 1;
+ const int64_t n_conv_p = hparams.ple_conv_state() > 0 ? (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size : 0;
+
+ inp->n_conv = std::max(n_conv_r, n_conv_p);
+ inp->n_pend = cparams.n_rs_seq + 1;
+
+ inp->rep_cols = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->n_conv, n_seqs);
+ ggml_set_input(inp->rep_cols);
+ ggml_set_name(inp->rep_cols, "rs_rep_cols");
+
+ const auto win = [&](int64_t n) {
+ return n == inp->n_conv ? inp->rep_cols : ggml_view_2d(ctx0, inp->rep_cols, n, n_seqs, inp->rep_cols->nb[1], 0);
+ };
+
+ inp->rep_cols_r = win(n_conv_r);
+ inp->rep_cols_p = n_conv_p > 0 ? win(n_conv_p) : nullptr;
+
+ inp->rep_n = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seqs);
+ ggml_set_input(inp->rep_n);
+ ggml_set_name(inp->rep_n, "rs_rep_n");
+ }
+
return inp;
}
llm_graph_input_rs * llm_graph_context::build_rs_inp() const {
const auto * mctx_cur = static_cast<const llama_memory_recurrent_context *>(mctx);
- auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur);
+ auto inp = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur);
return (llm_graph_input_rs *) res->add_input(std::move(inp));
}
@@ -4286,7 +4347,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store(
llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
- auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
+ auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4297,7 +4358,7 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const {
llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_context *>(mctx);
- auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr());
+ auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn());
auto inp = std::make_unique<llm_graph_input_mem_hybrid_k>(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur);
@@ -4308,7 +4369,7 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const
llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
- auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
+ auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
// build iswa attention input
const auto * attn_ctx = mctx_cur->get_attn();
@@ -4345,7 +4406,7 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is
uint32_t extent_swa) const {
const auto * mctx_cur = static_cast<const llama_memory_hybrid_iswa_context *>(mctx);
- auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr());
+ auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr());
const auto * attn_ctx = mctx_cur->get_attn();
diff --git a/src/llama-graph.h b/src/llama-graph.h
index 116b7132a..ff155f14d 100644
--- a/src/llama-graph.h
+++ b/src/llama-graph.h
@@ -323,6 +323,19 @@ public:
ggml_tensor * s_copy_main; // I32 [n_seqs]
ggml_tensor * s_copy_tail; // I32 [n_rs - 1]
+ // rs_replay: the ubatch first replays the kept pending tokens of the last ubatch (none is a no-op)
+ bool has_rep = false;
+ int64_t n_conv = 0; // conv window columns, the widest conv of the model
+ int64_t n_pend = 0; // pending slots per seq
+ ggml_tensor * rep_n = nullptr; // I32 [n_seqs], kept pending tokens
+ ggml_tensor * rep_cols = nullptr; // I32 [n_conv, n_seqs], conv history columns of the window after the kept tokens
+
+ // views of rep_cols for the delta-net conv and the PLE conv windows, computed once per graph and shared across layers
+ ggml_tensor * rep_cols_r = nullptr;
+ ggml_tensor * rep_cols_p = nullptr;
+
+ void set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch);
+
const llama_memory_recurrent_context * mctx;
// used in view offsets, need to match for valid graph reuse
diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp
index 0199c734e..3866d5980 100644
--- a/src/llama-memory-hybrid-idx.cpp
+++ b/src/llama-memory-hybrid-idx.cpp
@@ -33,6 +33,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -44,7 +45,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx(
no_alloc,
type_k, type_v, v_trans, kv_size, n_swa, swa_type,
type_r, type_s, rs_size,
- n_seq_max, n_rs_seq, offload, unified,
+ n_seq_max, n_rs_seq, rs_replay, offload, unified,
filter_attn, filter_recr),
hparams_idx(model.hparams),
mem_idx(filter_idx == nullptr ? nullptr : [&] {
diff --git a/src/llama-memory-hybrid-idx.h b/src/llama-memory-hybrid-idx.h
index 85a2a91ec..ebd082ab5 100644
--- a/src/llama-memory-hybrid-idx.h
+++ b/src/llama-memory-hybrid-idx.h
@@ -33,6 +33,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
bool offload,
bool unified,
/* layer filters */
diff --git a/src/llama-memory-hybrid-iswa.cpp b/src/llama-memory-hybrid-iswa.cpp
index 6d843c76e..569a09ee2 100644
--- a/src/llama-memory-hybrid-iswa.cpp
+++ b/src/llama-memory-hybrid-iswa.cpp
@@ -59,6 +59,7 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa(
rs_size,
n_seq_max,
n_rs_seq,
+ false,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp
index 7d3b27908..a93e256b0 100644
--- a/src/llama-memory-hybrid.cpp
+++ b/src/llama-memory-hybrid.cpp
@@ -25,6 +25,7 @@ llama_memory_hybrid::llama_memory_hybrid(
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
bool offload,
bool unified,
/* layer filters */
@@ -60,6 +61,7 @@ llama_memory_hybrid::llama_memory_hybrid(
rs_size,
n_seq_max,
n_rs_seq,
+ rs_replay,
filter_recr == nullptr ?
[&](int32_t il) { return hparams.is_recr(il); }
: filter_recr
diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h
index 2b4d1269c..b4df21f15 100644
--- a/src/llama-memory-hybrid.h
+++ b/src/llama-memory-hybrid.h
@@ -35,6 +35,7 @@ public:
/* common */
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
bool offload,
bool unified,
/* layer filters */
diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp
index 0d5739695..bab6276f6 100644
--- a/src/llama-memory-recurrent.cpp
+++ b/src/llama-memory-recurrent.cpp
@@ -26,6 +26,7 @@ llama_memory_recurrent::llama_memory_recurrent(
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max), ctxs_bufs(no_alloc) {
const int32_t n_layer = hparams.n_layer();
@@ -33,7 +34,8 @@ llama_memory_recurrent::llama_memory_recurrent(
size = mem_size;
used = 0;
- this->n_rs_seq = n_rs_seq;
+ this->n_rs_seq = n_rs_seq;
+ this->rs_replay = rs_replay && n_rs_seq > 0;
rs_idx.assign(n_seq_max, 0);
cells.clear();
@@ -53,7 +55,7 @@ llama_memory_recurrent::llama_memory_recurrent(
if (it == ctx_map.end()) {
ggml_init_params params = {
// r and s per layer, plus the separate PLE conv row where the model has one
- /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 3u : 2u)*n_layer*ggml_tensor_overhead()),
+ /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 6u : 5u)*n_layer*ggml_tensor_overhead()),
/*.mem_buffer =*/ NULL,
/*.no_alloc =*/ true,
};
@@ -74,6 +76,9 @@ llama_memory_recurrent::llama_memory_recurrent(
r_l.resize(n_layer);
s_l.resize(n_layer);
p_l.resize(n_layer);
+ spk_l.resize(n_layer);
+ spv_l.resize(n_layer);
+ spgb_l.resize(n_layer);
for (int i = 0; i < n_layer; i++) {
if (filter && !filter(i)) {
@@ -99,17 +104,45 @@ llama_memory_recurrent::llama_memory_recurrent(
throw std::runtime_error("failed to create ggml context for rs cache");
}
- const uint32_t n_rows = mem_size * (1 + n_rs_seq);
- ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows);
+ // rs_replay: r is the conv history [channels, d_conv - 1 + n_pend], the window then the pending columns,
+ // and spk, spv, spgb hold the gdn k, v, gate and beta of up to n_pend pending tokens
+ const int64_t n_pend = n_rs_seq + 1;
+ const int64_t n_ch = hparams.n_embd_r() / std::max<int64_t>(1, hparams.ssm_d_conv - 1);
+ const int64_t n_embd_r = this->rs_replay ? n_ch*(hparams.ssm_d_conv - 1 + n_pend) : hparams.n_embd_r();
+
+ const uint32_t n_rows = mem_size * (this->rs_replay ? 1 : 1 + n_rs_seq);
+ ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, n_embd_r, n_rows);
ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows);
ggml_format_name(r, "cache_r_l%d", i);
ggml_format_name(s, "cache_s_l%d", i);
r_l[i] = r;
s_l[i] = s;
+ if (this->rs_replay) {
+ // k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend]: separate rows, so that a split by heads
+ // is one axis of each (-sm tensor). The gate is a scalar per head (g0 = 1), or per key dim for KDA (g0 = S_v)
+ const bool kda = hparams.n_embd_head_kda != 0;
+ const int64_t n_k = kda ? (int64_t) hparams.n_embd_head_kda*hparams.n_head() : (int64_t) hparams.ssm_d_state*hparams.ssm_n_group;
+ const int64_t n_v = kda ? n_k : (int64_t) hparams.ssm_d_inner;
+ const int64_t n_gb = kda ? n_k : (int64_t) hparams.ssm_dt_rank;
+ ggml_tensor * spk = ggml_new_tensor_2d(ctx, type_s, n_k*n_pend, mem_size);
+ ggml_tensor * spv = ggml_new_tensor_2d(ctx, type_s, n_v*n_pend, mem_size);
+ ggml_tensor * spgb = ggml_new_tensor_2d(ctx, type_s, n_gb*2*n_pend, mem_size);
+ ggml_format_name(spk, "cache_spk_l%d", i);
+ ggml_format_name(spv, "cache_spv_l%d", i);
+ ggml_format_name(spgb, "cache_spgb_l%d", i);
+ spk_l[i] = spk;
+ spv_l[i] = spv;
+ spgb_l[i] = spgb;
+ }
+
// the PLE history needs its own row: Meta must mirror it while the delta-net conv state next door stays split
if (hparams.ple_conv_state() > 0 && hparams.is_ple(i)) {
- ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, hparams.ple_conv_state(), n_rows);
+ // rs_replay: [channels, window + n_pend], like r
+ const int64_t n_win_p = (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size;
+ const int64_t n_embd_p = this->rs_replay ? hparams.ple_conv_state()/n_win_p*(n_win_p + n_pend) : hparams.ple_conv_state();
+
+ ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, n_embd_p, n_rows);
ggml_format_name(p, "cache_ple_r_l%d", i);
p_l[i] = p;
}
@@ -124,7 +157,8 @@ llama_memory_recurrent::llama_memory_recurrent(
if (is_empty()) {
if (n_rs_seq > 0) {
- n_rs_seq = 0;
+ n_rs_seq = 0;
+ rs_replay = false;
LLAMA_LOG_INFO("%s: disabling rollback snapshots because the memory module is empty\n", __func__);
}
}
@@ -134,8 +168,8 @@ llama_memory_recurrent::llama_memory_recurrent(
const size_t memory_size_s = size_s_bytes();
const size_t memory_size_p = size_p_bytes();
- LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
- (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq,
+ LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq%s), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__,
+ (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, rs_replay ? " replay" : "",
ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f),
ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f),
ggml_type_name(type_r), (float)memory_size_p / (1024.0f * 1024.0f));
@@ -149,6 +183,8 @@ void llama_memory_recurrent::clear(bool data) {
cells[i].src = -1;
cells[i].tail = -1;
cells[i].rs_max = 0;
+ cells[i].rs_pend = 0;
+ cells[i].rs_rep = 0;
}
head = 0;
@@ -210,7 +246,13 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos
// pending rollback is single-use
const bool pending = rs_idx[seq_id] != 0;
if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) {
- set_rs_idx(seq_id, (uint32_t) rollback);
+ if (rs_replay) {
+ // the next ubatch replays only the kept pending tokens
+ cell.rs_pend -= rollback;
+ cell.rs_max = 0;
+ } else {
+ set_rs_idx(seq_id, (uint32_t) rollback);
+ }
cell.pos = p0 - 1;
return true;
}
@@ -615,6 +657,7 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
auto & orig_cell = cells[seq_meta.tail];
empty_cell.pos = orig_cell.pos;
empty_cell.src = orig_cell.src;
+ empty_cell.rs_pend = orig_cell.rs_pend;
orig_cell.seq_id.erase(seq_id);
empty_cell.seq_id.insert(seq_id); // will be overwritten
GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
@@ -645,7 +688,13 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
std::swap(dst_cell.pos, src_cell.pos);
std::swap(dst_cell.src, src_cell.src);
+ std::swap(dst_cell.rs_max, src_cell.rs_max);
+ std::swap(dst_cell.rs_pend, src_cell.rs_pend);
std::swap(dst_cell.seq_id, src_cell.seq_id);
+ // the cell moved out only gets its final state copied, its rollback snapshots stay behind
+ if (!rs_replay) {
+ src_cell.rs_max = 0;
+ }
// swap tails
for (uint32_t j = 0; j < size; ++j) {
@@ -674,6 +723,11 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
}
cell.pos = last_pos;
cell.rs_max = n_seq_tokens <= n_rs_seq + 1 ? n_seq_tokens - 1 : 0;
+ if (rs_replay) {
+ // replay what the last ubatch left pending, then keep this ubatch pending if it can be rolled back
+ cell.rs_rep = cell.src >= 0 ? cell.rs_pend : 0;
+ cell.rs_pend = cell.rs_max > 0 ? n_seq_tokens : 0;
+ }
cell.seq_id.clear();
for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
const llama_seq_id seq_id = ubatch.seq_id[i][j];
@@ -753,6 +807,7 @@ size_t llama_memory_recurrent::size_r_bytes() const {
}
}
+
return size_r_bytes;
}
@@ -765,6 +820,14 @@ size_t llama_memory_recurrent::size_s_bytes() const {
}
}
+ for (const auto * sp : { &spk_l, &spv_l, &spgb_l }) {
+ for (const auto & s : *sp) {
+ if (s != nullptr) {
+ size_s_bytes += ggml_nbytes(s);
+ }
+ }
+ }
+
return size_s_bytes;
}
@@ -907,6 +970,10 @@ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std::
io.write(&seq_id, sizeof(seq_id));
}
}
+
+ if (rs_replay) {
+ io.write(&cell.rs_pend, sizeof(cell.rs_pend));
+ }
}
}
}
@@ -929,7 +996,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
io.write(&r_type_i, sizeof(r_type_i));
// Write row size of R tensor
- const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
+ const uint64_t r_size_row = r_l[il]->nb[1];
io.write(&r_size_row, sizeof(r_size_row));
// Write each logical cell row range. With pending recurrent rollback,
@@ -942,7 +1009,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
// the PLE conv history is a second recurrent row, so it has to travel with the first
if (p_l[il] != nullptr) {
- const uint64_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
+ const uint64_t p_size_row = p_l[il]->nb[1];
io.write(&p_size_row, sizeof(p_size_row));
for (const auto & range : cell_ranges) {
@@ -1004,6 +1071,22 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
}
}
}
+
+ // rs_replay pending inputs travel with their cells
+ if (rs_replay) {
+ for (uint32_t il = 0; il < n_layer; ++il) {
+ for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
+ if (t == nullptr) continue;
+
+ const uint64_t size_row = t->nb[1];
+ io.write(&size_row, sizeof(size_row));
+
+ for (const auto & range : cell_ranges) {
+ io.write_tensor(t, range.first * size_row, (range.second - range.first) * size_row);
+ }
+ }
+ }
+ }
}
bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
@@ -1024,6 +1107,8 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
+ std::vector<uint32_t> rs_pend(cell_count, 0);
+
for (uint32_t i = 0; i < cell_count; ++i) {
llama_pos pos;
uint32_t n_seq_id;
@@ -1036,6 +1121,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
return false;
}
+ if (rs_replay) {
+ io.read(&rs_pend[i], sizeof(rs_pend[i]));
+ }
+
ubatch.pos[i] = pos;
}
ubatch.n_seq_id[0] = 1;
@@ -1053,6 +1142,11 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
+
+ for (uint32_t i = 0; i < cell_count; ++i) {
+ cells[head + i].rs_pend = rs_pend[i];
+ cells[head + i].rs_max = 0;
+ }
} else {
// whole KV cache restore
@@ -1092,6 +1186,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell
}
tail = i;
}
+
+ if (rs_replay) {
+ io.read(&cell.rs_pend, sizeof(cell.rs_pend));
+ }
}
head = 0;
@@ -1143,7 +1241,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
// Read row size of key
uint64_t r_size_row_ref;
io.read(&r_size_row_ref, sizeof(r_size_row_ref));
- const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
+ const size_t r_size_row = r_l[il]->nb[1];
if (r_size_row != r_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
return false;
@@ -1157,7 +1255,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
if (p_l[il] != nullptr) {
uint64_t p_size_row_ref;
io.read(&p_size_row_ref, sizeof(p_size_row_ref));
- const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
+ const size_t p_size_row = p_l[il]->nb[1];
if (p_size_row != p_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched ple row size (%zu != %zu, layer %d)\n", __func__, p_size_row, (size_t) p_size_row_ref, il);
return false;
@@ -1242,6 +1340,25 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
}
}
+ if (rs_replay) {
+ for (uint32_t il = 0; il < n_layer; ++il) {
+ for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) {
+ if (t == nullptr) continue;
+
+ uint64_t size_row_ref;
+ io.read(&size_row_ref, sizeof(size_row_ref));
+ if (size_row_ref != t->nb[1]) {
+ LLAMA_LOG_ERROR("%s: mismatched pending row size (%zu != %zu, layer %d)\n", __func__, t->nb[1], (size_t) size_row_ref, il);
+ return false;
+ }
+
+ if (cell_count) {
+ io.read_tensor(t, head * t->nb[1], cell_count * t->nb[1]);
+ }
+ }
+ }
+ }
+
return true;
}
@@ -1264,7 +1381,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
for (uint32_t il = 0; il < n_layer; ++il) {
if (r_l[il] != nullptr) {
- const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
+ const size_t r_size_row = r_l[il]->nb[1];
ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row);
}
@@ -1274,7 +1391,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
}
if (p_l[il] != nullptr) {
- const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
+ const size_t p_size_row = p_l[il]->nb[1];
ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row);
}
}
@@ -1360,6 +1477,26 @@ ggml_tensor * llama_memory_recurrent_context::get_p_l(int32_t il) const {
return mem->p_l[il];
}
+ggml_tensor * llama_memory_recurrent_context::get_spk_l(int32_t il) const {
+ return mem->spk_l[il];
+}
+
+ggml_tensor * llama_memory_recurrent_context::get_spv_l(int32_t il) const {
+ return mem->spv_l[il];
+}
+
+ggml_tensor * llama_memory_recurrent_context::get_spgb_l(int32_t il) const {
+ return mem->spgb_l[il];
+}
+
+bool llama_memory_recurrent_context::get_rs_replay() const {
+ return mem->rs_replay;
+}
+
+uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const {
+ return is_full ? 0 : mem->cells[i + mem->head].rs_rep;
+}
+
int32_t llama_memory_recurrent_context::s_copy(int i) const {
const uint32_t cell_idx = i + mem->head;
const int32_t src0 = mem->cells[cell_idx].src0;
diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h
index 6442fc1c1..5efe9c3b4 100644
--- a/src/llama-memory-recurrent.h
+++ b/src/llama-memory-recurrent.h
@@ -25,6 +25,7 @@ public:
uint32_t mem_size,
uint32_t n_seq_max,
uint32_t n_rs_seq,
+ bool rs_replay,
const layer_filter_cb & filter);
~llama_memory_recurrent() = default;
@@ -77,6 +78,9 @@ public:
// per-seq rollback index
std::vector<uint32_t> rs_idx;
+ // deferred commit: keep one state plane plus the inputs of the last ubatch, replay the accepted part in the next ubatch
+ bool rs_replay = false;
+
void set_rs_idx(llama_seq_id seq_id, uint32_t idx);
// computed before each graph build
@@ -93,9 +97,13 @@ public:
int32_t tail = -1;
// largest rollback whose snapshot the last ubatch guarantees: a ubatch of n <= n_rs_seq + 1 tokens
- // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_gated_delta_net)
+ // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_ssm_scan)
uint32_t rs_max = 0;
+ // rs_replay: valid tokens in the pending rows, and the pending tokens the current ubatch replays
+ uint32_t rs_pend = 0;
+ uint32_t rs_rep = 0;
+
std::set<llama_seq_id> seq_id;
bool has_seq_id(const llama_seq_id & id) const {
@@ -118,6 +126,10 @@ public:
std::vector<ggml_tensor *> s_l;
// a second conv history that must stay replicated across devices, so it cannot share the r row
std::vector<ggml_tensor *> p_l;
+ // rs_replay pending gdn inputs: k, v, and the gates then the betas
+ std::vector<ggml_tensor *> spk_l;
+ std::vector<ggml_tensor *> spv_l;
+ std::vector<ggml_tensor *> spgb_l;
private:
//const llama_model & model;
@@ -184,9 +196,15 @@ public:
ggml_tensor * get_r_l(int32_t il) const;
ggml_tensor * get_s_l(int32_t il) const;
ggml_tensor * get_p_l(int32_t il) const;
+ ggml_tensor * get_spk_l (int32_t il) const;
+ ggml_tensor * get_spv_l (int32_t il) const;
+ ggml_tensor * get_spgb_l(int32_t il) const;
int32_t s_copy(int i) const;
+ bool get_rs_replay() const;
+ uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i
+
private:
const llama_memory_status status;
diff --git a/src/llama-model.cpp b/src/llama-model.cpp
index fa20378aa..b20459646 100644
--- a/src/llama-model.cpp
+++ b/src/llama-model.cpp
@@ -468,6 +468,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
static const std::regex pattern_r_cache ("cache_r_l\\d*");
static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*");
static const std::regex pattern_s_cache ("cache_s_l\\d*");
+ static const std::regex pattern_spk_cache ("cache_spk_l\\d*");
+ static const std::regex pattern_spv_cache ("cache_spv_l\\d*");
+ static const std::regex pattern_spgb_cache ("cache_spgb_l\\d*");
static const std::regex pattern_ssm_conv1d ("blk\\.\\d*\\.ssm_conv1d.weight");
static const std::regex pattern_ssm_out_weight ("blk\\.\\d*\\.ssm_out.weight");
static const std::regex pattern_kda_conv1d ("blk\\.\\d*\\.ssm_conv1d_(q|k|v)\\.weight");
@@ -577,7 +580,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_2, "attn_output.weight");
}
if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) ||
- std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
+ std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
+ std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
+ std::regex_match(tensor_name, pattern_spgb_cache)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight");
}
}
@@ -642,7 +647,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) {
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight");
}
- if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) {
+ if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) ||
+ std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
+ std::regex_match(tensor_name, pattern_spgb_cache)) {
if (ud->model->arch == LLM_ARCH_LFM2 || ud->model->arch == LLM_ARCH_LFM2MOE || ud->model->arch == LLM_ARCH_LFM3) {
// the LFM2 shortconv block runs fully mirrored, so its conv state must be mirrored too
return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_MIRRORED, "");
@@ -697,10 +704,22 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
auto get_split_segments = [&](int axis, uint32_t il) -> std::vector<std::pair<int64_t, uint32_t>> {
if (is_glm5_next && std::regex_match(tensor_name, pattern_r_cache)) {
// the conv state holds the q, k and v windows one after the other
- const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * hparams.n_embd_head_kda;
- GGML_ASSERT(tensor->ne[axis] == 3*conv_state_size);
+ const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
+ const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * d_inner;
+ if (tensor->ne[axis] != 3*conv_state_size) {
+ // replay: q, k and v histories [d_inner, window + pending], every column is a block of heads
+ GGML_ASSERT(tensor->ne[axis] % (3*d_inner) == 0);
+ return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
+ }
return {{conv_state_size, 3}};
}
+ if (is_glm5_next && (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
+ std::regex_match(tensor_name, pattern_spgb_cache))) {
+ // replay pending inputs, per token: k [S_k, H], v [S_v, H], then the gates [S_v, H] and the betas (in element 0)
+ const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda;
+ GGML_ASSERT(tensor->ne[axis] % d_inner == 0);
+ return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}};
+ }
// TODO: deduplicate condition [TAG_SPLIT_QGATE_QWEN]
// zonos3 has the qwen35 GDN layout, its attention layers have no fused qkv
if (ud->model->arch == LLM_ARCH_QWEN3NEXT || ud->model->arch == LLM_ARCH_QWEN35 || ud->model->arch == LLM_ARCH_QWEN35MOE || ud->model->arch == LLM_ARCH_CLEF || ud->model->arch == LLM_ARCH_CLOVER_MOE ||
@@ -731,6 +750,8 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{key_dim, 2}, {value_dim, 1}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
+ // the replay layouts need the Qwen 3.5 pattern, llama_context keeps Qwen 3 Next on snapshots
+ GGML_ASSERT(tensor->ne[axis] == (2*key_dim + value_dim) * (hparams.ssm_d_conv - 1));
return {{key_dim * (hparams.ssm_d_conv - 1), 2}, {value_dim * (hparams.ssm_d_conv - 1), 1}};
}
} else {
@@ -755,11 +776,26 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {{n_k_heads, head_ratio}};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
+ const int64_t n_conv_ch = 2*key_dim + value_dim;
+ if (tensor->ne[axis] != n_conv_ch * (hparams.ssm_d_conv - 1)) {
+ // replay: [channels, window + pending] per cell, every column is a q, k, v block
+ GGML_ASSERT(tensor->ne[axis] % n_conv_ch == 0);
+ return {{key_dim, uint32_t((2 + head_ratio) * (tensor->ne[axis] / n_conv_ch))}};
+ }
return {{key_dim * (hparams.ssm_d_conv - 1), 2 + head_ratio}};
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {{n_k_heads * head_v_dim * head_v_dim, head_ratio}};
}
+ // replay pending inputs, per token: k [S_k, H_k], v [S_v, H_v], then the gates and betas [H_v]
+ if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
+ GGML_ASSERT(tensor->ne[axis] % key_dim == 0);
+ return {{key_dim, uint32_t(tensor->ne[axis] / key_dim)}};
+ }
+ if (std::regex_match(tensor_name, pattern_spgb_cache)) {
+ GGML_ASSERT(tensor->ne[axis] % n_k_heads == 0);
+ return {{n_k_heads, uint32_t(tensor->ne[axis] / n_k_heads)}};
+ }
}
// the FFN is the same for Qwen 3 Next and Qwen 3.5:
@@ -815,7 +851,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return {granularity_qkv / head_dim};
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
- return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
+ // replay: channels first, each segment is a single conv column
+ const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * head_dim;
+ const bool replay = tensor->ne[0] != 3*conv_state_size;
+ return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
+ }
+ if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) ||
+ std::regex_match(tensor_name, pattern_spgb_cache)) {
+ return std::vector<int64_t>(segments.size(), granularity_qkv);
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return {granularity_qkv * head_dim};
@@ -852,11 +895,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
return std::vector<int64_t>(segments.size(), 2 * (granularity_qkv / head_dim));
}
if (std::regex_match(tensor_name, pattern_r_cache)) {
- return std::vector<int64_t>(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1));
+ // replay: [channels, window + pending], each segment is a single conv column
+ const int64_t n_conv_ch = 2*hparams.ssm_n_group*hparams.ssm_d_state + hparams.ssm_d_inner;
+ const bool replay = tensor->ne[0] != n_conv_ch * (hparams.ssm_d_conv - 1);
+ return std::vector<int64_t>(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1));
}
if (std::regex_match(tensor_name, pattern_s_cache)) {
return std::vector<int64_t>(segments.size(), granularity_qkv * head_dim);
}
+ if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) {
+ return std::vector<int64_t>(segments.size(), granularity_qkv);
+ }
+ if (std::regex_match(tensor_name, pattern_spgb_cache)) {
+ return std::vector<int64_t>(segments.size(), granularity_qkv / head_dim);
+ }
} else {
// regular attention
const uint32_t n_gqa = hparams.n_gqa(il);
@@ -3220,6 +3272,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_rs_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
+ /* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3433,6 +3486,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
std::max((uint32_t) 1, cparams.n_seq_max),
cparams.n_seq_max,
cparams.n_rs_seq,
+ false,
nullptr);
} else if (llm_arch_is_hybrid(arch) && !mtp_on_hybrid_qwen && !mtp_on_hybrid_nemotron) {
// The main difference between hybrid architectures is the
@@ -3527,6 +3581,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
+ /* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
@@ -3547,6 +3602,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
/* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max),
/* n_seq_max */ cparams.n_seq_max,
/* n_rs_seq */ cparams.n_rs_seq,
+ /* rs_replay */ cparams.rs_replay,
/* offload */ cparams.offload_kqv,
/* unified */ cparams.kv_unified,
/* filter_attn */ std::move(filter_attn),
diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp
index ad1f0ee27..20d940ca3 100644
--- a/src/models/bailingmoe3.cpp
+++ b/src/models/bailingmoe3.cpp
@@ -163,22 +163,29 @@ std::unique_ptr<llm_graph_context> llama_model_bailingmoe3::build_arch_graph(con
ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs) {
+ int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t total_state_size = 3 * conv_state_size;
- ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
- (d_conv - 1) * ggml_element_size(conv_state_all),
- total_state_size * ggml_element_size(conv_state_all),
- qkv * conv_state_size * ggml_element_size(conv_state_all));
-
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
- ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
- build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
- ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ ggml_tensor * conv_x = nullptr;
+ if (cparams.rs_replay) {
+ // the row holds the q, k and v conv histories one after the other
+ conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_proj, d_conv - 1, d_inner, il, conv_state_all, qkv);
+ } else {
+ ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
+ (d_conv - 1) * ggml_element_size(conv_state_all),
+ total_state_size * ggml_element_size(conv_state_all),
+ qkv * conv_state_size * ggml_element_size(conv_state_all));
+
+ conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0);
+
+ build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
+ ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ }
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -227,17 +234,17 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
if (hparams.is_recr(il)) {
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
- ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
+ ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
ggml_tensor * q = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv,
- d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * k = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv,
- d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * v = build_causal_conv1d(
inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv,
- d_conv, head_dim, n_head, n_seq_tokens, n_seqs);
+ d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur);
gate = ggml_add(ctx0, gate, layer.ssm_dt_b);
diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp
index 45b2de4bb..f05bd8c0a 100644
--- a/src/models/delta-net-base.cpp
+++ b/src/models/delta-net-base.cpp
@@ -32,8 +32,8 @@ std::pair<ggml_tensor *, ggml_tensor *> llm_build_delta_net_base::build_delta_ne
GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs);
GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs);
- // K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs].
- ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1);
+ // output carries the final state. state s is 4D [S_v, S_v, H_v, n_seqs].
+ ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, nullptr, nullptr, nullptr, nullptr, false);
ggml_tensor * output = ggml_view_4d(ctx0, result,
S_v, H_v, n_tokens, n_seqs,
ggml_row_size(result->type, S_v),
@@ -59,6 +59,10 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
int il) {
const int64_t n_seqs = ubatch.n_seqs;
+ if (cparams.rs_replay) {
+ return build_conv_state_replay(inp, conv_states_all, qkv_mixed, conv_kernel_size - 1, conv_channels, il);
+ }
+
ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs);
cb(conv_states, "conv_states", il);
@@ -76,7 +80,80 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state(
return conv_input;
}
-ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
+// [TAG_RECURRENT_REPLAY]
+// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled
+// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits
+// the result and then runs its own tokens. Must match the rule in llama_memory_recurrent::find_slot.
+// Every ubatch builds the same nodes, with or without pending tokens, so the allocation planned at reserve time
+// stays valid and the scheduler never re-plans.
+static bool rs_replay_keep(const llama_cparams & cparams, int64_t n_seq_tokens) {
+ return n_seq_tokens >= 2 && n_seq_tokens <= (int64_t) cparams.n_rs_seq + 1;
+}
+
+ggml_tensor * llm_build_delta_net_base::build_conv_state_replay(
+ llm_graph_input_rs * inp,
+ ggml_tensor * conv_states_all,
+ ggml_tensor * x,
+ int64_t n_conv,
+ int64_t channels,
+ int il,
+ ggml_tensor * hist_rows,
+ int64_t blk) {
+ const auto * mctx_cur = inp->mctx;
+
+ const auto kv_head = mctx_cur->get_head();
+
+ const int64_t n_hist = n_conv + cparams.n_rs_seq + 1;
+ const int64_t n_seqs = ubatch.n_seqs;
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
+
+ GGML_ASSERT(conv_states_all->ne[0] % (channels*n_hist) == 0);
+ const int64_t n_blk = conv_states_all->ne[0] / (channels*n_hist);
+
+ GGML_ASSERT(blk >= 0 && blk < n_blk);
+ GGML_ASSERT(x->ne[0] == channels && x->ne[1] == n_seq_tokens && x->ne[2] == n_seqs);
+ GGML_ASSERT(n_conv <= inp->n_conv);
+
+ if (hist_rows == nullptr) {
+ hist_rows = build_rs(inp, conv_states_all, conv_states_all->ne[0], n_seqs);
+ }
+ GGML_ASSERT(hist_rows->ne[0] == conv_states_all->ne[0] && hist_rows->ne[1] == n_seqs);
+
+ // channels first: [window | pending], the histories of a row one after the other
+ ggml_tensor * hist = nullptr;
+ if (n_blk == 1) {
+ hist = ggml_reshape_3d(ctx0, hist_rows, channels, n_hist, n_seqs);
+ } else {
+ hist = ggml_reshape_4d(ctx0, hist_rows, channels, n_hist, n_blk, n_seqs);
+ hist = ggml_view_3d(ctx0, hist, channels, n_hist, n_seqs, hist->nb[1], hist->nb[3], blk*hist->nb[2]);
+ }
+ cb(hist, "conv_hist", il);
+
+ ggml_tensor * win_cols = n_conv == inp->rep_cols_r->ne[0] ? inp->rep_cols_r : inp->rep_cols_p;
+ GGML_ASSERT(win_cols && win_cols->ne[0] == n_conv);
+
+ // [channels, n_conv + n_seq_tokens]: the window after the kept pending tokens, then the new tokens
+ // (built channels first, a transposed concat is much slower than a concat and a transpose)
+ ggml_tensor * cols = ggml_concat(ctx0, ggml_get_rows(ctx0, hist, win_cols), x, 1);
+
+ ggml_tensor * conv_input = ggml_cont(ctx0, ggml_transpose(ctx0, cols));
+ cb(conv_input, "conv_input", il);
+
+ // keep: the new tokens stay pending behind the committed window, else commit the last n_conv columns
+ const int64_t n_dst = rs_replay_keep(cparams, n_seq_tokens) ? n_conv + n_seq_tokens : n_conv;
+
+ ggml_tensor * tail = ggml_view_3d(ctx0, cols, channels, n_dst, n_seqs, cols->nb[1], cols->nb[2],
+ (n_conv + n_seq_tokens - n_dst)*cols->nb[1]);
+ // the rows as [channels, n_blk*n_hist, cells], so that the view of the ubatch cells keeps their strides (-sm tensor)
+ ggml_tensor * hist_all = ggml_reshape_3d(ctx0, conv_states_all, channels, n_blk*n_hist, conv_states_all->ne[1]);
+ ggml_tensor * hist_dst = ggml_view_3d(ctx0, hist_all, channels, n_dst, n_seqs, hist_all->nb[1], hist_all->nb[2],
+ kv_head*hist_all->nb[2] + blk*n_hist*hist_all->nb[1]);
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, tail, hist_dst));
+
+ return conv_input;
+}
+
+ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay(
llm_graph_input_rs * inp,
ggml_tensor * ssm_states_all,
ggml_tensor * q,
@@ -86,67 +163,112 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
ggml_tensor * b,
ggml_tensor * s,
int il) {
- const auto * mctx_cur = inp->mctx;
- const auto kv_head = mctx_cur->get_head();
- const uint32_t mem_size = mctx_cur->get_size();
-
- const int64_t S_v = s->ne[0];
- const int64_t H_v = s->ne[2];
- const int64_t n_seqs = s->ne[3];
- const int64_t n_seq_tokens = q->ne[2];
-
- const bool keep = cparams.n_rs_seq > 0;
-
- if (!keep) {
- auto attn_out = build_delta_net(q, k, v, g, b, s);
- ggml_tensor * output = attn_out.first;
- ggml_tensor * new_state = attn_out.second;
- cb(output, "attn_output", il);
- cb(new_state, "new_state", il);
-
- ggml_build_forward_expand(gf,
- ggml_cpy(ctx0, new_state,
- ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
- kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
-
- return output;
- }
+ const auto * mctx_cur = inp->mctx;
+
+ const auto kv_head = mctx_cur->get_head();
- const int64_t D = S_v * S_v * H_v;
- const int64_t K = cparams.n_rs_seq + 1;
+ const int64_t n_pend = cparams.n_rs_seq + 1;
+ const int64_t n_seqs = ubatch.n_seqs;
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
+
+ const int64_t S_k = k->ne[0];
+ const int64_t H_k = k->ne[1];
+ const int64_t S_v = v->ne[0];
+ const int64_t H_v = v->ne[1];
+ const int64_t g0 = g->ne[0];
- // state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output.
- ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K);
- const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs;
- const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs;
+ const size_t row_size = ggml_row_size(ssm_states_all->type, hparams.n_embd_s());
- ggml_tensor * output = ggml_view_4d(ctx0, gdn_out,
- S_v, H_v, n_seq_tokens, n_seqs,
- ggml_row_size(gdn_out->type, S_v),
- ggml_row_size(gdn_out->type, S_v * H_v),
- ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens),
- 0);
+ // the pending inputs of the cells: k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend] (the gates,
+ // then the betas). The views of the ubatch cells keep the strides of these 4D views, so that -sm tensor can split
+ // them by heads
+ ggml_tensor * spk = mctx_cur->get_spk_l(il);
+ ggml_tensor * spv = mctx_cur->get_spv_l(il);
+ ggml_tensor * spgb = mctx_cur->get_spgb_l(il);
+
+ ggml_tensor * ck = ggml_reshape_4d(ctx0, spk, S_k, H_k, n_pend, spk->ne[1]);
+ ggml_tensor * cv = ggml_reshape_4d(ctx0, spv, S_v, H_v, n_pend, spv->ne[1]);
+ ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]);
+
+ const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) {
+ return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs);
+ };
+
+ ggml_tensor * pk = gather(spk, ck);
+ ggml_tensor * pv = gather(spv, cv);
+ ggml_tensor * pgb = gather(spgb, cgb);
+
+ const bool keep = rs_replay_keep(cparams, n_seq_tokens);
+
+ ggml_tensor * state_dst = ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], kv_head*row_size);
+
+ // store the inputs of the new tokens as pending; only used when keep, a longer ubatch stores its first n_pend tokens
+ const auto store_inputs = [&]() {
+ const int64_t n_st = std::min(n_seq_tokens, n_pend);
+
+ const auto store = [&](ggml_tensor * x, ggml_tensor * c, int64_t t0) {
+ ggml_tensor * x_st = ggml_view_4d(ctx0, x, x->ne[0], x->ne[1], n_st, n_seqs, x->nb[1], x->nb[2], x->nb[3], 0);
+ ggml_tensor * dst = ggml_view_4d(ctx0, c, x->ne[0], x->ne[1], n_st, n_seqs, c->nb[1], c->nb[2], c->nb[3],
+ kv_head*c->nb[3] + t0*c->nb[2]);
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, x_st, dst));
+ };
+
+ store(k, ck, 0);
+ store(v, cv, 0);
+ store(g, cgb, 0);
+ store(b, cgb, n_pend);
+ };
+
+ // the gdn op replays the kept pending tokens, then runs the new tokens
+ ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, pk, pv, pgb, inp->rep_n, keep);
+
+ ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_seq_tokens, n_seqs,
+ ggml_row_size(result->type, S_v),
+ ggml_row_size(result->type, S_v*H_v),
+ ggml_row_size(result->type, S_v*H_v*n_seq_tokens), 0);
cb(output, "attn_output", il);
- const size_t row_size = hparams.n_embd_s() * ggml_element_size(ssm_states_all);
+ // keep: the state after the replay, else the final state
+ ggml_tensor * new_state = ggml_view_2d(ctx0, result, hparams.n_embd_s(), n_seqs,
+ ggml_row_size(result->type, hparams.n_embd_s()),
+ ggml_row_size(result->type, S_v*H_v*n_seq_tokens*n_seqs));
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst));
+
+ store_inputs();
+
+ return output;
+}
+
+ggml_tensor * llm_build_delta_net_base::build_recurrent_attn(
+ llm_graph_input_rs * inp,
+ ggml_tensor * ssm_states_all,
+ ggml_tensor * q,
+ ggml_tensor * k,
+ ggml_tensor * v,
+ ggml_tensor * g,
+ ggml_tensor * b,
+ ggml_tensor * s,
+ int il) {
+ if (cparams.rs_replay) {
+ return build_recurrent_attn_replay(inp, ssm_states_all, q, k, v, g, b, s, il);
+ }
- // op writes the last min(n_seq_tokens, K) snapshots; trailing slots are left unwritten
- const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);
+ // a rollback replays the kept tokens, the gdn op does not write state snapshots
+ GGML_ASSERT(cparams.n_rs_seq == 0);
- // write the produced snapshots into the recurrent cache (snapshot slot i -> rollback group i)
- ggml_tensor * src = ggml_view_3d(ctx0, gdn_out,
- D, n_seqs, n_written,
- ggml_row_size(gdn_out->type, D),
- ggml_row_size(gdn_out->type, state_size_per_snap),
- ggml_row_size(gdn_out->type, attn_score_elems));
+ const auto kv_head = inp->mctx->get_head();
+ const int64_t n_seqs = s->ne[3];
- ggml_tensor * dst = ggml_view_3d(ctx0, ssm_states_all,
- D, n_seqs, n_written,
- ssm_states_all->nb[1],
- (size_t) mem_size * row_size,
- (size_t) kv_head * row_size);
+ auto attn_out = build_delta_net(q, k, v, g, b, s);
+ ggml_tensor * output = attn_out.first;
+ ggml_tensor * new_state = attn_out.second;
+ cb(output, "attn_output", il);
+ cb(new_state, "new_state", il);
- ggml_build_forward_expand(gf, ggml_cpy(ctx0, src, dst));
+ ggml_build_forward_expand(gf,
+ ggml_cpy(ctx0, new_state,
+ ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1],
+ kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all))));
return output;
}
diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp
index 51a26df3d..5d3944af2 100644
--- a/src/models/glm5-next.cpp
+++ b/src/models/glm5-next.cpp
@@ -194,22 +194,29 @@ std::unique_ptr<llm_graph_context> llama_model_glm5_next::build_arch_graph(const
ggml_tensor * llama_model_glm5_next::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
+ int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
- ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
- (d_conv - 1) * ggml_element_size(conv_state_all),
- n_embd_r_total * ggml_element_size(conv_state_all),
- qkv * conv_state_size * ggml_element_size(conv_state_all));
-
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
- ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
- build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
- ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ ggml_tensor * conv_x = nullptr;
+ if (cparams.rs_replay) {
+ // the row holds the q, k and v conv histories one after the other
+ conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
+ } else {
+ ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
+ (d_conv - 1) * ggml_element_size(conv_state_all),
+ n_embd_r_total * ggml_element_size(conv_state_all),
+ qkv * conv_state_size * ggml_element_size(conv_state_all));
+
+ conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
+
+ build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
+ ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ }
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -796,11 +803,11 @@ ggml_tensor * llama_model_glm5_next::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
- ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
+ ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
- ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
+ ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp
index 2e91c5243..e0ef7b6cd 100644
--- a/src/models/kimi-k3.cpp
+++ b/src/models/kimi-k3.cpp
@@ -355,22 +355,29 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) :
ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
+ int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
- ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
- (d_conv - 1) * ggml_element_size(conv_state_all),
- n_embd_r_total * ggml_element_size(conv_state_all),
- qkv * conv_state_size * ggml_element_size(conv_state_all));
-
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
- ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
- build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
- ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ ggml_tensor * conv_x = nullptr;
+ if (cparams.rs_replay) {
+ // the row holds the q, k and v conv histories one after the other
+ conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
+ } else {
+ ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
+ (d_conv - 1) * ggml_element_size(conv_state_all),
+ n_embd_r_total * ggml_element_size(conv_state_all),
+ qkv * conv_state_size * ggml_element_size(conv_state_all));
+
+ conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
+
+ build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
+ ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ }
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -388,11 +395,11 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
- ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
+ ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
- ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
+ ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp
index 3f99eca4a..049f667de 100644
--- a/src/models/kimi-k31.cpp
+++ b/src/models/kimi-k31.cpp
@@ -391,22 +391,29 @@ llama_model_kimi_k31::graph::graph(const llm_graph_params & params) :
ggml_tensor * llama_model_kimi_k31::graph::build_kda_conv1d(
llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) {
+ int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) {
const int64_t d_inner = head_dim * n_head_kda;
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t n_embd_r_total = 3 * conv_state_size;
- ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
- (d_conv - 1) * ggml_element_size(conv_state_all),
- n_embd_r_total * ggml_element_size(conv_state_all),
- qkv * conv_state_size * ggml_element_size(conv_state_all));
-
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
- ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
- build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
- ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ ggml_tensor * conv_x = nullptr;
+ if (cparams.rs_replay) {
+ // the row holds the q, k and v conv histories one after the other
+ conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv);
+ } else {
+ ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs,
+ (d_conv - 1) * ggml_element_size(conv_state_all),
+ n_embd_r_total * ggml_element_size(conv_state_all),
+ qkv * conv_state_size * ggml_element_size(conv_state_all));
+
+ conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0);
+
+ build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1,
+ ggml_row_size(conv_states_all->type, qkv * conv_state_size));
+ }
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight);
@@ -424,11 +431,11 @@ ggml_tensor * llama_model_kimi_k31::graph::build_kda_layer(
const auto * mctx_cur = inp_rs->mctx;
ggml_tensor * conv_states_all = mctx_cur->get_r_l(il);
- ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs);
+ ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs);
- ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
- ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs);
+ ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
+ ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il);
cb(Qcur, "kda_q_conv", il);
cb(Kcur, "kda_k_conv", il);
cb(Vcur, "kda_v_conv", il);
diff --git a/src/models/models.h b/src/models/models.h
index b12642fb9..3b4f04c19 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -67,6 +67,31 @@ struct llm_build_delta_net_base : public llm_graph_context {
ggml_tensor * b,
ggml_tensor * s,
int il);
+
+ // rs_replay variants: replay the kept pending tokens, then keep or commit the new ones [TAG_RECURRENT_REPLAY]
+ // x: [channels, n_seq_tokens, n_seqs] new conv inputs; returns [n_conv + n_seq_tokens, channels, n_seqs]
+ // a row of conv_states_all can hold several histories [channels, n_conv + n_pend] one after the other (KDA: q, k, v):
+ // blk picks one, and hist_rows are the rows of the ubatch cells (build_rs) shared by the blocks, nullptr gathers them
+ ggml_tensor * build_conv_state_replay(
+ llm_graph_input_rs * inp,
+ ggml_tensor * conv_states_all,
+ ggml_tensor * x,
+ int64_t n_conv,
+ int64_t channels,
+ int il,
+ ggml_tensor * hist_rows = nullptr,
+ int64_t blk = 0);
+
+ ggml_tensor * build_recurrent_attn_replay(
+ llm_graph_input_rs * inp,
+ ggml_tensor * ssm_states_all,
+ ggml_tensor * q,
+ ggml_tensor * k,
+ ggml_tensor * v,
+ ggml_tensor * g,
+ ggml_tensor * b,
+ ggml_tensor * s,
+ int il);
};
struct llm_build_lfm_base : public llm_graph_context {
@@ -2209,7 +2234,7 @@ struct llama_model_bailingmoe3 : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_causal_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs);
+ int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il);
};
struct graph_mtp : public llm_graph_context {
@@ -3170,7 +3195,7 @@ struct llama_model_kimi_k3 : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs);
+ int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer,
llm_graph_input_attn_k * inp_attn_k,
@@ -3207,7 +3232,7 @@ struct llama_model_kimi_k31 : public llama_model_base {
ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
int64_t d_conv, int64_t head_dim, int64_t n_head_kda,
- int64_t n_seq_tokens, int64_t n_seqs);
+ int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_kda_layer(ggml_tensor * cur, const llama_layer & layer,
llm_graph_input_rs * inp_rs,
@@ -3294,7 +3319,7 @@ struct llama_model_glm5_next : public llama_model_base {
// causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used
ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all,
int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w,
- int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs);
+ int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il);
ggml_tensor * build_kpool_select(ggml_tensor * cur, ggml_tensor * qr, const llama_layer & layer,
const llama_memory_hybrid_idx_context * mctx_hyb, llm_graph_input_kpool * inp_kpool, int il);
diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp
index 106530490..f77e6f509 100644
--- a/src/models/qwen4exp.cpp
+++ b/src/models/qwen4exp.cpp
@@ -1373,6 +1373,10 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at(
int64_t state_cols,
int64_t channels,
int il) {
+ if (cparams.rs_replay) {
+ return build_conv_state_replay(inp, conv_states_all, x, state_cols, channels, il);
+ }
+
const int64_t n_seqs = ubatch.n_seqs;
const int64_t row_total = conv_states_all->ne[0];
diff --git a/tests/llama-context/cases-rs.cpp b/tests/llama-context/cases-rs.cpp
index a26322b30..ba4b71c7e 100644
--- a/tests/llama-context/cases-rs.cpp
+++ b/tests/llama-context/cases-rs.cpp
@@ -357,7 +357,7 @@ struct case_rollback_bound : ctx_test {
const llm_arch arch = llama_arch_from_string(arch_name);
// the DSV4 cache rebuilds snapshot d from the state before the ubatch, so d <= n is exact;
- // the recurrent memory gets snapshots 0..n-1 from ggml_gated_delta_net, only for n <= n_rs_seq + 1
+ // the recurrent memory gets snapshots 0..n-1 from ggml_ssm_scan, only for n <= n_rs_seq + 1
const bool from_ubatch_start = arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41;
const auto make_ctx = [&]() {
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index a0268b638..5947cc1b0 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -5358,7 +5358,6 @@ struct test_gated_delta_net : public test_case {
const int v_repeat;
const bool permuted;
const bool kda;
- const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states
const bool correlated;
const bool padded_v;
const bool padded_q;
@@ -5366,16 +5365,8 @@ struct test_gated_delta_net : public test_case {
// lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence
const float g_min;
- std::string op_desc(ggml_tensor * t) override {
- GGML_UNUSED(t);
- return "GATED_DELTA_NET";
- }
-
- // compare only the view returned by build_graph, not the full op output
- bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; }
-
std::string vars() override {
- std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k);
+ std::string s = VARS_TO_STR12(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, correlated, padded_v, padded_q, permuted_k);
if (g_min != -20.0f) {
s += "," + VAR_TO_STR(g_min);
}
@@ -5384,9 +5375,9 @@ struct test_gated_delta_net : public test_case {
test_gated_delta_net(ggml_type type = GGML_TYPE_F32,
int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1,
- int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f)
+ int v_repeat = 1, bool permuted = false, bool kda = false, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f)
: type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
- v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {}
+ v_repeat(v_repeat), permuted(permuted), kda(kda), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * q;
@@ -5430,11 +5421,7 @@ struct test_gated_delta_net : public test_case {
k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3);
k = ggml_cpy(ctx, k, k_permuted);
}
- ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K);
- if (K > 1 && n_seq_tokens > K) {
- // n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0
- out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0);
- }
+ ggml_tensor * out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false);
return out;
}
@@ -5462,6 +5449,115 @@ struct test_gated_delta_net : public test_case {
}
};
+// GGML_OP_GATED_DELTA_NET with a replay of pending tokens (ggml_gated_delta_net_replay)
+struct test_gated_delta_net_replay : public test_case {
+ const int64_t head_count; // k heads
+ const int64_t head_size;
+ const int64_t n_seq_tokens;
+ const int64_t n_seqs;
+ const int v_repeat;
+ const bool kda;
+ const int64_t n_pend;
+ const bool keep;
+
+ std::string vars() override {
+ return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep);
+ }
+
+ test_gated_delta_net_replay(int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 4, int64_t n_seqs = 1,
+ int v_repeat = 1, bool kda = false, int64_t n_pend = 4, bool keep = true)
+ : head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs),
+ v_repeat(v_repeat), kda(kda), n_pend(n_pend), keep(keep) {}
+
+ ggml_tensor * build_graph(ggml_context * ctx) override {
+ const int64_t S = head_size;
+ const int64_t H_k = head_count;
+ const int64_t H = head_count * v_repeat;
+ const int64_t g0 = kda ? S : 1;
+
+ ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs);
+ ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs);
+ ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_seq_tokens, n_seqs);
+ ggml_tensor * g = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, n_seq_tokens, n_seqs);
+ ggml_tensor * beta = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, H, n_seq_tokens, n_seqs);
+ ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, S, H, n_seqs);
+ // one spare token per seq in pend_k, so that its seq stride is not the dense one
+ ggml_tensor * pk = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_pend + 1, n_seqs);
+ ggml_tensor * pv = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_pend, n_seqs);
+ ggml_tensor * pgb = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, 2*n_pend, n_seqs);
+ ggml_tensor * n_rep = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
+ ggml_set_name(g, "g");
+ ggml_set_name(beta, "beta");
+ ggml_set_name(v, "v");
+ ggml_set_name(pk, "pend_k");
+ ggml_set_name(pv, "pend_v");
+ ggml_set_name(pgb, "pend_gb");
+ ggml_set_name(n_rep, "n_rep");
+
+ q = ggml_l2_norm(ctx, q, 1e-6f);
+ k = ggml_l2_norm(ctx, k, 1e-6f);
+
+ ggml_tensor * pk_tok = ggml_view_4d(ctx, pk, S, H_k, n_pend, n_seqs, pk->nb[1], pk->nb[2], pk->nb[3], 0);
+
+ return ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, pk_tok, pv, pgb, n_rep, keep);
+ }
+
+ void initialize_tensors(ggml_context * ctx) override {
+ std::mt19937 rng(0x6d4e);
+ const int64_t S = head_size;
+ const int64_t H = head_count * v_repeat;
+ const int64_t g0 = kda ? S : 1;
+
+ for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
+ if (ggml_is_view_op(t->op)) { continue; }
+ if (strcmp(t->name, "g") == 0) {
+ init_tensor_uniform(t, -20.0f, -1e-4f);
+ } else if (strcmp(t->name, "beta") == 0) {
+ init_tensor_uniform(t, 0.0f, 1.0f);
+ } else if (strcmp(t->name, "v") == 0) {
+ init_tensor_uniform(t, -0.3f, 5.0f);
+ } else if (strcmp(t->name, "n_rep") == 0) {
+ std::vector<int32_t> data(n_seqs);
+ for (auto & x : data) {
+ x = std::uniform_int_distribution<int32_t>(0, n_pend)(rng);
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(int32_t));
+ } else if (strcmp(t->name, "pend_k") == 0) {
+ // unit rows, as the l2 norm leaves them
+ std::vector<float> data(ggml_nelements(t));
+ std::uniform_real_distribution<float> u(-1.0f, 1.0f);
+ for (int64_t i = 0; i < ggml_nelements(t)/S; ++i) {
+ float n2 = 0.0f;
+ for (int64_t j = 0; j < S; ++j) { data[i*S + j] = u(rng); n2 += data[i*S + j]*data[i*S + j]; }
+ for (int64_t j = 0; j < S; ++j) { data[i*S + j] /= sqrtf(n2); }
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float));
+ } else if (strcmp(t->name, "pend_v") == 0) {
+ init_tensor_uniform(t, -2.0f, 2.0f);
+ } else if (strcmp(t->name, "pend_gb") == 0) {
+ // the gates < 0, then the betas in [0, 1] (element 0 of each gate group)
+ std::vector<float> data(ggml_nelements(t), 0.0f);
+ std::uniform_real_distribution<float> u(0.0f, 1.0f);
+ for (int64_t s = 0; s < n_seqs; ++s) {
+ for (int64_t r = 0; r < 2*n_pend; ++r) {
+ float * row = data.data() + (s*2*n_pend + r)*g0*H;
+ for (int64_t h = 0; h < H; ++h) {
+ if (r < n_pend) {
+ for (int64_t j = 0; j < g0; ++j) { row[h*g0 + j] = -20.0f*u(rng) - 1e-4f; }
+ } else {
+ row[h*g0] = u(rng);
+ }
+ }
+ }
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float));
+ } else {
+ init_tensor_uniform(t);
+ }
+ }
+ }
+};
+
// GGML_OP_GATED_DELTA_NET + GGML_OP_CPY (recurrent cache fusion)
struct test_gated_delta_net_cache_fusion : public test_case {
const ggml_type type;
@@ -5470,25 +5566,22 @@ struct test_gated_delta_net_cache_fusion : public test_case {
const int64_t head_size;
const int64_t n_seq_tokens;
const int64_t n_seqs;
- const int64_t K; // snapshot slot count (>1)
ggml_tensor * cpy_node = nullptr;
std::string vars() override {
- return VARS_TO_STR6(type, head_count, head_size, n_seq_tokens, n_seqs, K);
+ return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
}
test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32,
- int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1,
- int64_t K = 2)
- : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K) {}
+ int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1)
+ : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
const int64_t S_v = head_size;
const int64_t H_v = head_count;
const int64_t H_k = head_count;
const int64_t D = S_v * S_v * H_v;
- const int64_t n_written = std::min<int64_t>(n_seq_tokens, K);
ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs);
@@ -5506,7 +5599,7 @@ struct test_gated_delta_net_cache_fusion : public test_case {
q = ggml_l2_norm(ctx, q, 1e-6f);
k = ggml_l2_norm(ctx, k, 1e-6f);
- ggml_tensor * gdn_out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K);
+ ggml_tensor * gdn_out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false);
ggml_set_name(gdn_out, "gdn_out");
// attn scores view (first part of the gdn output)
@@ -5517,21 +5610,19 @@ struct test_gated_delta_net_cache_fusion : public test_case {
ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), 0);
ggml_set_name(attn, "attn");
- // snapshot tail view [D, n_seqs, n_written]
+ // state tail view [D, n_seqs]
const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs;
- ggml_tensor * src = ggml_view_3d(ctx, gdn_out,
- D, n_seqs, n_written,
+ ggml_tensor * src = ggml_view_2d(ctx, gdn_out,
+ D, n_seqs,
ggml_row_size(gdn_out->type, D),
- ggml_row_size(gdn_out->type, D * n_seqs),
ggml_row_size(gdn_out->type, attn_score_elems));
- // recurrent cache view [D, n_seqs, n_written]
- ggml_tensor * cache = ggml_new_tensor_3d(ctx, type, D, n_seqs, n_written);
+ // recurrent cache view [D, n_seqs]
+ ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, D, n_seqs);
ggml_set_name(cache, "cache");
- ggml_tensor * dst = ggml_view_3d(ctx, cache,
- D, n_seqs, n_written,
- ggml_row_size(cache->type, D),
- ggml_row_size(cache->type, D * n_seqs), 0);
+ ggml_tensor * dst = ggml_view_2d(ctx, cache,
+ D, n_seqs,
+ ggml_row_size(cache->type, D), 0);
ggml_tensor * cpy = ggml_cpy(ctx, src, dst);
ggml_set_name(cpy, "gdn_cache_cpy");
@@ -10004,14 +10095,34 @@ struct test_fill : public test_case {
const ggml_type type;
const std::array<int64_t, 4> ne;
float c;
+ const int64_t offset; // > 0: fill in place a view that starts offset elements into its buffer
- std::string vars() override { return VARS_TO_STR3(type, ne, c); }
+ std::string vars() override {
+ std::string s = VARS_TO_STR3(type, ne, c);
+ if (offset != 0) {
+ s += "," + VAR_TO_STR(offset);
+ }
+ return s;
+ }
test_fill(float c, ggml_type type = GGML_TYPE_F32,
- std::array<int64_t, 4> ne = { 10, 10, 4, 3 })
- : type(type), ne(ne), c(c) {}
+ std::array<int64_t, 4> ne = { 10, 10, 4, 3 }, int64_t offset = 0)
+ : type(type), ne(ne), c(c), offset(offset) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
+ if (offset != 0) {
+ ggml_tensor * a = ggml_new_tensor_1d(ctx, type, offset + ne[0]*ne[1]*ne[2]*ne[3]);
+ ggml_set_name(a, "a");
+
+ ggml_tensor * v = ggml_view_4d(ctx, a, ne[0], ne[1], ne[2], ne[3],
+ ne[0]*ggml_type_size(type), ne[0]*ne[1]*ggml_type_size(type), ne[0]*ne[1]*ne[2]*ggml_type_size(type),
+ offset*ggml_type_size(type));
+
+ ggml_tensor * out = ggml_fill_inplace(ctx, v, c);
+ ggml_set_name(out, "out");
+ return out;
+ }
+
ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
ggml_set_param(a);
ggml_set_name(a, "a");
@@ -13469,6 +13580,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 207, 11, 3 }));
test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 }));
test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 }));
+ test_cases.emplace_back(new test_fill(0.0f, GGML_TYPE_F32, { 303, 7, 1, 1 }, 1));
+ test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F32, { 96, 4, 1, 1 }, 37));
+ test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 7, 1, 1 }, 3));
test_cases.emplace_back(new test_sleep(0));
test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 }));
@@ -14006,6 +14120,19 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_moe_reduce(2048, 16, 32, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1));
+ for (bool keep : { true, false }) {
+ test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 4, 1, 1, false, 4, keep));
+ test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 2, 3, 3, false, 4, keep));
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 4, 1, 3, false, 4, keep));
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 8, 2, 3, false, 8, keep));
+ test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 1, 2, 2, false, 3, keep));
+ test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 3, 2, 1, true, 4, keep));
+ }
+ // prefill sized: the replay runs before the chunked kernels (CUDA from 64 tokens, HIP from 2048)
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 65, 1, 1, false, 4, false));
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 257, 1, 3, false, 4, false));
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 513, 2, 2, false, 8, false));
+ test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 2048, 1, 3, false, 4, false));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, false, true));
@@ -14041,9 +14168,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, true, true));
// MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold.
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1));
@@ -14064,53 +14190,43 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, false, true));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2));
// Correlated keys, high beta, and weak decay stress the chunked triangular solve.
for (int64_t n_tokens : {64, 65, 257}) {
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, true));
}
// Odd V strides require element loads instead of aligned matrix loads.
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, false, true));
// Q and K can have different strides in both scalar and chunked paths.
for (int64_t n_tokens : {4, 65}) {
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, true));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, false, true));
}
- // mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots
+ // mild decay keeps the state alive across the sequence; qwen35 prefill layout
for (int64_t n : { 5, 300, 2048 }) {
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, false, false, false, false, /*g_min=*/-0.05f));
}
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, false, false, false, false, /*g_min=*/-0.05f));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f));
// a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA
for (int64_t s : { 16, 32, 64, 128 }) {
for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) {
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f));
+ test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, false, false, false, false, /*g_min=*/-0.05f));
}
}
- // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first
- // (slot 0 = final state, slot s = state s tokens back).
- // exact-match cases (K == n_seq_tokens):
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 16, 2, 1, 1, false, false, /*K=*/2));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 32, 4, 1, 1, false, false, /*K=*/4));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, false, /*K=*/4));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 128, 4, 1, 1, false, false, /*K=*/4));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, true, /*K=*/4));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 32, 4, 2, 2, false, true, /*K=*/4));
-
- // gdn + cache cpy fusion (K > 1)
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1, 2));
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2));
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4));
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4));
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4));
- test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4));
+ // gdn + cache cpy fusion
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1));
+ test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1));
#if 0
// these tests are disabled to save execution time, sbut they can be handy for debugging
@@ -14795,7 +14911,6 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1));
test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1));
- test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5
// lightning_indexer
for (int kv : { 256, 4096, 65536 }) {