Skip to content

Commit 571d0d5

Browse files
model: rotate injected K/V cache for DFlash (ggml-org#25823)
* dflash: rotate injected K/V cache when using K/V quantization * Update src/models/dflash.cpp Co-authored-by: Georgi Gerganov <ggerganov@gmail.com> * clearer format * remove trailing whitespace --------- Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
1 parent 4937ca8 commit 571d0d5

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

src/models/dflash.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include "models.h"
22

3+
#include "llama-impl.h"
34
#include "llama-kv-cache.h"
45
#include "llama-kv-cache-iswa.h"
56

@@ -164,9 +165,25 @@ llama_model_dflash::graph<false>::graph(const llama_model & model, const llm_gra
164165
const auto * kv = is_swa ? inp_attn_iswa->mctx->get_swa() : inp_attn_iswa->mctx->get_base();
165166
ggml_tensor * k_idxs = is_swa ? inp_attn_iswa->get_k_idxs_swa() : inp_attn_iswa->get_k_idxs();
166167
ggml_tensor * v_idxs = is_swa ? inp_attn_iswa->get_v_idxs_swa() : inp_attn_iswa->get_v_idxs();
168+
// rotate K/V into the cache's rotated space
169+
ggml_tensor * k_rot = is_swa ? inp_attn_iswa->self_k_rot_swa : inp_attn_iswa->self_k_rot;
170+
ggml_tensor * v_rot = is_swa ? inp_attn_iswa->self_v_rot_swa : inp_attn_iswa->self_v_rot;
171+
if (k_rot) {
172+
Kcur = llama_mul_mat_hadamard(ctx0, Kcur, k_rot);
173+
}
174+
if (v_rot) {
175+
Vcur = llama_mul_mat_hadamard(ctx0, Vcur, v_rot);
176+
}
167177
ggml_build_forward_expand(gf, kv->cpy_k(ctx0, Kcur, k_idxs, il));
168178
ggml_build_forward_expand(gf, kv->cpy_v(ctx0, Vcur, v_idxs, il));
169179
} else {
180+
// rotate K/V into the cache's rotated space
181+
if (inp_attn->self_k_rot) {
182+
Kcur = llama_mul_mat_hadamard(ctx0, Kcur, inp_attn->self_k_rot);
183+
}
184+
if (inp_attn->self_v_rot) {
185+
Vcur = llama_mul_mat_hadamard(ctx0, Vcur, inp_attn->self_v_rot);
186+
}
170187
ggml_build_forward_expand(gf, inp_attn->mctx->cpy_k(ctx0, Kcur, inp_attn->get_k_idxs(), il));
171188
ggml_build_forward_expand(gf, inp_attn->mctx->cpy_v(ctx0, Vcur, inp_attn->get_v_idxs(), il));
172189
}

0 commit comments

Comments
 (0)