Skip to content

Commit 08618ff

Browse files
authored
llama : fix K/V and recurrent state cleanup after failed restores (ggml-org#27530)
* llama : add discard for deferred state writes * llama : add tensor zeroing helper for backends without tensor memset * llama : clear K/V data after failed sequence restore * llama : clear recurrent state data after failed sequence restore * llama : simplify discard and restore cleanup * llama : report error when abnormal cell count is found in state_read_meta * llama : clear attention state on hybrid restore failure * tests : cover failed state restore cleanup * llama : clear MLA state on dsa restore failure * tests : update test for rebased test suite * llama : clarify comment in llama_memory_recurrent::state_read
1 parent a1de614 commit 08618ff

11 files changed

Lines changed: 383 additions & 17 deletions

‎src/llama-context.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2736,6 +2736,10 @@ class llama_io_read_host : public llama_io_read_i {
27362736
buf_size -= size;
27372737
}
27382738

2739+
void discard() override {
2740+
rinfos.clear();
2741+
}
2742+
27392743
size_t n_bytes() override {
27402744
return size_read;
27412745
}
@@ -3086,6 +3090,11 @@ class llama_io_read_device : public llama_io_read_i {
30863090
rinfos.push_back({tensor, ptr, size, offset});
30873091
}
30883092

3093+
void discard() override {
3094+
rinfos.clear();
3095+
buf_size = 0;
3096+
}
3097+
30893098
size_t n_bytes() override {
30903099
return size_read;
30913100
}
@@ -3132,6 +3141,7 @@ size_t llama_context::state_set_data(const uint8_t * src, size_t size) {
31323141
return state_read_data(io);
31333142
} catch (const std::exception & err) {
31343143
LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
3144+
io.discard();
31353145
return 0;
31363146
}
31373147
}
@@ -3205,6 +3215,7 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr
32053215
return state_seq_read_data(*io, seq_id, flags);
32063216
} catch (const std::exception & err) {
32073217
LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
3218+
io->discard();
32083219
return 0;
32093220
}
32103221
}

‎src/llama-impl.cpp‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
#include "llama-impl.h"
22

3+
#include "ggml-backend.h"
34
#include "gguf.h"
45
#include "llama.h"
56

7+
#include <algorithm>
68
#include <cinttypes>
79
#include <climits>
810
#include <cstdarg>
@@ -66,6 +68,16 @@ void llama_log_callback_default(ggml_log_level level, const char * text, void *
6668
fflush(stderr);
6769
}
6870

71+
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size) {
72+
static const std::vector<uint8_t> zeros(1024*1024, 0);
73+
74+
// not all backend buffers implement ggml_backend_tensor_memset(), so write zeros instead
75+
// TODO: make this a generic fallback in `ggml_backend_tensor_memset` when `set_tensor` is available
76+
for (size_t ofs = 0; ofs < size; ofs += zeros.size()) {
77+
ggml_backend_tensor_set(t, zeros.data(), offset + ofs, std::min(size - ofs, zeros.size()));
78+
}
79+
}
80+
6981
void replace_all(std::string & s, const std::string & search, const std::string & replace) {
7082
if (search.empty()) {
7183
return;

‎src/llama-impl.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ struct buffer_view {
9393
}
9494
};
9595

96+
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size);
97+
9698
void replace_all(std::string & s, const std::string & search, const std::string & replace);
9799

98100
// TODO: rename to llama_format ?

