Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 44 additions & 41 deletions src/llama-kv-cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,10 @@ void llama_kv_cache::clear(bool data) {
}

bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
return seq_rm(seq_id, p0, p1, nullptr);
}

bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1, placement_journal * journal) {
const llama_kv_settle_on_return settle{ v_cells };
// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
if (other) {
Expand All @@ -413,7 +417,22 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
if (seq_id >= 0) {
auto & cells = v_cells[seq_to_stream[seq_id]];
auto & head = v_heads[seq_to_stream[seq_id]];
cells.note_cut(p0); // a checkpoint at or past p0 no longer holds what it counted on
if (!journal) {
cells.note_cut(p0);
}

if (journal) {
std::vector<uint32_t> indices;
for (uint32_t i = 0; i < cells.size(); ++i) {
if (cells.pos_in(i, p0, p1) && cells.seq_has(i, seq_id)) {
indices.push_back(i);
}
}
if (!indices.empty()) {
auto saved = cells.cp(indices);
journal->push_back({seq_to_stream[seq_id], std::move(indices), std::move(saved)});
}
}

uint32_t new_head = cells.size();

Expand All @@ -440,7 +459,9 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
auto & head = v_heads[s];

uint32_t new_head = cells.size();
cells.note_cut(p0); // every sequence in this stream loses what a checkpoint past p0 counted on
if (!journal) {
cells.note_cut(p0);
}

for (uint32_t i = 0; i < cells.size(); ++i) {
if (!cells.pos_in(i, p0, p1)) {
Expand Down Expand Up @@ -778,16 +799,8 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector<llama_
const llama_kv_settle_on_return settle{ v_cells };
llama_kv_cache::slot_info_vec_t res;

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> 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;
const auto heads_before = v_heads;
placement_journal journal;

bool success = true;

Expand All @@ -802,37 +815,13 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector<llama_
// remember 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]];

state.v_cells.push_back(cells.cp(sinfo_new.idxs[s]));
}

states.push_back(std::move(state));
}

// now emplace the ubatch
apply_ubatch(sinfo_new, ubatch);
apply_ubatch(sinfo_new, ubatch, &journal);
}

GGML_ASSERT(!states.empty() || !success);

// iterate backwards and restore the cells to their original state
for (auto it = states.rbegin(); it != states.rend(); ++it) {
const auto & 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];
}
for (auto entry = journal.rbegin(); entry != journal.rend(); ++entry) {
v_cells[entry->stream].set(entry->indices, entry->cells);
}
v_heads = heads_before;

if (!success) {
return {};
Expand Down Expand Up @@ -1122,6 +1111,10 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch,
}

void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) {
apply_ubatch(sinfo, ubatch, nullptr);
}

void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch, placement_journal * journal) {
const llama_kv_settle_on_return settle{ v_cells };
// TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
if (other) {
Expand All @@ -1138,6 +1131,12 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch &
assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size());

for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
if (journal) {
const uint32_t stream = sinfo.strm[s];
const auto & indices = sinfo.idxs[s];
journal->push_back({stream, indices, v_cells[stream].cp(indices)});
}
llama_pos first_overwritten = std::numeric_limits<llama_pos>::max();
for (uint32_t ii = 0; ii < sinfo.size(); ++ii) {
const uint32_t i = s*sinfo.size() + ii;

Expand All @@ -1153,6 +1152,7 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch &

seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);

first_overwritten = std::min(first_overwritten, pos);
cells.rm(idx);
}

Expand All @@ -1170,6 +1170,9 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch &
cells.seq_add(idx, ubatch.seq_id[i][s]);
}
}
if (!journal && first_overwritten != std::numeric_limits<llama_pos>::max()) {
v_cells[sinfo.strm[s]].note_cut(first_overwritten);
}
}

// note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
Expand All @@ -1188,7 +1191,7 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch &
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);

seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1, journal);
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/llama-kv-cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,17 @@ class llama_kv_cache : public llama_memory_i {
void set_input_v_rot(ggml_tensor * dst) const;

private:
// Metadata changed by a speculative placement. Entries unwind in reverse order
// because a later purge can touch a cell already saved by an earlier placement.
struct cell_snapshot {
uint32_t stream;
std::vector<uint32_t> indices;
llama_kv_cells cells;
};
using placement_journal = std::vector<cell_snapshot>;
void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch, placement_journal * journal);
bool seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1, placement_journal * journal);

const llama_model & model;
const llama_hparams & hparams;

Expand Down
47 changes: 47 additions & 0 deletions tests/test-persona-blocks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
#include "llama.h"

#include "../src/llama-context.h"
#include "../src/llama-batch.h"
#include "../src/llama-kv-cache.h"
#include "../src/llama-model.h"

#include <algorithm>
#include <atomic>
Expand Down Expand Up @@ -125,6 +128,47 @@ struct fixture {
llama_pos pos_max(llama_seq_id seq) const { return llama_memory_seq_pos_max(llama_get_memory(ctx), seq); }
};

// Exercise placement and receipt ownership directly. Four metadata cells suffice to wrap
// the sliding window, independent of the architecture and weights of the fixture model.
static void test_checkpoint_after_swa_overwrite(const llama_model & model, bool fragmented) {
llama_kv_cache cache(model, model.hparams, GGML_TYPE_F16, GGML_TYPE_F16, false, false, true,
4, 1, 1, 2, LLAMA_SWA_TYPE_STANDARD, nullptr, [](int) { return false; }, nullptr, nullptr);
llama_seq_id seq = 0;
llama_seq_id * ids = &seq;
llama_pos pos = 0;
int32_t count = 1;
llama_ubatch batch{};
batch.n_seq_tokens = batch.n_seqs = batch.n_tokens = batch.n_seqs_unq = batch.n_pos = batch.b_equal_seqs = 1;
batch.pos = &pos;
batch.n_seq_id = &count;
batch.seq_id = &ids;
batch.seq_id_unq = &seq;
auto plan = [&] {
auto slots = cache.prepare({batch});
require(slots.size() == 1, "one SWA slot planned");
return slots.front();
};
auto take = [&](llama_persona_checkpoint_blocks & mark) {
require_move(cache.persona_check_checkpoint(seq, mark), llama_persona_move::done, "prepare SWA checkpoint");
cache.persona_commit_checkpoint(seq, mark);
mark.taken = true;
};
for (llama_pos i = 0; i < 4; ++i) {
pos = fragmented && i < 2 ? 1 - i : i;
cache.apply_ubatch(plan(), batch);
}
pos = 4;
llama_persona_checkpoint_blocks before{}, after{};
take(before);
const auto slot = plan();
require(cache.seq_pos_min(seq) == 0, "planning restores every purged prefix cell");
require_move(cache.persona_check_rewind(seq, before), llama_persona_move::done, "planning preserves old KV");
cache.apply_ubatch(slot, batch);
take(after);
require_move(cache.persona_check_rewind(seq, before), llama_persona_move::checkpoint_stale, "overwritten KV revoked");
require_move(cache.persona_check_rewind(seq, after), llama_persona_move::done, "new sliding window retained");
}

int main(int argc, char ** argv) {
common_params params;
params.kv_unified = false; // one attention stream per sequence
Expand Down Expand Up @@ -198,6 +242,9 @@ int main(int argc, char ** argv) {
return 0;
}

test_checkpoint_after_swa_overwrite(*llama_get_model(f.ctx), false);
test_checkpoint_after_swa_overwrite(*llama_get_model(f.ctx), true);

const auto ref_a0 = f.reference(0, 1); // persona a on sequence 0
const auto ref_b1 = f.reference(1, 2); // persona b on sequence 1

Expand Down