// TODO: this is temporary until we support passing reuse layer filters [KV_REUSE] auto n_layer_cache = hparams.n_layer; if (model.arch == LLM_ARCH_GEMMA3N) {
n_layer_cache = 20;
} if (model.arch == LLM_ARCH_GLM4_MOE) { // GLM-4.5: Only process up to last layer, skip final NextN layer
n_layer_cache = hparams.n_layer - hparams.nextn_predict_layers;
}
// create a context for each buffer type
std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map; auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * { auto it = ctx_map.find(buft); if (it == ctx_map.end()) {
ggml_init_params params = { /*.mem_size =*/ size_t(2u*(1 + n_stream)*n_layer_cache*ggml_tensor_overhead()), /*.mem_buffer =*/ NULL, /*.no_alloc =*/ true,
};
v_heads.resize(n_stream); for (uint32_t s = 0; s < n_stream; ++s) {
v_heads[s] = 0;
}
v_cells.resize(n_stream); for (uint32_t s = 0; s < n_stream; ++s) {
v_cells[s].resize(kv_size);
}
// by default, all sequence ids are mapped to the 0th stream
seq_to_stream.resize(LLAMA_MAX_SEQ, 0);
if (n_stream > 1) {
seq_to_stream.resize(n_stream, 0); for (uint32_t s = 0; s < n_stream; ++s) {
seq_to_stream[s] = s;
}
}
// [TAG_V_CACHE_VARIABLE] if (v_trans && hparams.is_n_embd_v_gqa_variable()) {
LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n",
__func__, hparams.n_embd_v_gqa_max());
}
for (uint32_t il = 0; il < n_layer_cache; il++) { if (filter && !filter(il)) {
LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il); continue;
}
for (uint32_t s = 0; s < n_stream; ++s) {
k_stream.push_back(ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2]));
v_stream.push_back(ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2]));
}
map_layer_ids[il] = layers.size();
layers.push_back({ il, k, v, k_stream, v_stream, });
}
// TODO: this is temporary until we support passing reuse layer filters [KV_REUSE] if (model.arch == LLM_ARCH_GEMMA3N) {
LLAMA_LOG_DEBUG("%s: GEMMA3N: reuse layers [%d, %d]\n", __func__, n_layer_cache, hparams.n_layer - 1);
for (uint32_t il = n_layer_cache; il < hparams.n_layer; il++) { if (filter && !filter(il)) {
LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, il); continue;
}
if (p1 < 0) {
p1 = std::numeric_limits<llama_pos>::max();
}
if (seq_id >= 0) { auto & cells = v_cells[seq_to_stream[seq_id]]; auto & head = v_heads[seq_to_stream[seq_id]];
uint32_t new_head = cells.size();
for (uint32_t i = 0; i < cells.size(); ++i) { if (!cells.pos_in(i, p0, p1)) { continue;
}
if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) { if (new_head == cells.size()) {
new_head = i;
}
}
}
// If we freed up a slot, set head to it so searching can start there. if (new_head != cells.size() && new_head < head) {
head = new_head;
}
} else { // match any sequence for (uint32_t s = 0; s < n_stream; ++s) { auto & cells = v_cells[s]; auto & head = v_heads[s];
uint32_t new_head = cells.size();
for (uint32_t i = 0; i < cells.size(); ++i) { if (!cells.pos_in(i, p0, p1)) { continue;
}
cells.rm(i);
if (new_head == cells.size()) {
new_head = i;
}
}
// If we freed up a slot, set head to it so searching can start there. if (new_head != cells.size() && new_head < head) {
head = new_head;
}
}
}
auto & cells = v_cells[seq_to_stream[seq_id]]; auto & head = v_heads[seq_to_stream[seq_id]];
if (shift == 0) { return;
}
uint32_t new_head = cells.size();
if (p0 < 0) {
p0 = 0;
}
if (p1 < 0) {
p1 = std::numeric_limits<llama_pos>::max();
}
// If there is no range then return early to avoid looping over all cells. if (p0 == p1) { return;
}
for (uint32_t i = 0; i < cells.size(); ++i) { if (!cells.pos_in(i, p0, p1)) { continue;
}
if (cells.seq_has(i, seq_id)) { if (cells.pos_add(i, shift)) { if (new_head == cells.size()) {
new_head = i;
}
}
}
}
// If we freed up a slot, set head to it so searching can start there. // Otherwise we just start the next search from the beginning.
head = new_head != cells.size() ? new_head : 0;
}
// see if we need to defrag if (n_stream == 1) { // note : for now do not consider defrag for n_stream > 1 constauto & cells = v_cells[seq_to_stream[0]];
// - do not defrag small contexts (i.e. < 2048 tokens) // - count the padding towards the number of used tokens constfloat fragmentation = n_kv >= 2048 ? std::max(0.0f, 1.0f - (float(cells.get_used() + n_pad)/n_kv)) : 0.0f;
struct state_t {
slot_info sinfo; // slot info for the ubatch
std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch
std::vector<llama_kv_cells_unified> v_cells; // copy of the old cells, before placing the ubatch
};
// remember the old state of the cells so we can restore it in the end
std::vector<state_t> states;
bool success = true;
for (constauto & ubatch : ubatches) { // non-continuous slots require support for ggml_set_rows() constbool cont = supports_set_rows ? false : true;
// only find a suitable slot for the ubatch. don't modify the cells yet constauto sinfo_new = find_slot(ubatch, cont); if (sinfo_new.empty()) {
success = false; break;
}
// remeber the position that we found
res.push_back(sinfo_new);
// store the old state of the cells in the recovery stack
{
state_t state = { sinfo_new, v_heads, {} };
for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) { auto & cells = v_cells[sinfo_new.strm[s]];
// now emplace the ubatch
apply_ubatch(sinfo_new, ubatch);
}
GGML_ASSERT(!states.empty() || !success);
// iterate backwards and restore the cells to their original state for (auto it = states.rbegin(); it != states.rend(); ++it) { constauto & sinfo = it->sinfo;
for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { auto & cells = v_cells[sinfo.strm[s]]; auto & head = v_heads[sinfo.strm[s]];
cells.set(sinfo.idxs[s], it->v_cells[s]);
head = it->v_heads_old[s];
}
}
// if we have enough unused cells before the current head -> // better to start searching from the beginning of the cache, hoping to fill it if (head_cur > cells.get_used() + 2*n_tokens) {
head_cur = 0;
}
// for continuous slots, we test that all tokens in the ubatch fit, starting from the current head // for non-continuous slots, we test the tokens one by one const uint32_t n_test = cont ? n_tokens : 1;
while (true) { if (head_cur + n_test > cells.size()) {
n_tested += cells.size() - head_cur;
head_cur = 0; continue;
}
for (uint32_t i = 0; i < n_test; i++) { constauto idx = head_cur;
// can we use this cell? either: // - the cell is empty // - the cell is occupied only by one sequence: // - (disabled) mask causally, if the sequence is the same as the one we are inserting // - mask SWA, using current max pos for that sequence in the cache // always insert in the cell with minimum pos bool can_use = cells.is_empty(idx);
if (can_use) {
res.idxs[s].push_back(idx);
} else { if (cont) { break;
}
}
}
if (res.idxs[s].size() == n_tokens) { break;
}
if (cont) {
res.idxs[s].clear();
}
if (n_tested >= cells.size()) { //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens); return { };
}
}
// we didn't find a suitable slot - return empty result if (res.idxs[s].size() < n_tokens) { return { };
}
}
assert(res.s1 >= res.s0);
return res;
}
void llama_kv_cache_unified::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) { // keep track of the max sequence position that we would overwrite with this ubatch // for non-SWA cache, this would be always empty
llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ]; for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
seq_pos_max_rm[s] = -1;
}
for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) {
cells.seq_add(idx, ubatch.seq_id[i][s]);
}
}
}
// note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence // will be present in the cache. so we have to purge any position which is less than those we would overwrite // ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092 for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) { if (seq_pos_max_rm[s] == -1) { continue;
}
GGML_ASSERT(s < seq_to_stream.size());
auto & cells = v_cells[seq_to_stream[s]];
if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
__func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
int64_t * data = (int64_t *) dst->data;
if (!v_trans) { for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { const int64_t offs = sinfo.strm[s]*get_size();
for (uint32_t i = 0; i < sinfo.size(); ++i) {
data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
}
}
} else { // note: the V cache is transposed when not using flash attention const int64_t kv_size = get_size();
std::fill(data, data + ggml_nelements(dst), -INFINITY);
// Use only the previous KV cells of the correct sequence for each token of the ubatch. // It's assumed that if a token in the batch has multiple sequences, they are equivalent. // Example with a cache of 10 tokens, 2 tokens populated in cache and 3 tokens in batch: // Causal mask: // xxx------- // xxxx------ // xxxxx----- // Non-causal mask: // xxxxx----- // xxxxx----- // xxxxx----- // To visualize the mask, see https://github.com/ggml-org/llama.cpp/pull/12615 // TODO: optimize this section for (uint32_t h = 0; h < 1; ++h) { for (uint32_t s = 0; s < n_stream; ++s) { for (uint32_t ii = 0; ii < n_tps; ++ii) { const uint32_t i = s*n_tps + ii;
GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
int32_t * data = (int32_t *) dst->data;
const int32_t n_kv = dst->ne[0];
for (int h = 0; h < 1; ++h) { for (int i = 0; i < n_tokens; ++i) { for (int j = 0; j < n_kv; ++j) { // the position when the cells is empty is irrelevant - it will be masked out later in the attention const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j);
constauto & n_rot = hparams.n_rot; constauto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE // @ngxson : this is a workaround // for M-RoPE, we want to rotate the whole vector when doing KV shift // a normal RoPE should work, we just need to use the correct ordering // ref: https://github.com/ggml-org/llama.cpp/pull/13870
? LLAMA_ROPE_TYPE_NEOX
: hparams.rope_type;
// See llm_build_deepseek2() for why attn_factor has to be scaled for YaRN RoPE to work correctly. // See https://github.com/ggerganov/llama.cpp/discussions/7416 for detailed explanation. constfloat yarn_attn_factor = model.arch == LLM_ARCH_DEEPSEEK2
? 1.0f / (1.0f + 0.1f * logf(1.0f / freq_scale))
: cparams.yarn_attn_factor;
ggml_tensor * tmp;
if (ggml_is_quantized(cur->type)) { // dequantize to f32 -> RoPE -> quantize back
tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
GGML_ASSERT(n_stream == 1 && "n_stream > 1 does not support defrag");
constauto & cells = v_cells[0];
constauto & ids = dinfo.ids;
constauto & cparams = lctx->get_cparams();
#if0 // CPU defrag // // TODO: optimizations are possible: // - multiple threads // - avoid copying to the host memory when already there // // likely not worth the effort, as we have ggml_graph based defrag //
if (cparams.flash_attn) { // NOTE: the V cache is not transposed when using flash attention
view_v_src = ggml_view_2d(ctx, layer.v,
n_embd_v_gqa, nm,
ggml_row_size(layer.v->type, n_embd_v_gqa),
ggml_row_size(layer.v->type, n_embd_v_gqa*i));
// each move requires 6*n_layer tensors (see graph_build_kv_self_defrag) // - source view, destination view, copy operation // - x2 for keys and values //const uint32_t max_moves = max_nodes()/(6*n_layer); // TODO: tmp fix https://github.com/ggerganov/llama.cpp/issues/6685#issuecomment-2057579516 const uint32_t max_moves = (n_max_nodes - 2*n_layer)/(6*n_layer);
// determine which KV cells to move where
defrag_info res; auto & ids = res.ids;
ids.resize(n_kv, n_kv);
for (uint32_t i0 = 0; i0 < n_used; ++i0) { if (!cells.is_empty(i0)) {
ids[i0] = i0;
continue;
}
// found a hole - fill it with data from the end of the cache
uint32_t nh = 1;
// determine the size of the hole while (i0 + nh < n_used && cells.is_empty(i0 + nh)) {
nh++;
}
uint32_t nf = 0;
uint32_t is = n_kv - 1;
// starting from the end, find nh non-empty cells for (; is > i0; --is) { if (cells.is_empty(is) || ids[is] != n_kv) { continue;
}
// non-empty cell which is not yet moved
nf++;
if (nf == nh) { break;
}
}
// this can only happen if `n_used` is not accurate, which would be a bug
GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
nf = 0;
uint32_t i1 = is;
// are we moving a continuous block of memory? bool cont = false;
// should we stop searching for the next move? bool stop = false;
// go back and move the nf cells to the hole for (; i1 < n_kv; ++i1) { if (cells.is_empty(i1) || ids[i1] != n_kv) { if (n_moves == max_moves) {
stop = true; break;
}
cont = false; continue;
}
// this cell goes to (i0 + nf)
ids[i1] = i0 + nf;
if (!cont) {
n_moves++;
cont = true;
}
nf++;
if (nf == nh) { break;
}
}
if (stop || n_moves == max_moves) { break;
}
//LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
for (uint32_t s = 0; s < n_stream; ++s) {
cell_ranges_t cr { s, {} };
uint32_t cell_count = 0;
constauto & cells = v_cells[s];
// Count the number of cells with the specified seq_id // Find all the ranges of cells with this seq id (or all, when -1)
uint32_t cell_range_begin = cells.size();
for (uint32_t i = 0; i < cells.size(); ++i) { if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) {
++cell_count; if (cell_range_begin == cells.size()) {
cell_range_begin = i;
}
} else { if (cell_range_begin != cells.size()) {
cr.data.emplace_back(cell_range_begin, i);
cell_range_begin = cells.size();
}
}
}
if (cell_range_begin != cells.size()) {
cr.data.emplace_back(cell_range_begin, cells.size());
}
// DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
uint32_t cell_count_check = 0; for (constauto & range : cr.data) {
cell_count_check += range.second - range.first;
}
GGML_ASSERT(cell_count == cell_count_check);
// Iterate and write all the keys first, each row is a cell // Get whole range at a time for (constauto & layer : layers) { const uint32_t il = layer.il;
// Read each range of cells of k_size length each into tmp_buf and write out for (constauto & range : cr.data) { const size_t range_size = range.second - range.first; const size_t buf_size = range_size * k_size_row;
io.write_tensor(k, range.first * k_size_row, buf_size);
}
}
if (!v_trans) { for (constauto & layer : layers) { const uint32_t il = layer.il;
// Write value type const int32_t v_type_i = (int32_t) v->type;
io.write(&v_type_i, sizeof(v_type_i));
// Write row size of value const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
io.write(&v_size_row, sizeof(v_size_row));
// Read each range of cells of v_size length each into tmp_buf and write out for (constauto & range : cr.data) { const size_t range_size = range.second - range.first; const size_t buf_size = range_size * v_size_row;
io.write_tensor(v, range.first * v_size_row, buf_size);
}
}
} else { // When v is transposed, we also need the element size and get the element ranges from each row const uint32_t kv_size = cells.size();
for (constauto & layer : layers) { const uint32_t il = layer.il;
// For each row, we get the element values of each cell for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { // Read each range of cells of v_size_el length each into tmp_buf and write out for (constauto & range : cr.data) { const size_t range_size = range.second - range.first; const size_t src_offset = (range.first + j * kv_size) * v_size_el; const size_t buf_size = range_size * v_size_el;
io.write_tensor(v, src_offset, buf_size);
}
}
}
}
}
bool llama_kv_cache_unified::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, llama_seq_id dest_seq_id) { auto & cells = v_cells[strm]; auto & head = v_heads[strm];
if (dest_seq_id != -1) { // single sequence
seq_rm(dest_seq_id, -1, -1);
constauto sinfo = find_slot(ubatch, true); if (sinfo.empty()) {
LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__); returnfalse;
}
apply_ubatch(sinfo, ubatch);
constauto head_cur = sinfo.head();
// keep the head at the old position because we will read the KV data into it in state_read_data()
head = head_cur;
if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max); returnfalse;
}
cells.seq_add(i, seq_id);
}
}
head = 0;
}
return true;
}
bool llama_kv_cache_unified::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count) { auto & cells = v_cells[strm]; auto & head = v_heads[strm];
if (n_layer != layers.size()) {
LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size()); returnfalse;
}
if (cell_count > cells.size()) {
LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size()); returnfalse;
}
if (this->v_trans != (bool) v_trans) {
LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__); returnfalse;
}
// For each layer, read the keys for each cell, one row is one cell, read as one contiguous block for (constauto & layer : layers) { const uint32_t il = layer.il;
if (cell_count) { // Read and set the keys for the whole cell range
ggml_backend_tensor_set(k, io.read(cell_count * k_size_row), head * k_size_row, cell_count * k_size_row);
}
}
if (!this->v_trans) { for (constauto & layer : layers) { const uint32_t il = layer.il;
// Read type of value
int32_t v_type_i_ref;
io.read_to(&v_type_i_ref, sizeof(v_type_i_ref)); const int32_t v_type_i = (int32_t) v->type; if (v_type_i != v_type_i_ref) {
LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il); returnfalse;
}
// Read row size of value
uint64_t v_size_row_ref;
io.read_to(&v_size_row_ref, sizeof(v_size_row_ref)); const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa); if (v_size_row != v_size_row_ref) {
LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il); returnfalse;
}
if (cell_count) { // Read and set the values for the whole cell range
ggml_backend_tensor_set(v, io.read(cell_count * v_size_row), head * v_size_row, cell_count * v_size_row);
}
}
} else { // For each layer, read the values for each cell (transposed) for (constauto & layer : layers) { const uint32_t il = layer.il;
// create a dummy slot info - the actual data is irrelevant. we just need to build the graph
sinfos.resize(1);
sinfos[0].s0 = 0;
sinfos[0].s1 = n_stream - 1;
sinfos[0].idxs.resize(n_stream); for (uint32_t s = 0; s < n_stream; ++s) {
sinfos[0].strm.push_back(s);
sinfos[0].idxs[s].resize(1, 0);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.