‎src/llama-io.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ class llama_io_read_i {
2828
virtual void read(void * dst, size_t size) = 0;
2929
virtual void read_tensor(ggml_tensor * tensor, size_t offset, size_t size) = 0;
3030

31+
// drop tensor data that has been read but not yet applied (e.g. when a restore fails)
32+
virtual void discard() {}
33+
3134
// bytes read so far
3235
virtual size_t n_bytes() = 0;
3336

‎src/llama-kv-cache-dsa.cpp‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,15 @@ void llama_kv_cache_dsa::state_write(llama_io_write_i & io, llama_seq_id seq_id,
168168

169169
void llama_kv_cache_dsa::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
170170
kv_mla->state_read(io, seq_id, flags);
171-
kv_lid->state_read(io, seq_id, flags);
171+
172+
try {
173+
kv_lid->state_read(io, seq_id, flags);
174+
} catch (...) {
175+
// the MLA part is already restored - undo it, so that a failed restore leaves nothing behind
176+
kv_mla->state_clear(seq_id);
177+
178+
throw;
179+
}
172180
}
173181

174182
llama_kv_cache * llama_kv_cache_dsa::get_mla() const {

‎src/llama-kv-cache.cpp‎

Lines changed: 112 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2188,11 +2188,7 @@ const slot_info_vec_t * sinfos_in) {
21882188
}
21892189

21902190
if (!res) {
2191-
if (seq_id == -1) {
2192-
clear(true);
2193-
} else {
2194-
seq_rm(seq_id, -1, -1);
2195-
}
2191+
state_clear(seq_id, strm, sinfo);
21962192
throw std::runtime_error("failed to restore kv cache");
21972193
}
21982194

@@ -2340,6 +2336,11 @@ bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32
23402336

23412337
if (dest_seq_id != -1) {
23422338
// single sequence
2339+
if (cell_count > cells.size()) {
2340+
LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
2341+
return false;
2342+
}
2343+
23432344
seq_rm(dest_seq_id, -1, -1);
23442345

23452346
llama_batch_allocr balloc(hparams.n_pos_per_embd());
@@ -2663,6 +2664,112 @@ bool llama_kv_cache::state_read_data(llama_io_read_i & io, uint32_t strm, uint32
26632664
return true;
26642665
}
26652666

2667+
void llama_kv_cache::state_clear(llama_seq_id seq_id) {
2668+
if (seq_id == -1) {
2669+
clear(true);
2670+
return;
2671+
}
2672+
2673+
GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
2674+
2675+
const uint32_t strm = seq_to_stream[seq_id];
2676+
2677+
const auto & cells = v_cells[strm];
2678+
2679+
slot_info sinfo;
2680+
sinfo.s0 = strm;
2681+
sinfo.s1 = strm;
2682+
sinfo.resize(1);
2683+
sinfo.strm[0] = strm;
2684+
2685+
// a cell that another sequence still uses keeps its data
2686+
for (uint32_t i = 0; i < cells.size(); ++i) {
2687+
if (cells.seq_has(i, seq_id) && cells.seq_count(i) == 1) {
2688+
sinfo.idxs[0].push_back(i);
2689+
}
2690+
}
2691+
2692+
state_clear(seq_id, strm, sinfo);
2693+
}
2694+
2695+
// the cleared ranges mirror the write pattern of state_read_data() - keep both in sync
2696+
void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_info & sinfo) {
2697+
if (seq_id == -1) {
2698+
clear(true);
2699+
return;
2700+
}
2701+
2702+
seq_rm(seq_id, -1, -1);
2703+
2704+
// zero the K/V data of the failed restore attempt - the attention can still read the data of free cells
2705+
if (sinfo.empty() || sinfo.size() == 0) {
2706+
return;
2707+
}
2708+
2709+
const auto & cells = v_cells[strm];
2710+
2711+
const uint32_t cell_count = sinfo.size();
2712+
2713+
const bool is_contiguous = sinfo.is_contiguous();
2714+
2715+
for (const auto & layer : layers) {
2716+
const uint32_t il = layer.il;
2717+
2718+
const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
2719+
2720+
auto * k = layer.k_stream[strm];
2721+
2722+
const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
2723+
2724+
if (is_contiguous) {
2725+
llama_clear_tensor_data(k, sinfo.head() * k_size_row, cell_count * k_size_row);
2726+
} else {
2727+
for (uint32_t i = 0; i < cell_count; ++i) {
2728+
llama_clear_tensor_data(k, sinfo.idxs[0][i] * k_size_row, k_size_row);
2729+
}
2730+
}
2731+
}
2732+
2733+
for (const auto & layer : layers) {
2734+
const uint32_t il = layer.il;
2735+
2736+
const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
2737+
2738+
auto * v = layer.v_stream[strm];
2739+
if (!v) {
2740+
continue;
2741+
}
2742+
2743+
if (!v_trans) {
2744+
const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
2745+
2746+
if (is_contiguous) {
2747+
llama_clear_tensor_data(v, sinfo.head() * v_size_row, cell_count * v_size_row);
2748+
} else {
2749+
for (uint32_t i = 0; i < cell_count; ++i) {
2750+
llama_clear_tensor_data(v, sinfo.idxs[0][i] * v_size_row, v_size_row);
2751+
}
2752+
}
2753+
} else {
2754+
const size_t v_size_el = ggml_type_size(v->type);
2755+
2756+
if (is_contiguous) {
2757+
const uint32_t h = sinfo.head();
2758+
2759+
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
2760+
llama_clear_tensor_data(v, (h + j * cells.size()) * v_size_el, cell_count * v_size_el);
2761+
}
2762+
} else {
2763+
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
2764+
for (uint32_t i = 0; i < cell_count; ++i) {
2765+
llama_clear_tensor_data(v, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el);
2766+
}
2767+
}
2768+
}
2769+
}
2770+
}
2771+
}
2772+
26662773
//
26672774
// llama_kv_cache_context
26682775
//

‎src/llama-kv-cache.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,9 @@ class llama_kv_cache : public llama_memory_i {
179179
slot_info_vec_t * sinfos_out,
180180
const slot_info_vec_t * sinfos_in);
181181

182+
// undo a state_read() of seq_id (-1 for the whole cache) that another memory module failed to complete
183+
void state_clear(llama_seq_id seq_id);
184+
182185
//
183186
// graph_build API
184187
//
@@ -345,6 +348,8 @@ class llama_kv_cache : public llama_memory_i {
345348
// sinfo_in, when set, replaces the find_slot call: the cells are given by the caller
346349
bool state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, slot_info & sinfo, llama_seq_id dest_seq_id = -1, const slot_info * sinfo_in = nullptr);
347350
bool state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, const slot_info & sinfo);
351+
352+
void state_clear(llama_seq_id seq_id, uint32_t strm, const slot_info & sinfo);
348353
};
349354

350355
class llama_kv_cache_context : public llama_memory_context_i {

‎src/llama-memory-hybrid.cpp‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,22 @@ void llama_memory_hybrid::state_write(llama_io_write_i & io, llama_seq_id seq_id
195195
}
196196

197197
void llama_memory_hybrid::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
198-
if ((flags & LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == 0) {
198+
const bool read_attn = (flags & LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY) == 0;
199+
200+
if (read_attn) {
199201
mem_attn->state_read(io, seq_id, flags);
200202
}
201-
mem_recr->state_read(io, seq_id, flags);
203+
204+
try {
205+
mem_recr->state_read(io, seq_id, flags);
206+
} catch (...) {
207+
// the attention part is already restored - undo it
208+
if (read_attn) {
209+
mem_attn->state_clear(seq_id);
210+
}
211+
212+
throw;
213+
}
202214
}
203215

204216
llama_kv_cache * llama_memory_hybrid::get_mem_attn() const {

‎src/llama-memory-recurrent.cpp‎

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -852,7 +852,12 @@ void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_i
852852

853853
bool res = true;
854854

855-
res = res && state_read_meta(io, cell_count, seq_id);
855+
// save the head of the restored cells - could be needed to clear the state
856+
// the head is valid only when state_read_meta() succeeded
857+
const bool meta_read = state_read_meta(io, cell_count, seq_id);
858+
const uint32_t cell_head = head;
859+
860+
res = res && meta_read;
856861

857862
try {
858863
res = res && state_read_data(io, cell_count);
@@ -861,12 +866,7 @@ void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_i
861866
}
862867

863868
if (!res) {
864-
// TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG]
865-
if (seq_id == -1) {
866-
clear(true);
867-
} else {
868-
seq_rm(seq_id, -1, -1);
869-
}
869+
state_clear(seq_id, cell_head, meta_read ? cell_count : 0);
870870
throw std::runtime_error("failed to restore kv cache");
871871
}
872872

@@ -992,6 +992,11 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::
992992
bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
993993
if (dest_seq_id != -1) {
994994
// single sequence
995+
if (cell_count > size) {
996+
LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
997+
return false;
998+
}
999+
9951000
seq_rm(dest_seq_id, -1, -1);
9961001

9971002
if (cell_count == 0) {
@@ -1223,6 +1228,41 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell
12231228
return true;
12241229
}
12251230

1231+
// the cleared ranges mirror the write pattern of state_read_data() - keep both in sync
1232+
// the transposed s layout is not handled - state_read_data() rejects it before any write
1233+
void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head, uint32_t cell_count) {
1234+
// TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG]
1235+
if (seq_id == -1) {
1236+
clear(true);
1237+
return;
1238+
}
1239+
1240+
seq_rm(seq_id, -1, -1);
1241+
1242+
if (cell_count == 0) {
1243+
return;
1244+
}
1245+
1246+
const uint32_t n_layer = hparams.n_layer();
1247+
1248+
for (uint32_t il = 0; il < n_layer; ++il) {
1249+
if (r_l[il] != nullptr) {
1250+
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
1251+
llama_clear_tensor_data(r_l[il], cell_head * r_size_row, cell_count * r_size_row);
1252+
}
1253+
1254+
if (s_l[il] != nullptr) {
1255+
const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
1256+
llama_clear_tensor_data(s_l[il], cell_head * s_size_row, cell_count * s_size_row);
1257+
}
1258+
1259+
if (p_l[il] != nullptr) {
1260+
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
1261+
llama_clear_tensor_data(p_l[il], cell_head * p_size_row, cell_count * p_size_row);
1262+
}
1263+
}
1264+
}
1265+
12261266
//
12271267
// llama_memory_recurrent_context
12281268
//

‎src/llama-memory-recurrent.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ class llama_memory_recurrent : public llama_memory_i {
134134

135135
bool state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id = -1);
136136
bool state_read_data(llama_io_read_i & io, uint32_t cell_count);
137+
138+
void state_clear(llama_seq_id seq_id, uint32_t cell_head, uint32_t cell_count);
137139
};
138140

139141
class llama_memory_recurrent_context : public llama_memory_context_i {

0 commit comments

Comments
 (0)