cui-llama.rn 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/android/src/main/jni.cpp +9 -9
  2. package/cpp/common.cpp +163 -60
  3. package/cpp/common.h +43 -12
  4. package/cpp/ggml-alloc.c +1042 -1037
  5. package/cpp/ggml-backend-impl.h +255 -256
  6. package/cpp/ggml-backend-reg.cpp +582 -582
  7. package/cpp/ggml-backend.cpp +2002 -2002
  8. package/cpp/ggml-backend.h +354 -352
  9. package/cpp/ggml-common.h +1853 -1853
  10. package/cpp/ggml-cpp.h +39 -39
  11. package/cpp/ggml-cpu-aarch64.cpp +4247 -4247
  12. package/cpp/ggml-cpu-aarch64.h +8 -8
  13. package/cpp/ggml-cpu-impl.h +386 -386
  14. package/cpp/ggml-cpu-quants.c +10920 -10839
  15. package/cpp/ggml-cpu-traits.cpp +36 -36
  16. package/cpp/ggml-cpu-traits.h +38 -38
  17. package/cpp/ggml-cpu.c +329 -60
  18. package/cpp/ggml-cpu.cpp +10 -2
  19. package/cpp/ggml-cpu.h +135 -135
  20. package/cpp/ggml-impl.h +567 -567
  21. package/cpp/ggml-metal-impl.h +17 -17
  22. package/cpp/ggml-metal.m +4884 -4884
  23. package/cpp/ggml-quants.c +5238 -5238
  24. package/cpp/ggml-threading.h +14 -14
  25. package/cpp/ggml.c +6514 -6448
  26. package/cpp/ggml.h +2194 -2163
  27. package/cpp/gguf.cpp +1329 -1325
  28. package/cpp/gguf.h +202 -202
  29. package/cpp/json-schema-to-grammar.cpp +1045 -1045
  30. package/cpp/json-schema-to-grammar.h +8 -8
  31. package/cpp/json.hpp +24766 -24766
  32. package/cpp/llama-adapter.cpp +347 -346
  33. package/cpp/llama-adapter.h +74 -73
  34. package/cpp/llama-arch.cpp +1487 -1434
  35. package/cpp/llama-arch.h +400 -395
  36. package/cpp/llama-batch.cpp +368 -368
  37. package/cpp/llama-batch.h +88 -88
  38. package/cpp/llama-chat.cpp +578 -567
  39. package/cpp/llama-chat.h +52 -51
  40. package/cpp/llama-context.cpp +1775 -1771
  41. package/cpp/llama-context.h +128 -128
  42. package/cpp/llama-cparams.cpp +1 -1
  43. package/cpp/llama-cparams.h +37 -37
  44. package/cpp/llama-cpp.h +30 -30
  45. package/cpp/llama-grammar.cpp +1139 -1139
  46. package/cpp/llama-grammar.h +143 -143
  47. package/cpp/llama-hparams.cpp +71 -71
  48. package/cpp/llama-hparams.h +139 -140
  49. package/cpp/llama-impl.cpp +167 -167
  50. package/cpp/llama-impl.h +61 -61
  51. package/cpp/llama-kv-cache.cpp +718 -718
  52. package/cpp/llama-kv-cache.h +218 -218
  53. package/cpp/llama-mmap.cpp +2 -1
  54. package/cpp/llama-mmap.h +67 -67
  55. package/cpp/llama-model-loader.cpp +1124 -1011
  56. package/cpp/llama-model-loader.h +167 -158
  57. package/cpp/llama-model.cpp +3997 -2202
  58. package/cpp/llama-model.h +370 -391
  59. package/cpp/llama-sampling.cpp +2408 -2406
  60. package/cpp/llama-sampling.h +32 -48
  61. package/cpp/llama-vocab.cpp +3247 -1982
  62. package/cpp/llama-vocab.h +125 -182
  63. package/cpp/llama.cpp +416 -2886
  64. package/cpp/llama.h +1323 -1285
  65. package/cpp/log.cpp +401 -401
  66. package/cpp/log.h +121 -121
  67. package/cpp/rn-llama.hpp +18 -12
  68. package/cpp/sampling.cpp +505 -500
  69. package/cpp/sgemm.cpp +2597 -2597
  70. package/cpp/speculative.cpp +277 -274
  71. package/cpp/speculative.h +28 -28
  72. package/cpp/unicode.cpp +2 -3
  73. package/package.json +1 -1
@@ -1,1771 +1,1775 @@
1
- #include "llama-context.h"
2
-
3
- #include <cassert>
4
- #include <cmath>
5
- #include <cstring>
6
- #include <stdexcept>
7
-
8
- void llama_set_k_shift(struct llama_context & lctx) {
9
- const int64_t kv_size = lctx.kv_self.size;
10
-
11
- assert(lm_ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
12
-
13
- int32_t * data = (int32_t *) lctx.inp_K_shift->data;
14
-
15
- for (int i = 0; i < kv_size; ++i) {
16
- data[i] = lctx.kv_self.cells[i].delta;
17
- }
18
- }
19
-
20
- void llama_set_s_copy(struct llama_context & lctx) {
21
- const int64_t kv_size = lctx.kv_self.size;
22
-
23
- assert(lm_ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
24
-
25
- int32_t * data = (int32_t *) lctx.inp_s_copy->data;
26
-
27
- for (int i = 0; i < kv_size; ++i) {
28
- data[i] = lctx.kv_self.cells[i].src;
29
- }
30
- }
31
-
32
- // llama input
33
-
34
- static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
35
- // TODO move to hparams if a T5 variant appears that uses a different value
36
- const int64_t max_distance = 128;
37
-
38
- if (bidirectional) {
39
- n_buckets >>= 1;
40
- }
41
-
42
- const int64_t max_exact = n_buckets >> 1;
43
-
44
- int32_t relative_position = x - y;
45
- int32_t relative_bucket = 0;
46
- if (bidirectional) {
47
- relative_bucket += (relative_position > 0) * n_buckets;
48
- relative_position = abs(relative_position);
49
- } else {
50
- relative_position = -std::min<int32_t>(relative_position, 0);
51
- }
52
- int32_t relative_position_if_large = floorf(max_exact + logf(1.0 * relative_position / max_exact) * (n_buckets - max_exact) / log(1.0 * max_distance / max_exact));
53
- relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
54
- relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
55
- return relative_bucket;
56
- }
57
-
58
- void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch) {
59
- //
60
- // set input data
61
- //
62
-
63
- const auto & hparams = lctx.model.hparams;
64
- const auto & cparams = lctx.cparams;
65
- const auto & kv_self = lctx.kv_self;
66
-
67
- if (ubatch.token) {
68
- const int64_t n_tokens = ubatch.n_tokens;
69
-
70
- lm_ggml_backend_tensor_set(lctx.inp_tokens, ubatch.token, 0, n_tokens*lm_ggml_element_size(lctx.inp_tokens));
71
- }
72
-
73
- if (ubatch.embd) {
74
- const int64_t n_embd = hparams.n_embd;
75
- const int64_t n_tokens = ubatch.n_tokens;
76
-
77
- lm_ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*lm_ggml_element_size(lctx.inp_embd));
78
- }
79
-
80
- if (ubatch.pos && lctx.inp_pos) {
81
- const int64_t n_tokens = ubatch.n_tokens;
82
- auto n_pos = lctx.n_pos_per_token;
83
- lm_ggml_backend_tensor_set(lctx.inp_pos, ubatch.pos, 0, n_tokens*n_pos*lm_ggml_element_size(lctx.inp_pos));
84
- }
85
-
86
- if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
87
- //LM_GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
88
-
89
- if (!lctx.inp_out_ids) {
90
- LLAMA_LOG_WARN("%s: 'lctx.inp_out_ids' is not created\n", __func__);
91
- } else {
92
- const int64_t n_tokens = ubatch.n_tokens;
93
-
94
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
95
- int32_t * data = (int32_t *) lctx.inp_out_ids->data;
96
-
97
- if (lctx.n_outputs == n_tokens) {
98
- for (int i = 0; i < n_tokens; ++i) {
99
- data[i] = i;
100
- }
101
- } else if (ubatch.output) {
102
- int32_t n_outputs = 0;
103
- for (int i = 0; i < n_tokens; ++i) {
104
- if (ubatch.output[i]) {
105
- data[n_outputs++] = i;
106
- }
107
- }
108
- // the graph needs to have been passed the correct number of outputs
109
- LM_GGML_ASSERT(lctx.n_outputs == n_outputs);
110
- } else if (lctx.n_outputs == 1) {
111
- // only keep last output
112
- data[0] = n_tokens - 1;
113
- } else {
114
- LM_GGML_ASSERT(lctx.n_outputs == 0);
115
- }
116
- }
117
- }
118
-
119
- LM_GGML_ASSERT(
120
- // (!a || b) is a logical implication (a -> b)
121
- // !hparams.causal_attn -> !cparams.causal_attn
122
- (hparams.causal_attn || !cparams.causal_attn) &&
123
- "causal attention is not supported by this model"
124
- );
125
-
126
- if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
127
- // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
128
- if (cparams.causal_attn && !lctx.is_encoding) {
129
- const int64_t n_kv = kv_self.n;
130
- const int64_t n_tokens = ubatch.n_tokens;
131
- const int64_t n_seq_tokens = ubatch.n_seq_tokens;
132
- const int64_t n_seqs = ubatch.n_seqs;
133
-
134
-
135
- float * data = nullptr;
136
- float * data_swa = nullptr;
137
-
138
- if (lctx.inp_KQ_mask) {
139
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
140
- data = (float *) lctx.inp_KQ_mask->data;
141
- }
142
-
143
- if (lctx.inp_KQ_mask_swa) {
144
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
145
- data_swa = (float *) lctx.inp_KQ_mask_swa->data;
146
- }
147
-
148
- // For causal attention, use only the previous KV cells
149
- // of the correct sequence for each token of the ubatch.
150
- // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
151
- for (int h = 0; h < 1; ++h) {
152
- for (int s = 0; s < n_seqs; ++s) {
153
- const llama_seq_id seq_id = ubatch.seq_id[s][0];
154
-
155
- for (int j = 0; j < n_seq_tokens; ++j) {
156
- const llama_pos pos = ubatch.pos[s*n_seq_tokens + j];
157
-
158
- for (int i = 0; i < n_kv; ++i) {
159
- float f;
160
- if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
161
- f = -INFINITY;
162
- } else {
163
- if (hparams.use_alibi) {
164
- f = -std::abs(kv_self.cells[i].pos - pos);
165
- } else {
166
- f = 0.0f;
167
- }
168
- }
169
-
170
- if (data) {
171
- data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
172
- }
173
-
174
- // may need to cut off old tokens for sliding window
175
- if (data_swa) {
176
- if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
177
- f = -INFINITY;
178
- }
179
- data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
180
- }
181
- }
182
- }
183
- }
184
-
185
- if (data) {
186
- for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
187
- for (int j = 0; j < n_kv; ++j) {
188
- data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
189
- }
190
- }
191
- }
192
-
193
- if (data_swa) {
194
- for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
195
- for (int j = 0; j < n_kv; ++j) {
196
- data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
197
- }
198
- }
199
- }
200
- }
201
- } else {
202
- const int64_t n_tokens = ubatch.n_tokens;
203
- const int64_t n_seq_tokens = ubatch.n_seq_tokens;
204
- const int64_t n_seqs = ubatch.n_seqs;
205
- // when using kv cache, the mask needs to match the kv cache size
206
- const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
207
-
208
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
209
-
210
- float * data = (float *) lctx.inp_KQ_mask->data;
211
-
212
- for (int h = 0; h < 1; ++h) {
213
- for (int s1 = 0; s1 < n_seqs; ++s1) {
214
- const llama_seq_id seq_id = ubatch.seq_id[s1][0];
215
-
216
- for (int j = 0; j < n_seq_tokens; ++j) {
217
- const int32_t tj = s1*n_seq_tokens + j;
218
-
219
- for (int s0 = 0; s0 < n_seqs; ++s0) {
220
- for (int i = 0; i < n_seq_tokens; ++i) {
221
- const int32_t ti = s0*n_seq_tokens + i;
222
- float f = -INFINITY;
223
-
224
- for (int s = 0; s < ubatch.n_seq_id[s0]; ++s) {
225
- if (ubatch.seq_id[s0][s] == seq_id) {
226
- if (hparams.use_alibi) {
227
- f = -std::abs(ubatch.pos[ti] - ubatch.pos[tj]);
228
- } else {
229
- f = 0.0f;
230
- }
231
- break;
232
- }
233
- }
234
-
235
- data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
236
- }
237
- }
238
-
239
- for (int i = n_tokens; i < n_stride; ++i) {
240
- data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
241
- }
242
- }
243
- }
244
- }
245
- }
246
- }
247
-
248
- if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
249
- const int64_t n_tokens = ubatch.n_tokens;
250
- const int64_t n_seq_tokens = ubatch.n_seq_tokens;
251
- const int64_t n_seqs = ubatch.n_seqs;
252
-
253
- LM_GGML_ASSERT(lctx.inp_mean);
254
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
255
-
256
- float * data = (float *) lctx.inp_mean->data;
257
- memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * lm_ggml_element_size(lctx.inp_mean));
258
-
259
- std::vector<uint64_t> sum(n_tokens, 0);
260
-
261
- for (int s = 0; s < n_seqs; ++s) {
262
- const llama_seq_id seq_id = ubatch.seq_id[s][0];
263
-
264
- // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
265
- LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
266
-
267
- sum[seq_id] += ubatch.n_seq_tokens;
268
- }
269
-
270
- std::vector<float> div(n_tokens, 0.0f);
271
- for (int i = 0; i < n_tokens; ++i) {
272
- const uint64_t s = sum[i];
273
- if (s > 0) {
274
- div[i] = 1.0f/float(s);
275
- }
276
- }
277
-
278
- for (int s = 0; s < n_seqs; ++s) {
279
- const llama_seq_id seq_id = ubatch.seq_id[s][0];
280
-
281
- for (int i = 0; i < n_seq_tokens; ++i) {
282
- data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
283
- }
284
- }
285
- }
286
-
287
- if (cparams.embeddings && (
288
- cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
289
- cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
290
- const int64_t n_tokens = ubatch.n_tokens;
291
- const int64_t n_seq_tokens = ubatch.n_seq_tokens;
292
- const int64_t n_seqs = ubatch.n_seqs;
293
-
294
- LM_GGML_ASSERT(lctx.inp_cls);
295
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
296
-
297
- uint32_t * data = (uint32_t *) lctx.inp_cls->data;
298
- memset(lctx.inp_cls->data, 0, n_tokens * lm_ggml_element_size(lctx.inp_cls));
299
-
300
- for (int s = 0; s < n_seqs; ++s) {
301
- const llama_seq_id seq_id = ubatch.seq_id[s][0];
302
-
303
- // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
304
- LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
305
-
306
- for (int i = 0; i < n_seq_tokens; ++i) {
307
- const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
308
-
309
- if (pos == 0) {
310
- data[seq_id] = s*n_seq_tokens + i;
311
- }
312
- }
313
- }
314
- }
315
-
316
- if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
317
- const int64_t n_tokens = ubatch.n_tokens;
318
- const int64_t n_seq_tokens = ubatch.n_seq_tokens;
319
- const int64_t n_seqs = ubatch.n_seqs;
320
-
321
- LM_GGML_ASSERT(lctx.inp_cls);
322
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
323
-
324
- uint32_t * data = (uint32_t *) lctx.inp_cls->data;
325
- memset(lctx.inp_cls->data, 0, n_tokens * lm_ggml_element_size(lctx.inp_cls));
326
-
327
- std::vector<int> last_pos(n_tokens, -1);
328
- std::vector<int> last_row(n_tokens, -1);
329
-
330
- for (int s = 0; s < n_seqs; ++s) {
331
- const llama_seq_id seq_id = ubatch.seq_id[s][0];
332
-
333
- // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
334
- LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
335
-
336
- for (int i = 0; i < n_seq_tokens; ++i) {
337
- const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
338
-
339
- if (pos >= last_pos[seq_id]) {
340
- last_pos[seq_id] = pos;
341
- last_row[seq_id] = s*n_seq_tokens + i;
342
- }
343
- }
344
- }
345
-
346
- for (int i = 0; i < n_tokens; ++i) {
347
- if (last_row[i] >= 0) {
348
- data[i] = last_row[i];
349
- }
350
- }
351
- }
352
-
353
- if (kv_self.recurrent) {
354
- const int64_t n_kv = kv_self.n;
355
-
356
- if (lctx.inp_s_mask) {
357
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
358
- float * data = (float *) lctx.inp_s_mask->data;
359
-
360
- // clear unused states
361
- for (int i = 0; i < n_kv; ++i) {
362
- const uint32_t cell_id = i + kv_self.head;
363
- llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
364
-
365
- data[i] = (float) (kv_cell.src >= 0);
366
-
367
- // only clear once
368
- if (kv_cell.src < 0) {
369
- kv_cell.src = cell_id;
370
- }
371
- }
372
- }
373
-
374
- if (lctx.inp_s_copy) {
375
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
376
- int32_t * data = (int32_t *) lctx.inp_s_copy->data;
377
-
378
- // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
379
- for (uint32_t i = 0; i < n_kv; ++i) {
380
- const uint32_t cell_id = i + kv_self.head;
381
- llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
382
-
383
- // prevent out-of-bound sources
384
- if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
385
- kv_cell.src = cell_id;
386
- }
387
-
388
- data[i] = kv_cell.src;
389
-
390
- // ensure copy only happens once
391
- if (kv_cell.src != (int32_t) cell_id) {
392
- kv_cell.src = cell_id;
393
- }
394
- }
395
- }
396
- }
397
-
398
- if (lctx.inp_pos_bucket) {
399
- const int64_t n_tokens = ubatch.n_tokens;
400
-
401
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
402
- LM_GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
403
-
404
- int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
405
-
406
- if (!lctx.is_encoding) {
407
- const int64_t n_kv = kv_self.n;
408
- for (int h = 0; h < 1; ++h) {
409
- for (int j = 0; j < n_tokens; ++j) {
410
- for (int i = 0; i < n_kv; ++i) {
411
- data[h*(n_kv*n_tokens) + j*n_kv + i] = llama_relative_position_bucket(lctx.kv_self.cells[i].pos, ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
412
- }
413
- }
414
- }
415
- } else {
416
- for (int h = 0; h < 1; ++h) {
417
- for (int j = 0; j < n_tokens; ++j) {
418
- for (int i = 0; i < n_tokens; ++i) {
419
- data[h*(n_tokens*n_tokens) + j*n_tokens + i] = llama_relative_position_bucket(ubatch.pos[i], ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
420
- }
421
- }
422
- }
423
- }
424
- }
425
-
426
- if (!lctx.is_encoding && lctx.inp_embd_enc) {
427
- assert(lctx.inp_embd_enc->type == LM_GGML_TYPE_F32);
428
- assert((size_t) lm_ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
429
-
430
- lm_ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, lm_ggml_nbytes(lctx.inp_embd_enc));
431
- }
432
-
433
- if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
434
- const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
435
- const int64_t n_tokens = ubatch.n_tokens;
436
-
437
- LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
438
- LM_GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
439
-
440
- float * data = (float *) lctx.inp_KQ_mask_cross->data;
441
-
442
- for (int h = 0; h < 1; ++h) {
443
- for (int j = 0; j < n_tokens; ++j) {
444
- for (int i = 0; i < n_output_enc; ++i) {
445
- float f = -INFINITY;
446
- for (int s = 0; s < ubatch.n_seq_id[j]; ++s) {
447
- const llama_seq_id seq_id = ubatch.seq_id[j][s];
448
- if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
449
- f = 0.0f;
450
- }
451
- }
452
- data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
453
- }
454
- }
455
-
456
- for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
457
- for (int j = 0; j < n_output_enc; ++j) {
458
- data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
459
- }
460
- }
461
- }
462
- }
463
- }
464
-
465
- // llama output
466
-
467
- size_t llama_output_reserve(struct llama_context & lctx, size_t n_outputs) {
468
- const auto & cparams = lctx.cparams;
469
- const auto & hparams = lctx.model.hparams;
470
-
471
- const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
472
-
473
- const auto n_batch = cparams.n_batch;
474
- const auto n_vocab = hparams.n_vocab;
475
- const auto n_embd = hparams.n_embd;
476
-
477
- // TODO: use a per-batch flag for logits presence instead
478
- const bool has_logits = !cparams.embeddings;
479
- const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
480
-
481
- const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
482
- const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
483
-
484
- if (lctx.output_ids.empty()) {
485
- // init, never resized afterwards
486
- lctx.output_ids.resize(n_batch);
487
- }
488
-
489
- const size_t prev_size = lctx.buf_output ? lm_ggml_backend_buffer_get_size(lctx.buf_output.get()) : 0;
490
- const size_t new_size = (logits_size + embd_size) * sizeof(float);
491
-
492
- // alloc only when more than the current capacity is required
493
- // TODO: also consider shrinking the buffer
494
- if (!lctx.buf_output || prev_size < new_size) {
495
- if (lctx.buf_output) {
496
- #ifndef NDEBUG
497
- // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
498
- LLAMA_LOG_INFO("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
499
- #endif
500
- lctx.buf_output = nullptr;
501
- lctx.logits = nullptr;
502
- lctx.embd = nullptr;
503
- }
504
-
505
- auto * buft = lm_ggml_backend_cpu_buffer_type();
506
- // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
507
- auto * output_dev = lctx.model.dev_output.dev;
508
- auto * output_dev_host_buft = output_dev ? lm_ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
509
- if (output_dev_host_buft) {
510
- buft = output_dev_host_buft;
511
- }
512
- lctx.buf_output.reset(lm_ggml_backend_buft_alloc_buffer(buft, new_size));
513
- if (lctx.buf_output == nullptr) {
514
- LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
515
- return 0;
516
- }
517
- }
518
-
519
- float * output_base = (float *) lm_ggml_backend_buffer_get_base(lctx.buf_output.get());
520
-
521
- lctx.logits = has_logits ? output_base : nullptr;
522
- lctx.embd = has_embd ? output_base + logits_size : nullptr;
523
-
524
- lctx.output_size = n_outputs_max;
525
- lctx.logits_size = logits_size;
526
- lctx.embd_size = embd_size;
527
-
528
- // set all ids as invalid (negative)
529
- std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
530
-
531
- lm_ggml_backend_buffer_clear(lctx.buf_output.get(), 0);
532
-
533
- lctx.n_outputs = 0;
534
-
535
- return n_outputs_max;
536
- }
537
-
538
- void llama_output_reorder(struct llama_context & ctx) {
539
- std::vector<size_t> & out_ids = ctx.sbatch.out_ids;
540
- if (!out_ids.empty()) {
541
- const uint32_t n_vocab = ctx.model.hparams.n_vocab;
542
- const uint32_t n_embd = ctx.model.hparams.n_embd;
543
-
544
- const int32_t n_outputs = ctx.n_outputs;
545
- LM_GGML_ASSERT((size_t) n_outputs == out_ids.size());
546
-
547
- // TODO: is there something more efficient which also minimizes swaps?
548
- // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
549
- for (int32_t i = 0; i < n_outputs - 1; ++i) {
550
- int32_t j_min = i;
551
- for (int32_t j = i + 1; j < n_outputs; ++j) {
552
- if (out_ids[j] < out_ids[j_min]) {
553
- j_min = j;
554
- }
555
- }
556
- if (j_min == i) { continue; }
557
- std::swap(out_ids[i], out_ids[j_min]);
558
- if (ctx.logits_size > 0) {
559
- for (uint32_t k = 0; k < n_vocab; k++) {
560
- std::swap(ctx.logits[i*n_vocab + k], ctx.logits[j_min*n_vocab + k]);
561
- }
562
- }
563
- if (ctx.embd_size > 0) {
564
- for (uint32_t k = 0; k < n_embd; k++) {
565
- std::swap(ctx.embd[i*n_embd + k], ctx.embd[j_min*n_embd + k]);
566
- }
567
- }
568
- }
569
- std::fill(ctx.output_ids.begin(), ctx.output_ids.end(), -1);
570
- for (int32_t i = 0; i < n_outputs; ++i) {
571
- ctx.output_ids[out_ids[i]] = i;
572
- }
573
- out_ids.clear();
574
- }
575
- }
576
-
577
- //
578
- // interface implementation
579
- //
580
-
581
- void llama_free(struct llama_context * ctx) {
582
- delete ctx;
583
- }
584
-
585
- uint32_t llama_n_ctx(const struct llama_context * ctx) {
586
- return ctx->cparams.n_ctx;
587
- }
588
-
589
- uint32_t llama_n_batch(const struct llama_context * ctx) {
590
- return ctx->cparams.n_batch;
591
- }
592
-
593
- uint32_t llama_n_ubatch(const struct llama_context * ctx) {
594
- return ctx->cparams.n_ubatch;
595
- }
596
-
597
- uint32_t llama_n_seq_max(const struct llama_context * ctx) {
598
- return ctx->kv_self.size;
599
- }
600
-
601
- const struct llama_model * llama_get_model(const struct llama_context * ctx) {
602
- return &ctx->model;
603
- }
604
-
605
- enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
606
- return ctx->cparams.pooling_type;
607
- }
608
-
609
- void llama_attach_threadpool(
610
- struct llama_context * ctx,
611
- lm_ggml_threadpool_t threadpool,
612
- lm_ggml_threadpool_t threadpool_batch) {
613
- ctx->threadpool = threadpool;
614
- ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
615
- }
616
-
617
- void llama_detach_threadpool(struct llama_context * ctx) {
618
- ctx->threadpool = nullptr;
619
- ctx->threadpool_batch = nullptr;
620
- }
621
-
622
- void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
623
- ctx->cparams.n_threads = n_threads;
624
- ctx->cparams.n_threads_batch = n_threads_batch;
625
- }
626
-
627
- int32_t llama_n_threads(struct llama_context * ctx) {
628
- return ctx->cparams.n_threads;
629
- }
630
-
631
- int32_t llama_n_threads_batch(struct llama_context * ctx) {
632
- return ctx->cparams.n_threads_batch;
633
- }
634
-
635
- void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
636
- ctx->abort_callback = abort_callback;
637
- ctx->abort_callback_data = abort_callback_data;
638
-
639
- for (auto & backend : ctx->backends) {
640
- auto * reg = lm_ggml_backend_dev_backend_reg(lm_ggml_backend_get_device(backend.get()));
641
- auto * set_abort_callback_fn = (lm_ggml_backend_set_abort_callback_t) lm_ggml_backend_reg_get_proc_address(reg, "lm_ggml_backend_set_abort_callback");
642
- if (set_abort_callback_fn) {
643
- set_abort_callback_fn(backend.get(), ctx->abort_callback, ctx->abort_callback_data);
644
- }
645
- }
646
- }
647
-
648
- void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
649
- ctx->cparams.embeddings = embeddings;
650
- }
651
-
652
- void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
653
- ctx->cparams.causal_attn = causal_attn;
654
- }
655
-
656
- void llama_synchronize(struct llama_context * ctx) {
657
- lm_ggml_backend_sched_synchronize(ctx->sched.get());
658
-
659
- // FIXME: if multiple single tokens are evaluated without a synchronization,
660
- // the stats will be added to the prompt evaluation stats
661
- // this should only happen when using batch size 1 to evaluate a batch
662
-
663
- // add the evaluation to the stats
664
- if (ctx->n_queued_tokens == 1) {
665
- if (!ctx->cparams.no_perf) {
666
- ctx->t_eval_us += lm_ggml_time_us() - ctx->t_compute_start_us;
667
- }
668
- ctx->n_eval++;
669
- } else if (ctx->n_queued_tokens > 1) {
670
- if (!ctx->cparams.no_perf) {
671
- ctx->t_p_eval_us += lm_ggml_time_us() - ctx->t_compute_start_us;
672
- }
673
- ctx->n_p_eval += ctx->n_queued_tokens;
674
- }
675
-
676
- // get a more accurate load time, upon first eval
677
- if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
678
- ctx->t_load_us = lm_ggml_time_us() - ctx->t_start_us;
679
- ctx->has_evaluated_once = true;
680
- }
681
-
682
- ctx->n_queued_tokens = 0;
683
- ctx->t_compute_start_us = 0;
684
- }
685
-
686
- float * llama_get_logits(struct llama_context * ctx) {
687
- llama_synchronize(ctx);
688
-
689
- // reorder logits for backward compatibility
690
- // TODO: maybe deprecate this
691
- llama_output_reorder(*ctx);
692
-
693
- return ctx->logits;
694
- }
695
-
696
- float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
697
- int32_t j = -1;
698
-
699
- llama_synchronize(ctx);
700
-
701
- try {
702
- if (ctx->logits == nullptr) {
703
- throw std::runtime_error("no logits");
704
- }
705
-
706
- if (i < 0) {
707
- j = ctx->n_outputs + i;
708
- if (j < 0) {
709
- throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
710
- }
711
- } else if ((size_t) i >= ctx->output_ids.size()) {
712
- throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
713
- } else {
714
- j = ctx->output_ids[i];
715
- }
716
-
717
- if (j < 0) {
718
- throw std::runtime_error(format("batch.logits[%d] != true", i));
719
- }
720
- if (j >= ctx->n_outputs) {
721
- // This should not happen
722
- throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
723
- }
724
-
725
- return ctx->logits + j*ctx->model.hparams.n_vocab;
726
- } catch (const std::exception & err) {
727
- LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
728
- #ifndef NDEBUG
729
- LM_GGML_ABORT("fatal error");
730
- #else
731
- return nullptr;
732
- #endif
733
- }
734
- }
735
-
736
- float * llama_get_embeddings(struct llama_context * ctx) {
737
- llama_synchronize(ctx);
738
-
739
- // reorder embeddings for backward compatibility
740
- // TODO: maybe deprecate this
741
- llama_output_reorder(*ctx);
742
-
743
- return ctx->embd;
744
- }
745
-
746
- float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
747
- int32_t j = -1;
748
-
749
- llama_synchronize(ctx);
750
-
751
- try {
752
- if (ctx->embd == nullptr) {
753
- throw std::runtime_error("no embeddings");
754
- }
755
-
756
- if (i < 0) {
757
- j = ctx->n_outputs + i;
758
- if (j < 0) {
759
- throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
760
- }
761
- } else if ((size_t) i >= ctx->output_ids.size()) {
762
- throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
763
- } else {
764
- j = ctx->output_ids[i];
765
- }
766
-
767
- if (j < 0) {
768
- throw std::runtime_error(format("batch.logits[%d] != true", i));
769
- }
770
- if (j >= ctx->n_outputs) {
771
- // This should not happen
772
- throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
773
- }
774
-
775
- return ctx->embd + j*ctx->model.hparams.n_embd;
776
- } catch (const std::exception & err) {
777
- LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
778
- #ifndef NDEBUG
779
- LM_GGML_ABORT("fatal error");
780
- #else
781
- return nullptr;
782
- #endif
783
- }
784
- }
785
-
786
- float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
787
- llama_synchronize(ctx);
788
-
789
- auto it = ctx->embd_seq.find(seq_id);
790
- if (it == ctx->embd_seq.end()) {
791
- return nullptr;
792
- }
793
-
794
- return it->second.data();
795
- }
796
-
797
- // llama state API
798
-
799
- // deprecated
800
- size_t llama_get_state_size(struct llama_context * ctx) {
801
- return llama_state_get_size(ctx);
802
- }
803
-
804
- // deprecated
805
- size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
806
- return llama_state_get_data(ctx, dst, -1);
807
- }
808
-
809
- // deprecated
810
- size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
811
- return llama_state_set_data(ctx, src, -1);
812
- }
813
-
814
- // deprecated
815
- bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
816
- return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
817
- }
818
-
819
- // deprecated
820
- bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
821
- return llama_state_save_file(ctx, path_session, tokens, n_token_count);
822
- }
823
-
824
- // TODO: replace all non-fatal assertions with returned errors or exceptions
825
- struct llama_data_write {
826
- virtual void write(const void * src, size_t size) = 0;
827
- virtual void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) = 0;
828
- virtual size_t get_size_written() = 0;
829
- virtual ~llama_data_write() = default;
830
-
831
- void write_string(const std::string & str) {
832
- uint32_t str_size = str.size();
833
-
834
- write(&str_size, sizeof(str_size));
835
- write(str.data(), str_size);
836
- }
837
-
838
- void write_model_info(const struct llama_context * ctx) {
839
- const std::string arch_str = llm_arch_name(ctx->model.arch);
840
- write_string(arch_str);
841
- // TODO: add more model-specific info which should prevent loading the session file if not identical
842
- }
843
-
844
- //void write_rng(const std::mt19937 & rng) {
845
- // std::ostringstream rng_ss;
846
- // rng_ss << rng;
847
-
848
- // const std::string & rng_str = rng_ss.str();
849
-
850
- // write_string(rng_str);
851
- //}
852
-
853
- void write_output_ids(struct llama_context * ctx) {
854
- llama_output_reorder(*ctx);
855
-
856
- const uint32_t n_outputs = ctx->n_outputs;
857
-
858
- std::vector<int32_t> output_pos;
859
-
860
- const size_t n_batch = ctx->cparams.n_batch;
861
- const auto & output_ids = ctx->output_ids;
862
-
863
- LM_GGML_ASSERT(n_outputs <= ctx->output_size);
864
-
865
- output_pos.resize(n_outputs);
866
-
867
- // build a more compact representation of the output ids
868
- for (size_t i = 0; i < n_batch; ++i) {
869
- // map an output id to a position in the batch
870
- int32_t pos = output_ids[i];
871
- if (pos >= 0) {
872
- LM_GGML_ASSERT((uint32_t) pos < n_outputs);
873
- output_pos[pos] = i;
874
- }
875
- }
876
-
877
- write(&n_outputs, sizeof(n_outputs));
878
-
879
- if (n_outputs) {
880
- write(output_pos.data(), n_outputs * sizeof(int32_t));
881
- }
882
- }
883
-
884
- void write_logits(const struct llama_context * ctx) {
885
- const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_vocab);
886
-
887
- write(&logits_size, sizeof(logits_size));
888
-
889
- if (logits_size) {
890
- write(ctx->logits, logits_size * sizeof(float));
891
- }
892
- }
893
-
894
- void write_embeddings(const struct llama_context * ctx) {
895
- const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
896
-
897
- write(&embeddings_size, sizeof(embeddings_size));
898
-
899
- if (embeddings_size) {
900
- write(ctx->embd, embeddings_size * sizeof(float));
901
- }
902
- }
903
-
904
- void write_kv_cache_meta(const llama_kv_cache & kv_self, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id = -1) {
905
- for (const auto & range : cell_ranges) {
906
- for (uint32_t i = range.first; i < range.second; ++i) {
907
- const auto & cell = kv_self.cells[i];
908
- const llama_pos pos = cell.pos;
909
- const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
910
-
911
- write(&pos, sizeof(pos));
912
- write(&n_seq_id, sizeof(n_seq_id));
913
-
914
- if (n_seq_id) {
915
- for (auto seq_id : cell.seq_id) {
916
- write(&seq_id, sizeof(seq_id));
917
- }
918
- }
919
- }
920
- }
921
- }
922
-
923
- void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
924
- const struct llama_kv_cache & kv_self = ctx->kv_self;
925
- const struct llama_hparams & hparams = ctx->model.hparams;
926
-
927
- const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
928
- const uint32_t n_layer = hparams.n_layer;
929
-
930
- write(&v_trans, sizeof(v_trans));
931
- write(&n_layer, sizeof(n_layer));
932
-
933
- std::vector<uint8_t> tmp_buf;
934
-
935
- // Iterate and write all the keys first, each row is a cell
936
- // Get whole range at a time
937
- for (uint32_t il = 0; il < n_layer; ++il) {
938
- const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
939
-
940
- // Write key type
941
- const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
942
- write(&k_type_i, sizeof(k_type_i));
943
-
944
- // Write row size of key
945
- const uint64_t k_size_row = lm_ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
946
- write(&k_size_row, sizeof(k_size_row));
947
-
948
- // Read each range of cells of k_size length each into tmp_buf and write out
949
- for (const auto & range : cell_ranges) {
950
- const size_t range_size = range.second - range.first;
951
- const size_t buf_size = range_size * k_size_row;
952
- write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
953
- }
954
- }
955
-
956
- if (!kv_self.v_trans) {
957
- for (uint32_t il = 0; il < n_layer; ++il) {
958
- const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
959
-
960
- // Write value type
961
- const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
962
- write(&v_type_i, sizeof(v_type_i));
963
-
964
- // Write row size of value
965
- const uint64_t v_size_row = lm_ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
966
- write(&v_size_row, sizeof(v_size_row));
967
-
968
- // Read each range of cells of v_size length each into tmp_buf and write out
969
- for (const auto & range : cell_ranges) {
970
- const size_t range_size = range.second - range.first;
971
- const size_t buf_size = range_size * v_size_row;
972
- write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
973
- }
974
- }
975
- } else {
976
- // When v is transposed, we also need the element size and get the element ranges from each row
977
- const uint32_t kv_size = kv_self.size;
978
- for (uint32_t il = 0; il < n_layer; ++il) {
979
- const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
980
-
981
- // Write value type
982
- const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
983
- write(&v_type_i, sizeof(v_type_i));
984
-
985
- // Write element size
986
- const uint32_t v_size_el = lm_ggml_type_size(kv_self.v_l[il]->type);
987
- write(&v_size_el, sizeof(v_size_el));
988
-
989
- // Write GQA embedding size
990
- write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
991
-
992
- // For each row, we get the element values of each cell
993
- for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
994
- // Read each range of cells of v_size_el length each into tmp_buf and write out
995
- for (const auto & range : cell_ranges) {
996
- const size_t range_size = range.second - range.first;
997
- const size_t src_offset = (range.first + j * kv_size) * v_size_el;
998
- const size_t buf_size = range_size * v_size_el;
999
- write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
1000
- }
1001
- }
1002
- }
1003
- }
1004
- }
1005
-
1006
- void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
1007
- const struct llama_kv_cache & kv_self = ctx->kv_self;
1008
- std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
1009
- uint32_t cell_count = 0;
1010
-
1011
- // Count the number of cells with the specified seq_id
1012
- // Find all the ranges of cells with this seq id (or all, when -1)
1013
- uint32_t cell_range_begin = kv_self.size;
1014
- for (uint32_t i = 0; i < kv_self.size; ++i) {
1015
- const auto & cell = kv_self.cells[i];
1016
- if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
1017
- ++cell_count;
1018
- if (cell_range_begin == kv_self.size) {
1019
- cell_range_begin = i;
1020
- }
1021
- } else {
1022
- if (cell_range_begin != kv_self.size) {
1023
- cell_ranges.emplace_back(cell_range_begin, i);
1024
- cell_range_begin = kv_self.size;
1025
- }
1026
- }
1027
- }
1028
- if (cell_range_begin != kv_self.size) {
1029
- cell_ranges.emplace_back(cell_range_begin, kv_self.size);
1030
- }
1031
-
1032
- // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
1033
- uint32_t cell_count_check = 0;
1034
- for (const auto & range : cell_ranges) {
1035
- cell_count_check += range.second - range.first;
1036
- }
1037
- LM_GGML_ASSERT(cell_count == cell_count_check);
1038
-
1039
- write(&cell_count, sizeof(cell_count));
1040
-
1041
- write_kv_cache_meta(kv_self, cell_ranges, seq_id);
1042
- write_kv_cache_data(ctx, cell_ranges);
1043
- }
1044
- };
1045
-
1046
- struct llama_data_read {
1047
- virtual const uint8_t * read(size_t size) = 0;
1048
- virtual void read_to(void * dst, size_t size) = 0;
1049
- virtual size_t get_size_read() = 0;
1050
- virtual ~llama_data_read() = default;
1051
-
1052
- void read_string(std::string & str) {
1053
- uint32_t str_size;
1054
- read_to(&str_size, sizeof(str_size));
1055
-
1056
- str.assign((const char *) read(str_size), str_size);
1057
- }
1058
-
1059
- // validate model information
1060
- void read_model_info(const struct llama_context * ctx) {
1061
- const std::string cur_arch_str = llm_arch_name(ctx->model.arch);
1062
-
1063
- std::string arch_str;
1064
- read_string(arch_str);
1065
- if (cur_arch_str != arch_str) {
1066
- throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
1067
- }
1068
- // TODO: add more info which needs to be identical but which is not verified otherwise
1069
- }
1070
-
1071
- //void read_rng(std::mt19937 & rng) {
1072
- // std::string rng_str;
1073
- // read_string(rng_str);
1074
-
1075
- // std::istringstream rng_ss(rng_str);
1076
- // rng_ss >> rng;
1077
-
1078
- // if (rng_ss.fail()) {
1079
- // throw std::runtime_error("failed to load RNG state");
1080
- // }
1081
- //}
1082
-
1083
- void read_output_ids(struct llama_context * ctx) {
1084
- std::vector<int32_t> output_pos;
1085
-
1086
- uint32_t n_outputs;
1087
- read_to(&n_outputs, sizeof(n_outputs));
1088
-
1089
- if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
1090
- throw std::runtime_error("could not reserve outputs");
1091
- }
1092
-
1093
- if (n_outputs) {
1094
- output_pos.resize(n_outputs);
1095
- read_to(output_pos.data(), n_outputs * sizeof(int32_t));
1096
-
1097
- for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
1098
- int32_t id = output_pos[i];
1099
- if ((uint32_t) id >= ctx->cparams.n_batch) {
1100
- throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
1101
- }
1102
- ctx->output_ids[id] = i;
1103
- }
1104
-
1105
- ctx->n_outputs = n_outputs;
1106
- }
1107
- }
1108
-
1109
- void read_logits(struct llama_context * ctx) {
1110
- uint64_t logits_size;
1111
- read_to(&logits_size, sizeof(logits_size));
1112
-
1113
- if (ctx->logits_size < logits_size) {
1114
- throw std::runtime_error("logits buffer too small");
1115
- }
1116
-
1117
- if (logits_size) {
1118
- read_to(ctx->logits, logits_size * sizeof(float));
1119
- }
1120
- }
1121
-
1122
- void read_embeddings(struct llama_context * ctx) {
1123
- uint64_t embeddings_size;
1124
- read_to(&embeddings_size, sizeof(embeddings_size));
1125
-
1126
- if (ctx->embd_size < embeddings_size) {
1127
- throw std::runtime_error("embeddings buffer too small");
1128
- }
1129
-
1130
- if (embeddings_size) {
1131
- read_to(ctx->embd, embeddings_size * sizeof(float));
1132
- }
1133
- }
1134
-
1135
- bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
1136
- struct llama_kv_cache & kv_self = ctx->kv_self;
1137
-
1138
- if (dest_seq_id != -1) {
1139
- // single sequence
1140
-
1141
- llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
1142
-
1143
- llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
1144
- batch.n_tokens = cell_count;
1145
- batch.n_seq_tokens = cell_count;
1146
- batch.n_seqs = 1;
1147
-
1148
- for (uint32_t i = 0; i < cell_count; ++i) {
1149
- llama_pos pos;
1150
- uint32_t n_seq_id;
1151
-
1152
- read_to(&pos, sizeof(pos));
1153
- read_to(&n_seq_id, sizeof(n_seq_id));
1154
-
1155
- if (n_seq_id != 0) {
1156
- LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
1157
- return false;
1158
- }
1159
-
1160
- batch.pos[i] = pos;
1161
- }
1162
- batch.n_seq_id[0] = 1;
1163
- batch.seq_id[0] = &dest_seq_id;
1164
- if (!llama_kv_cache_find_slot(kv_self, batch)) {
1165
- LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
1166
- return false;
1167
- }
1168
-
1169
- // DEBUG CHECK: kv_self.head should be our first cell, kv_self.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
1170
- // Assume that this is one contiguous block of cells
1171
- LM_GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
1172
- LM_GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
1173
- LM_GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
1174
- LM_GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
1175
- LM_GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
1176
- } else {
1177
- // whole KV cache restore
1178
-
1179
- if (cell_count > kv_self.size) {
1180
- LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
1181
- return false;
1182
- }
1183
-
1184
- llama_kv_cache_clear(kv_self);
1185
-
1186
- for (uint32_t i = 0; i < cell_count; ++i) {
1187
- llama_kv_cell & cell = kv_self.cells[i];
1188
-
1189
- llama_pos pos;
1190
- uint32_t n_seq_id;
1191
-
1192
- read_to(&pos, sizeof(pos));
1193
- read_to(&n_seq_id, sizeof(n_seq_id));
1194
-
1195
- cell.pos = pos;
1196
-
1197
- for (uint32_t j = 0; j < n_seq_id; ++j) {
1198
- llama_seq_id seq_id;
1199
- read_to(&seq_id, sizeof(seq_id));
1200
-
1201
- if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
1202
- LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
1203
- return false;
1204
- }
1205
-
1206
- cell.seq_id.insert(seq_id);
1207
-
1208
- if (kv_self.recurrent) {
1209
- int32_t & tail = kv_self.cells[seq_id].tail;
1210
- if (tail != -1) {
1211
- LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
1212
- return false;
1213
- }
1214
- tail = i;
1215
- }
1216
- }
1217
- }
1218
-
1219
- kv_self.head = 0;
1220
- kv_self.used = cell_count;
1221
- }
1222
-
1223
- if (kv_self.recurrent) {
1224
- for (uint32_t i = 0; i < cell_count; ++i) {
1225
- uint32_t cell_id = kv_self.head + i;
1226
- // make sure the recurrent states will keep their restored state
1227
- kv_self.cells[cell_id].src = cell_id;
1228
- }
1229
- }
1230
-
1231
- return true;
1232
- }
1233
-
1234
- bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
1235
- const struct llama_hparams & hparams = ctx->model.hparams;
1236
- struct llama_kv_cache & kv_self = ctx->kv_self;
1237
- uint32_t v_trans;
1238
- uint32_t n_layer;
1239
- read_to(&v_trans, sizeof(v_trans));
1240
- read_to(&n_layer, sizeof(n_layer));
1241
-
1242
- if (n_layer != hparams.n_layer) {
1243
- LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
1244
- return false;
1245
- }
1246
- if (cell_count > kv_self.size) {
1247
- LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
1248
- return false;
1249
- }
1250
- if (kv_self.v_trans != (bool) v_trans) {
1251
- LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
1252
- return false;
1253
- }
1254
-
1255
- // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
1256
- for (uint32_t il = 0; il < n_layer; ++il) {
1257
- const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
1258
-
1259
- // Read type of key
1260
- int32_t k_type_i_ref;
1261
- read_to(&k_type_i_ref, sizeof(k_type_i_ref));
1262
- const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
1263
- if (k_type_i != k_type_i_ref) {
1264
- LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
1265
- return false;
1266
- }
1267
-
1268
- // Read row size of key
1269
- uint64_t k_size_row_ref;
1270
- read_to(&k_size_row_ref, sizeof(k_size_row_ref));
1271
- const size_t k_size_row = lm_ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
1272
- if (k_size_row != k_size_row_ref) {
1273
- LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
1274
- return false;
1275
- }
1276
-
1277
- if (cell_count) {
1278
- // Read and set the keys for the whole cell range
1279
- lm_ggml_backend_tensor_set(kv_self.k_l[il], read(cell_count * k_size_row), kv_self.head * k_size_row, cell_count * k_size_row);
1280
- }
1281
- }
1282
-
1283
- if (!kv_self.v_trans) {
1284
- for (uint32_t il = 0; il < n_layer; ++il) {
1285
- const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
1286
-
1287
- // Read type of value
1288
- int32_t v_type_i_ref;
1289
- read_to(&v_type_i_ref, sizeof(v_type_i_ref));
1290
- const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
1291
- if (v_type_i != v_type_i_ref) {
1292
- LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
1293
- return false;
1294
- }
1295
-
1296
- // Read row size of value
1297
- uint64_t v_size_row_ref;
1298
- read_to(&v_size_row_ref, sizeof(v_size_row_ref));
1299
- const size_t v_size_row = lm_ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
1300
- if (v_size_row != v_size_row_ref) {
1301
- LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
1302
- return false;
1303
- }
1304
-
1305
- if (cell_count) {
1306
- // Read and set the values for the whole cell range
1307
- lm_ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_row), kv_self.head * v_size_row, cell_count * v_size_row);
1308
- }
1309
- }
1310
- } else {
1311
- // For each layer, read the values for each cell (transposed)
1312
- for (uint32_t il = 0; il < n_layer; ++il) {
1313
- const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
1314
-
1315
- // Read type of value
1316
- int32_t v_type_i_ref;
1317
- read_to(&v_type_i_ref, sizeof(v_type_i_ref));
1318
- const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
1319
- if (v_type_i != v_type_i_ref) {
1320
- LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
1321
- return false;
1322
- }
1323
-
1324
- // Read element size of value
1325
- uint32_t v_size_el_ref;
1326
- read_to(&v_size_el_ref, sizeof(v_size_el_ref));
1327
- const size_t v_size_el = lm_ggml_type_size(kv_self.v_l[il]->type);
1328
- if (v_size_el != v_size_el_ref) {
1329
- LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
1330
- return false;
1331
- }
1332
-
1333
- // Read GQA embedding size
1334
- uint32_t n_embd_v_gqa_ref;
1335
- read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
1336
- if (n_embd_v_gqa != n_embd_v_gqa_ref) {
1337
- LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
1338
- return false;
1339
- }
1340
-
1341
- if (cell_count) {
1342
- // For each row in the transposed matrix, read the values for the whole cell range
1343
- for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
1344
- const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
1345
- lm_ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
1346
- }
1347
- }
1348
- }
1349
- }
1350
- return true;
1351
- }
1352
-
1353
- void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
1354
- uint32_t cell_count;
1355
- read_to(&cell_count, sizeof(cell_count));
1356
-
1357
- bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
1358
-
1359
- if (!res) {
1360
- if (seq_id == -1) {
1361
- llama_kv_cache_clear(ctx);
1362
- } else {
1363
- llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
1364
- }
1365
- throw std::runtime_error("failed to restore kv cache");
1366
- }
1367
- }
1368
- };
1369
-
1370
- struct llama_data_write_dummy : llama_data_write {
1371
- size_t size_written = 0;
1372
-
1373
- llama_data_write_dummy() {}
1374
-
1375
- void write(const void * /* src */, size_t size) override {
1376
- size_written += size;
1377
- }
1378
-
1379
- void write_tensor_data(const struct lm_ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
1380
- size_written += size;
1381
- }
1382
-
1383
- size_t get_size_written() override {
1384
- return size_written;
1385
- }
1386
- };
1387
-
1388
- struct llama_data_write_buffer : llama_data_write {
1389
- uint8_t * ptr;
1390
- size_t buf_size = 0;
1391
- size_t size_written = 0;
1392
-
1393
- llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
1394
-
1395
- void write(const void * src, size_t size) override {
1396
- if (size > buf_size) {
1397
- throw std::runtime_error("unexpectedly reached end of buffer");
1398
- }
1399
- memcpy(ptr, src, size);
1400
- ptr += size;
1401
- size_written += size;
1402
- buf_size -= size;
1403
- }
1404
-
1405
- void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) override {
1406
- if (size > buf_size) {
1407
- throw std::runtime_error("unexpectedly reached end of buffer");
1408
- }
1409
- lm_ggml_backend_tensor_get(tensor, ptr, offset, size);
1410
- ptr += size;
1411
- size_written += size;
1412
- buf_size -= size;
1413
- }
1414
-
1415
- size_t get_size_written() override {
1416
- return size_written;
1417
- }
1418
- };
1419
-
1420
- struct llama_data_read_buffer : llama_data_read {
1421
- const uint8_t * ptr;
1422
- size_t buf_size = 0;
1423
- size_t size_read = 0;
1424
-
1425
- llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
1426
-
1427
- const uint8_t * read(size_t size) override {
1428
- const uint8_t * base_ptr = ptr;
1429
- if (size > buf_size) {
1430
- throw std::runtime_error("unexpectedly reached end of buffer");
1431
- }
1432
- ptr += size;
1433
- size_read += size;
1434
- buf_size -= size;
1435
- return base_ptr;
1436
- }
1437
-
1438
- void read_to(void * dst, size_t size) override {
1439
- memcpy(dst, read(size), size);
1440
- }
1441
-
1442
- size_t get_size_read() override {
1443
- return size_read;
1444
- }
1445
- };
1446
-
1447
- struct llama_data_write_file : llama_data_write {
1448
- llama_file * file;
1449
- size_t size_written = 0;
1450
- std::vector<uint8_t> temp_buffer;
1451
-
1452
- llama_data_write_file(llama_file * f) : file(f) {}
1453
-
1454
- void write(const void * src, size_t size) override {
1455
- file->write_raw(src, size);
1456
- size_written += size;
1457
- }
1458
-
1459
- void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) override {
1460
- temp_buffer.resize(size);
1461
- lm_ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
1462
- write(temp_buffer.data(), temp_buffer.size());
1463
- }
1464
-
1465
- size_t get_size_written() override {
1466
- return size_written;
1467
- }
1468
- };
1469
-
1470
- struct llama_data_read_file : llama_data_read {
1471
- llama_file * file;
1472
- size_t size_read = 0;
1473
- std::vector<uint8_t> temp_buffer;
1474
-
1475
- llama_data_read_file(llama_file * f) : file(f) {}
1476
-
1477
- void read_to(void * dst, size_t size) override {
1478
- file->read_raw(dst, size);
1479
- size_read += size;
1480
- }
1481
-
1482
- const uint8_t * read(size_t size) override {
1483
- temp_buffer.resize(size);
1484
- read_to(temp_buffer.data(), size);
1485
- return temp_buffer.data();
1486
- }
1487
-
1488
- size_t get_size_read() override {
1489
- return size_read;
1490
- }
1491
- };
1492
-
1493
- /** copy state data into either a buffer or file depending on the passed in context
1494
- *
1495
- * file context:
1496
- * llama_file file("/path", "wb");
1497
- * llama_data_write_file data_ctx(&file);
1498
- * llama_state_get_data_internal(ctx, data_ctx);
1499
- *
1500
- * buffer context:
1501
- * std::vector<uint8_t> buf(max_size, 0);
1502
- * llama_data_write_buffer data_ctx(buf.data(), max_size);
1503
- * llama_state_get_data_internal(ctx, data_ctx);
1504
- *
1505
- */
1506
- static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
1507
- llama_synchronize(ctx);
1508
-
1509
- data_ctx.write_model_info(ctx);
1510
-
1511
- // copy outputs
1512
- data_ctx.write_output_ids(ctx);
1513
- data_ctx.write_logits(ctx);
1514
- data_ctx.write_embeddings(ctx);
1515
-
1516
- data_ctx.write_kv_cache(ctx);
1517
-
1518
- return data_ctx.get_size_written();
1519
- }
1520
-
1521
- size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
1522
- llama_data_write_buffer data_ctx(dst, size);
1523
- try {
1524
- return llama_state_get_data_internal(ctx, data_ctx);
1525
- } catch (const std::exception & err) {
1526
- LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
1527
- return 0;
1528
- }
1529
- }
1530
-
1531
- // Returns the *actual* size of the state.
1532
- // Intended to be used when saving to state to a buffer.
1533
- size_t llama_state_get_size(struct llama_context * ctx) {
1534
- llama_data_write_dummy data_ctx;
1535
- try {
1536
- return llama_state_get_data_internal(ctx, data_ctx);
1537
- } catch (const std::exception & err) {
1538
- LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
1539
- return 0;
1540
- }
1541
- }
1542
-
1543
- static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
1544
- llama_synchronize(ctx);
1545
-
1546
- data_ctx.read_model_info(ctx);
1547
-
1548
- // set outputs
1549
- data_ctx.read_output_ids(ctx);
1550
- data_ctx.read_logits(ctx);
1551
- data_ctx.read_embeddings(ctx);
1552
-
1553
- data_ctx.read_kv_cache(ctx);
1554
-
1555
- return data_ctx.get_size_read();
1556
- }
1557
-
1558
- // Sets the state reading from the specified source address
1559
- size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
1560
- llama_data_read_buffer data_ctx(src, size);
1561
- try {
1562
- return llama_state_set_data_internal(ctx, data_ctx);
1563
- } catch (const std::exception & err) {
1564
- LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
1565
- return 0;
1566
- }
1567
- }
1568
-
1569
- static bool llama_state_load_file_internal(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1570
- llama_file file(path_session, "rb");
1571
-
1572
- // sanity checks
1573
- {
1574
- const uint32_t magic = file.read_u32();
1575
- const uint32_t version = file.read_u32();
1576
-
1577
- if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
1578
- LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
1579
- return false;
1580
- }
1581
- }
1582
-
1583
- // load the prompt
1584
- {
1585
- const uint32_t n_token_count = file.read_u32();
1586
-
1587
- if (n_token_count > n_token_capacity) {
1588
- LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
1589
- return false;
1590
- }
1591
-
1592
- file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
1593
- *n_token_count_out = n_token_count;
1594
- }
1595
-
1596
- // restore the context state
1597
- {
1598
- const size_t n_state_size_cur = file.size() - file.tell();
1599
-
1600
- llama_data_read_file data_ctx(&file);
1601
- const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
1602
-
1603
- if (n_read != n_state_size_cur) {
1604
- LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
1605
- return false;
1606
- }
1607
- }
1608
- return true;
1609
- }
1610
-
1611
- bool llama_state_load_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1612
- try {
1613
- return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
1614
- } catch (const std::exception & err) {
1615
- LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
1616
- return false;
1617
- }
1618
- }
1619
-
1620
- static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
1621
- llama_file file(path_session, "wb");
1622
-
1623
- file.write_u32(LLAMA_SESSION_MAGIC);
1624
- file.write_u32(LLAMA_SESSION_VERSION);
1625
-
1626
- // save the prompt
1627
- file.write_u32((uint32_t) n_token_count);
1628
- file.write_raw(tokens, sizeof(llama_token) * n_token_count);
1629
-
1630
- // save the context state using stream saving
1631
- llama_data_write_file data_ctx(&file);
1632
- llama_state_get_data_internal(ctx, data_ctx);
1633
-
1634
- return true;
1635
- }
1636
-
1637
- bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
1638
- try {
1639
- return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
1640
- } catch (const std::exception & err) {
1641
- LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
1642
- return false;
1643
- }
1644
- }
1645
-
1646
- static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
1647
- llama_synchronize(ctx);
1648
-
1649
- data_ctx.write_kv_cache(ctx, seq_id);
1650
-
1651
- return data_ctx.get_size_written();
1652
- }
1653
-
1654
- size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
1655
- llama_data_write_dummy data_ctx;
1656
- return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1657
- }
1658
-
1659
- size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
1660
- llama_data_write_buffer data_ctx(dst, size);
1661
- try {
1662
- return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1663
- } catch (const std::exception & err) {
1664
- LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
1665
- return 0;
1666
- }
1667
- }
1668
-
1669
- static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
1670
- llama_synchronize(ctx);
1671
-
1672
- data_ctx.read_kv_cache(ctx, dest_seq_id);
1673
-
1674
- return data_ctx.get_size_read();
1675
- }
1676
-
1677
- size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
1678
- llama_data_read_buffer data_ctx(src, size);
1679
- try {
1680
- return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
1681
- } catch (const std::exception & err) {
1682
- LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
1683
- return 0;
1684
- }
1685
- }
1686
-
1687
- static size_t llama_state_seq_save_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
1688
- llama_file file(filepath, "wb");
1689
-
1690
- file.write_u32(LLAMA_STATE_SEQ_MAGIC);
1691
- file.write_u32(LLAMA_STATE_SEQ_VERSION);
1692
-
1693
- // save the prompt
1694
- file.write_u32((uint32_t) n_token_count);
1695
- file.write_raw(tokens, sizeof(llama_token) * n_token_count);
1696
-
1697
- // save the context state using stream saving
1698
- llama_data_write_file data_ctx(&file);
1699
- llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1700
-
1701
- const size_t res = file.tell();
1702
- LM_GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
1703
- return res;
1704
- }
1705
-
1706
- static size_t llama_state_seq_load_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1707
- llama_file file(filepath, "rb");
1708
-
1709
- // version checks
1710
- {
1711
- const uint32_t magic = file.read_u32();
1712
- const uint32_t version = file.read_u32();
1713
-
1714
- if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
1715
- LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
1716
- return 0;
1717
- }
1718
- }
1719
-
1720
- // load the prompt
1721
- {
1722
- const uint32_t n_token_count = file.read_u32();
1723
-
1724
- if (n_token_count > n_token_capacity) {
1725
- LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
1726
- return 0;
1727
- }
1728
-
1729
- file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
1730
- *n_token_count_out = n_token_count;
1731
- }
1732
-
1733
- // restore the context state
1734
- {
1735
- const size_t state_size = file.size() - file.tell();
1736
- llama_data_read_file data_ctx(&file);
1737
- const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
1738
- if (!nread) {
1739
- LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
1740
- return 0;
1741
- }
1742
- LM_GGML_ASSERT(nread <= state_size);
1743
- LM_GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
1744
- }
1745
-
1746
- return file.tell();
1747
- }
1748
-
1749
- size_t llama_state_seq_save_file(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
1750
- try {
1751
- return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
1752
- } catch (const std::exception & err) {
1753
- LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
1754
- return 0;
1755
- }
1756
- }
1757
-
1758
- size_t llama_state_seq_load_file(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1759
- try {
1760
- return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
1761
- } catch (const std::exception & err) {
1762
- LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
1763
- return 0;
1764
- }
1765
- }
1766
-
1767
- const std::vector<std::pair<std::string, struct lm_ggml_tensor *>> & llama_internal_get_tensor_map(
1768
- struct llama_context * ctx
1769
- ) {
1770
- return ctx->model.tensors_by_name;
1771
- }
1
+ #include "llama-context.h"
2
+
3
+ #include "llama-impl.h"
4
+ #include "llama-mmap.h"
5
+
6
+ #include <cassert>
7
+ #include <cmath>
8
+ #include <cstring>
9
+ #include <stdexcept>
10
+
11
+ void llama_set_k_shift(struct llama_context & lctx) {
12
+ const int64_t kv_size = lctx.kv_self.size;
13
+
14
+ assert(lm_ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
15
+
16
+ int32_t * data = (int32_t *) lctx.inp_K_shift->data;
17
+
18
+ for (int i = 0; i < kv_size; ++i) {
19
+ data[i] = lctx.kv_self.cells[i].delta;
20
+ }
21
+ }
22
+
23
+ void llama_set_s_copy(struct llama_context & lctx) {
24
+ const int64_t kv_size = lctx.kv_self.size;
25
+
26
+ assert(lm_ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
27
+
28
+ int32_t * data = (int32_t *) lctx.inp_s_copy->data;
29
+
30
+ for (int i = 0; i < kv_size; ++i) {
31
+ data[i] = lctx.kv_self.cells[i].src;
32
+ }
33
+ }
34
+
35
+ // llama input
36
+
37
+ static int32_t llama_relative_position_bucket(llama_pos x, llama_pos y, uint64_t n_buckets, bool bidirectional) {
38
+ // TODO move to hparams if a T5 variant appears that uses a different value
39
+ const int64_t max_distance = 128;
40
+
41
+ if (bidirectional) {
42
+ n_buckets >>= 1;
43
+ }
44
+
45
+ const int64_t max_exact = n_buckets >> 1;
46
+
47
+ int32_t relative_position = x - y;
48
+ int32_t relative_bucket = 0;
49
+ if (bidirectional) {
50
+ relative_bucket += (relative_position > 0) * n_buckets;
51
+ relative_position = abs(relative_position);
52
+ } else {
53
+ relative_position = -std::min<int32_t>(relative_position, 0);
54
+ }
55
+ int32_t relative_position_if_large = floorf(max_exact + logf(1.0 * relative_position / max_exact) * (n_buckets - max_exact) / log(1.0 * max_distance / max_exact));
56
+ relative_position_if_large = std::min<int32_t>(relative_position_if_large, n_buckets - 1);
57
+ relative_bucket += (relative_position < max_exact ? relative_position : relative_position_if_large);
58
+ return relative_bucket;
59
+ }
60
+
61
+ void llama_set_inputs(llama_context & lctx, const llama_ubatch & ubatch) {
62
+ //
63
+ // set input data
64
+ //
65
+
66
+ const auto & hparams = lctx.model.hparams;
67
+ const auto & cparams = lctx.cparams;
68
+ const auto & kv_self = lctx.kv_self;
69
+
70
+ if (ubatch.token) {
71
+ const int64_t n_tokens = ubatch.n_tokens;
72
+
73
+ lm_ggml_backend_tensor_set(lctx.inp_tokens, ubatch.token, 0, n_tokens*lm_ggml_element_size(lctx.inp_tokens));
74
+ }
75
+
76
+ if (ubatch.embd) {
77
+ const int64_t n_embd = hparams.n_embd;
78
+ const int64_t n_tokens = ubatch.n_tokens;
79
+
80
+ lm_ggml_backend_tensor_set(lctx.inp_embd, ubatch.embd, 0, n_tokens*n_embd*lm_ggml_element_size(lctx.inp_embd));
81
+ }
82
+
83
+ if (ubatch.pos && lctx.inp_pos) {
84
+ const int64_t n_tokens = ubatch.n_tokens;
85
+ auto n_pos = lctx.n_pos_per_token;
86
+ lm_ggml_backend_tensor_set(lctx.inp_pos, ubatch.pos, 0, n_tokens*n_pos*lm_ggml_element_size(lctx.inp_pos));
87
+ }
88
+
89
+ if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
90
+ //LM_GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
91
+
92
+ if (!lctx.inp_out_ids) {
93
+ LLAMA_LOG_WARN("%s: 'lctx.inp_out_ids' is not created\n", __func__);
94
+ } else {
95
+ const int64_t n_tokens = ubatch.n_tokens;
96
+
97
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
98
+ int32_t * data = (int32_t *) lctx.inp_out_ids->data;
99
+
100
+ if (lctx.n_outputs == n_tokens) {
101
+ for (int i = 0; i < n_tokens; ++i) {
102
+ data[i] = i;
103
+ }
104
+ } else if (ubatch.output) {
105
+ int32_t n_outputs = 0;
106
+ for (int i = 0; i < n_tokens; ++i) {
107
+ if (ubatch.output[i]) {
108
+ data[n_outputs++] = i;
109
+ }
110
+ }
111
+ // the graph needs to have been passed the correct number of outputs
112
+ LM_GGML_ASSERT(lctx.n_outputs == n_outputs);
113
+ } else if (lctx.n_outputs == 1) {
114
+ // only keep last output
115
+ data[0] = n_tokens - 1;
116
+ } else {
117
+ LM_GGML_ASSERT(lctx.n_outputs == 0);
118
+ }
119
+ }
120
+ }
121
+
122
+ LM_GGML_ASSERT(
123
+ // (!a || b) is a logical implication (a -> b)
124
+ // !hparams.causal_attn -> !cparams.causal_attn
125
+ (hparams.causal_attn || !cparams.causal_attn) &&
126
+ "causal attention is not supported by this model"
127
+ );
128
+
129
+ if (lctx.inp_KQ_mask || lctx.inp_KQ_mask_swa) {
130
+ // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
131
+ if (cparams.causal_attn && !lctx.is_encoding) {
132
+ const int64_t n_kv = kv_self.n;
133
+ const int64_t n_tokens = ubatch.n_tokens;
134
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
135
+ const int64_t n_seqs = ubatch.n_seqs;
136
+
137
+
138
+ float * data = nullptr;
139
+ float * data_swa = nullptr;
140
+
141
+ if (lctx.inp_KQ_mask) {
142
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
143
+ data = (float *) lctx.inp_KQ_mask->data;
144
+ }
145
+
146
+ if (lctx.inp_KQ_mask_swa) {
147
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask_swa->buffer));
148
+ data_swa = (float *) lctx.inp_KQ_mask_swa->data;
149
+ }
150
+
151
+ // For causal attention, use only the previous KV cells
152
+ // of the correct sequence for each token of the ubatch.
153
+ // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
154
+ for (int h = 0; h < 1; ++h) {
155
+ for (int s = 0; s < n_seqs; ++s) {
156
+ const llama_seq_id seq_id = ubatch.seq_id[s][0];
157
+
158
+ for (int j = 0; j < n_seq_tokens; ++j) {
159
+ const llama_pos pos = ubatch.pos[s*n_seq_tokens + j];
160
+
161
+ for (int i = 0; i < n_kv; ++i) {
162
+ float f;
163
+ if (!kv_self.cells[i].has_seq_id(seq_id) || kv_self.cells[i].pos > pos) {
164
+ f = -INFINITY;
165
+ } else {
166
+ if (hparams.use_alibi) {
167
+ f = -std::abs(kv_self.cells[i].pos - pos);
168
+ } else {
169
+ f = 0.0f;
170
+ }
171
+ }
172
+
173
+ if (data) {
174
+ data[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
175
+ }
176
+
177
+ // may need to cut off old tokens for sliding window
178
+ if (data_swa) {
179
+ if (pos - kv_self.cells[i].pos >= (int32_t)hparams.n_swa) {
180
+ f = -INFINITY;
181
+ }
182
+ data_swa[h*(n_kv*n_tokens) + s*(n_kv*n_seq_tokens) + j*n_kv + i] = f;
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ if (data) {
189
+ for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
190
+ for (int j = 0; j < n_kv; ++j) {
191
+ data[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
192
+ }
193
+ }
194
+ }
195
+
196
+ if (data_swa) {
197
+ for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
198
+ for (int j = 0; j < n_kv; ++j) {
199
+ data_swa[h*(n_kv*n_tokens) + i*n_kv + j] = -INFINITY;
200
+ }
201
+ }
202
+ }
203
+ }
204
+ } else {
205
+ const int64_t n_tokens = ubatch.n_tokens;
206
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
207
+ const int64_t n_seqs = ubatch.n_seqs;
208
+ // when using kv cache, the mask needs to match the kv cache size
209
+ const int64_t n_stride = hparams.causal_attn && !lctx.is_encoding ? kv_self.n : n_tokens;
210
+
211
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
212
+
213
+ float * data = (float *) lctx.inp_KQ_mask->data;
214
+
215
+ for (int h = 0; h < 1; ++h) {
216
+ for (int s1 = 0; s1 < n_seqs; ++s1) {
217
+ const llama_seq_id seq_id = ubatch.seq_id[s1][0];
218
+
219
+ for (int j = 0; j < n_seq_tokens; ++j) {
220
+ const int32_t tj = s1*n_seq_tokens + j;
221
+
222
+ for (int s0 = 0; s0 < n_seqs; ++s0) {
223
+ for (int i = 0; i < n_seq_tokens; ++i) {
224
+ const int32_t ti = s0*n_seq_tokens + i;
225
+ float f = -INFINITY;
226
+
227
+ for (int s = 0; s < ubatch.n_seq_id[s0]; ++s) {
228
+ if (ubatch.seq_id[s0][s] == seq_id) {
229
+ if (hparams.use_alibi) {
230
+ f = -std::abs(ubatch.pos[ti] - ubatch.pos[tj]);
231
+ } else {
232
+ f = 0.0f;
233
+ }
234
+ break;
235
+ }
236
+ }
237
+
238
+ data[h*(n_tokens*n_tokens) + tj*n_stride + ti] = f;
239
+ }
240
+ }
241
+
242
+ for (int i = n_tokens; i < n_stride; ++i) {
243
+ data[h*(n_tokens*n_tokens) + tj*n_stride + i] = -INFINITY;
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ }
250
+
251
+ if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
252
+ const int64_t n_tokens = ubatch.n_tokens;
253
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
254
+ const int64_t n_seqs = ubatch.n_seqs;
255
+
256
+ LM_GGML_ASSERT(lctx.inp_mean);
257
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
258
+
259
+ float * data = (float *) lctx.inp_mean->data;
260
+ memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * lm_ggml_element_size(lctx.inp_mean));
261
+
262
+ std::vector<uint64_t> sum(n_tokens, 0);
263
+
264
+ for (int s = 0; s < n_seqs; ++s) {
265
+ const llama_seq_id seq_id = ubatch.seq_id[s][0];
266
+
267
+ // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
268
+ LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
269
+
270
+ sum[seq_id] += ubatch.n_seq_tokens;
271
+ }
272
+
273
+ std::vector<float> div(n_tokens, 0.0f);
274
+ for (int i = 0; i < n_tokens; ++i) {
275
+ const uint64_t s = sum[i];
276
+ if (s > 0) {
277
+ div[i] = 1.0f/float(s);
278
+ }
279
+ }
280
+
281
+ for (int s = 0; s < n_seqs; ++s) {
282
+ const llama_seq_id seq_id = ubatch.seq_id[s][0];
283
+
284
+ for (int i = 0; i < n_seq_tokens; ++i) {
285
+ data[seq_id*n_tokens + s*n_seq_tokens + i] = div[seq_id];
286
+ }
287
+ }
288
+ }
289
+
290
+ if (cparams.embeddings && (
291
+ cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
292
+ cparams.pooling_type == LLAMA_POOLING_TYPE_RANK)) {
293
+ const int64_t n_tokens = ubatch.n_tokens;
294
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
295
+ const int64_t n_seqs = ubatch.n_seqs;
296
+
297
+ LM_GGML_ASSERT(lctx.inp_cls);
298
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
299
+
300
+ uint32_t * data = (uint32_t *) lctx.inp_cls->data;
301
+ memset(lctx.inp_cls->data, 0, n_tokens * lm_ggml_element_size(lctx.inp_cls));
302
+
303
+ for (int s = 0; s < n_seqs; ++s) {
304
+ const llama_seq_id seq_id = ubatch.seq_id[s][0];
305
+
306
+ // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
307
+ LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS or RANK");
308
+
309
+ for (int i = 0; i < n_seq_tokens; ++i) {
310
+ const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
311
+
312
+ if (pos == 0) {
313
+ data[seq_id] = s*n_seq_tokens + i;
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ if (cparams.embeddings && cparams.pooling_type == LLAMA_POOLING_TYPE_LAST) {
320
+ const int64_t n_tokens = ubatch.n_tokens;
321
+ const int64_t n_seq_tokens = ubatch.n_seq_tokens;
322
+ const int64_t n_seqs = ubatch.n_seqs;
323
+
324
+ LM_GGML_ASSERT(lctx.inp_cls);
325
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
326
+
327
+ uint32_t * data = (uint32_t *) lctx.inp_cls->data;
328
+ memset(lctx.inp_cls->data, 0, n_tokens * lm_ggml_element_size(lctx.inp_cls));
329
+
330
+ std::vector<int> last_pos(n_tokens, -1);
331
+ std::vector<int> last_row(n_tokens, -1);
332
+
333
+ for (int s = 0; s < n_seqs; ++s) {
334
+ const llama_seq_id seq_id = ubatch.seq_id[s][0];
335
+
336
+ // TODO: adapt limits to n_seqs when ubatch.equal_seqs is true
337
+ LM_GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == LAST");
338
+
339
+ for (int i = 0; i < n_seq_tokens; ++i) {
340
+ const llama_pos pos = ubatch.pos[s*n_seq_tokens + i];
341
+
342
+ if (pos >= last_pos[seq_id]) {
343
+ last_pos[seq_id] = pos;
344
+ last_row[seq_id] = s*n_seq_tokens + i;
345
+ }
346
+ }
347
+ }
348
+
349
+ for (int i = 0; i < n_tokens; ++i) {
350
+ if (last_row[i] >= 0) {
351
+ data[i] = last_row[i];
352
+ }
353
+ }
354
+ }
355
+
356
+ if (kv_self.recurrent) {
357
+ const int64_t n_kv = kv_self.n;
358
+
359
+ if (lctx.inp_s_mask) {
360
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
361
+ float * data = (float *) lctx.inp_s_mask->data;
362
+
363
+ // clear unused states
364
+ for (int i = 0; i < n_kv; ++i) {
365
+ const uint32_t cell_id = i + kv_self.head;
366
+ llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
367
+
368
+ data[i] = (float) (kv_cell.src >= 0);
369
+
370
+ // only clear once
371
+ if (kv_cell.src < 0) {
372
+ kv_cell.src = cell_id;
373
+ }
374
+ }
375
+ }
376
+
377
+ if (lctx.inp_s_copy) {
378
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
379
+ int32_t * data = (int32_t *) lctx.inp_s_copy->data;
380
+
381
+ // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n
382
+ for (uint32_t i = 0; i < n_kv; ++i) {
383
+ const uint32_t cell_id = i + kv_self.head;
384
+ llama_kv_cell & kv_cell = lctx.kv_self.cells[cell_id];
385
+
386
+ // prevent out-of-bound sources
387
+ if (kv_cell.src < 0 || (uint32_t) kv_cell.src >= kv_self.size) {
388
+ kv_cell.src = cell_id;
389
+ }
390
+
391
+ data[i] = kv_cell.src;
392
+
393
+ // ensure copy only happens once
394
+ if (kv_cell.src != (int32_t) cell_id) {
395
+ kv_cell.src = cell_id;
396
+ }
397
+ }
398
+ }
399
+ }
400
+
401
+ if (lctx.inp_pos_bucket) {
402
+ const int64_t n_tokens = ubatch.n_tokens;
403
+
404
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_pos_bucket->buffer));
405
+ LM_GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
406
+
407
+ int32_t * data = (int32_t *) lctx.inp_pos_bucket->data;
408
+
409
+ if (!lctx.is_encoding) {
410
+ const int64_t n_kv = kv_self.n;
411
+ for (int h = 0; h < 1; ++h) {
412
+ for (int j = 0; j < n_tokens; ++j) {
413
+ for (int i = 0; i < n_kv; ++i) {
414
+ data[h*(n_kv*n_tokens) + j*n_kv + i] = llama_relative_position_bucket(lctx.kv_self.cells[i].pos, ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
415
+ }
416
+ }
417
+ }
418
+ } else {
419
+ for (int h = 0; h < 1; ++h) {
420
+ for (int j = 0; j < n_tokens; ++j) {
421
+ for (int i = 0; i < n_tokens; ++i) {
422
+ data[h*(n_tokens*n_tokens) + j*n_tokens + i] = llama_relative_position_bucket(ubatch.pos[i], ubatch.pos[j], hparams.n_rel_attn_bkts, lctx.is_encoding);
423
+ }
424
+ }
425
+ }
426
+ }
427
+ }
428
+
429
+ if (!lctx.is_encoding && lctx.inp_embd_enc) {
430
+ assert(lctx.inp_embd_enc->type == LM_GGML_TYPE_F32);
431
+ assert((size_t) lm_ggml_nelements(lctx.inp_embd_enc) == lctx.embd_enc.size());
432
+
433
+ lm_ggml_backend_tensor_set(lctx.inp_embd_enc, lctx.embd_enc.data(), 0, lm_ggml_nbytes(lctx.inp_embd_enc));
434
+ }
435
+
436
+ if (!lctx.is_encoding && lctx.inp_KQ_mask_cross) {
437
+ const int64_t n_output_enc = lctx.embd_enc.size() / hparams.n_embd;
438
+ const int64_t n_tokens = ubatch.n_tokens;
439
+
440
+ LM_GGML_ASSERT(lm_ggml_backend_buffer_is_host(lctx.inp_KQ_mask_cross->buffer));
441
+ LM_GGML_ASSERT(!ubatch.equal_seqs); // TODO: use ubatch.n_seqs instead of failing
442
+
443
+ float * data = (float *) lctx.inp_KQ_mask_cross->data;
444
+
445
+ for (int h = 0; h < 1; ++h) {
446
+ for (int j = 0; j < n_tokens; ++j) {
447
+ for (int i = 0; i < n_output_enc; ++i) {
448
+ float f = -INFINITY;
449
+ for (int s = 0; s < ubatch.n_seq_id[j]; ++s) {
450
+ const llama_seq_id seq_id = ubatch.seq_id[j][s];
451
+ if (lctx.seq_ids_enc[i].find(seq_id) != lctx.seq_ids_enc[i].end()) {
452
+ f = 0.0f;
453
+ }
454
+ }
455
+ data[h*(n_output_enc*n_tokens) + j*n_output_enc + i] = f;
456
+ }
457
+ }
458
+
459
+ for (int i = n_tokens; i < LM_GGML_PAD(n_tokens, LM_GGML_KQ_MASK_PAD); ++i) {
460
+ for (int j = 0; j < n_output_enc; ++j) {
461
+ data[h*(n_output_enc*n_tokens) + i*n_output_enc + j] = -INFINITY;
462
+ }
463
+ }
464
+ }
465
+ }
466
+ }
467
+
468
+ // llama output
469
+
470
+ size_t llama_output_reserve(struct llama_context & lctx, size_t n_outputs) {
471
+ const auto & cparams = lctx.cparams;
472
+ const auto & hparams = lctx.model.hparams;
473
+ const auto & vocab = lctx.model.vocab;
474
+
475
+ const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
476
+
477
+ const auto n_batch = cparams.n_batch;
478
+ const auto n_vocab = vocab.n_tokens();
479
+ const auto n_embd = hparams.n_embd;
480
+
481
+ // TODO: use a per-batch flag for logits presence instead
482
+ const bool has_logits = !cparams.embeddings;
483
+ const bool has_embd = cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
484
+
485
+ const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
486
+ const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
487
+
488
+ if (lctx.output_ids.empty()) {
489
+ // init, never resized afterwards
490
+ lctx.output_ids.resize(n_batch);
491
+ }
492
+
493
+ const size_t prev_size = lctx.buf_output ? lm_ggml_backend_buffer_get_size(lctx.buf_output.get()) : 0;
494
+ const size_t new_size = (logits_size + embd_size) * sizeof(float);
495
+
496
+ // alloc only when more than the current capacity is required
497
+ // TODO: also consider shrinking the buffer
498
+ if (!lctx.buf_output || prev_size < new_size) {
499
+ if (lctx.buf_output) {
500
+ #ifndef NDEBUG
501
+ // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
502
+ LLAMA_LOG_INFO("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
503
+ #endif
504
+ lctx.buf_output = nullptr;
505
+ lctx.logits = nullptr;
506
+ lctx.embd = nullptr;
507
+ }
508
+
509
+ auto * buft = lm_ggml_backend_cpu_buffer_type();
510
+ // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
511
+ auto * output_dev = lctx.model.dev_output();
512
+ auto * output_dev_host_buft = output_dev ? lm_ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
513
+ if (output_dev_host_buft) {
514
+ buft = output_dev_host_buft;
515
+ }
516
+ lctx.buf_output.reset(lm_ggml_backend_buft_alloc_buffer(buft, new_size));
517
+ if (lctx.buf_output == nullptr) {
518
+ LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
519
+ return 0;
520
+ }
521
+ }
522
+
523
+ float * output_base = (float *) lm_ggml_backend_buffer_get_base(lctx.buf_output.get());
524
+
525
+ lctx.logits = has_logits ? output_base : nullptr;
526
+ lctx.embd = has_embd ? output_base + logits_size : nullptr;
527
+
528
+ lctx.output_size = n_outputs_max;
529
+ lctx.logits_size = logits_size;
530
+ lctx.embd_size = embd_size;
531
+
532
+ // set all ids as invalid (negative)
533
+ std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
534
+
535
+ lm_ggml_backend_buffer_clear(lctx.buf_output.get(), 0);
536
+
537
+ lctx.n_outputs = 0;
538
+
539
+ return n_outputs_max;
540
+ }
541
+
542
+ void llama_output_reorder(struct llama_context & ctx) {
543
+ std::vector<size_t> & out_ids = ctx.sbatch.out_ids;
544
+ if (!out_ids.empty()) {
545
+ const uint32_t n_vocab = ctx.model.vocab.n_tokens();
546
+ const uint32_t n_embd = ctx.model.hparams.n_embd;
547
+
548
+ const int32_t n_outputs = ctx.n_outputs;
549
+ LM_GGML_ASSERT((size_t) n_outputs == out_ids.size());
550
+
551
+ // TODO: is there something more efficient which also minimizes swaps?
552
+ // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
553
+ for (int32_t i = 0; i < n_outputs - 1; ++i) {
554
+ int32_t j_min = i;
555
+ for (int32_t j = i + 1; j < n_outputs; ++j) {
556
+ if (out_ids[j] < out_ids[j_min]) {
557
+ j_min = j;
558
+ }
559
+ }
560
+ if (j_min == i) { continue; }
561
+ std::swap(out_ids[i], out_ids[j_min]);
562
+ if (ctx.logits_size > 0) {
563
+ for (uint32_t k = 0; k < n_vocab; k++) {
564
+ std::swap(ctx.logits[i*n_vocab + k], ctx.logits[j_min*n_vocab + k]);
565
+ }
566
+ }
567
+ if (ctx.embd_size > 0) {
568
+ for (uint32_t k = 0; k < n_embd; k++) {
569
+ std::swap(ctx.embd[i*n_embd + k], ctx.embd[j_min*n_embd + k]);
570
+ }
571
+ }
572
+ }
573
+ std::fill(ctx.output_ids.begin(), ctx.output_ids.end(), -1);
574
+ for (int32_t i = 0; i < n_outputs; ++i) {
575
+ ctx.output_ids[out_ids[i]] = i;
576
+ }
577
+ out_ids.clear();
578
+ }
579
+ }
580
+
581
+ //
582
+ // interface implementation
583
+ //
584
+
585
+ void llama_free(struct llama_context * ctx) {
586
+ delete ctx;
587
+ }
588
+
589
+ uint32_t llama_n_ctx(const struct llama_context * ctx) {
590
+ return ctx->cparams.n_ctx;
591
+ }
592
+
593
+ uint32_t llama_n_batch(const struct llama_context * ctx) {
594
+ return ctx->cparams.n_batch;
595
+ }
596
+
597
+ uint32_t llama_n_ubatch(const struct llama_context * ctx) {
598
+ return ctx->cparams.n_ubatch;
599
+ }
600
+
601
+ uint32_t llama_n_seq_max(const struct llama_context * ctx) {
602
+ return ctx->kv_self.size;
603
+ }
604
+
605
+ const struct llama_model * llama_get_model(const struct llama_context * ctx) {
606
+ return &ctx->model;
607
+ }
608
+
609
+ enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx) {
610
+ return ctx->cparams.pooling_type;
611
+ }
612
+
613
+ void llama_attach_threadpool(
614
+ struct llama_context * ctx,
615
+ lm_ggml_threadpool_t threadpool,
616
+ lm_ggml_threadpool_t threadpool_batch) {
617
+ ctx->threadpool = threadpool;
618
+ ctx->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
619
+ }
620
+
621
+ void llama_detach_threadpool(struct llama_context * ctx) {
622
+ ctx->threadpool = nullptr;
623
+ ctx->threadpool_batch = nullptr;
624
+ }
625
+
626
+ void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
627
+ ctx->cparams.n_threads = n_threads;
628
+ ctx->cparams.n_threads_batch = n_threads_batch;
629
+ }
630
+
631
+ int32_t llama_n_threads(struct llama_context * ctx) {
632
+ return ctx->cparams.n_threads;
633
+ }
634
+
635
+ int32_t llama_n_threads_batch(struct llama_context * ctx) {
636
+ return ctx->cparams.n_threads_batch;
637
+ }
638
+
639
+ void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
640
+ ctx->abort_callback = abort_callback;
641
+ ctx->abort_callback_data = abort_callback_data;
642
+
643
+ for (auto & backend : ctx->backends) {
644
+ auto * reg = lm_ggml_backend_dev_backend_reg(lm_ggml_backend_get_device(backend.get()));
645
+ auto * set_abort_callback_fn = (lm_ggml_backend_set_abort_callback_t) lm_ggml_backend_reg_get_proc_address(reg, "lm_ggml_backend_set_abort_callback");
646
+ if (set_abort_callback_fn) {
647
+ set_abort_callback_fn(backend.get(), ctx->abort_callback, ctx->abort_callback_data);
648
+ }
649
+ }
650
+ }
651
+
652
+ void llama_set_embeddings(struct llama_context * ctx, bool embeddings) {
653
+ ctx->cparams.embeddings = embeddings;
654
+ }
655
+
656
+ void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
657
+ ctx->cparams.causal_attn = causal_attn;
658
+ }
659
+
660
+ void llama_synchronize(struct llama_context * ctx) {
661
+ lm_ggml_backend_sched_synchronize(ctx->sched.get());
662
+
663
+ // FIXME: if multiple single tokens are evaluated without a synchronization,
664
+ // the stats will be added to the prompt evaluation stats
665
+ // this should only happen when using batch size 1 to evaluate a batch
666
+
667
+ // add the evaluation to the stats
668
+ if (ctx->n_queued_tokens == 1) {
669
+ if (!ctx->cparams.no_perf) {
670
+ ctx->t_eval_us += lm_ggml_time_us() - ctx->t_compute_start_us;
671
+ }
672
+ ctx->n_eval++;
673
+ } else if (ctx->n_queued_tokens > 1) {
674
+ if (!ctx->cparams.no_perf) {
675
+ ctx->t_p_eval_us += lm_ggml_time_us() - ctx->t_compute_start_us;
676
+ }
677
+ ctx->n_p_eval += ctx->n_queued_tokens;
678
+ }
679
+
680
+ // get a more accurate load time, upon first eval
681
+ if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
682
+ ctx->t_load_us = lm_ggml_time_us() - ctx->t_start_us;
683
+ ctx->has_evaluated_once = true;
684
+ }
685
+
686
+ ctx->n_queued_tokens = 0;
687
+ ctx->t_compute_start_us = 0;
688
+ }
689
+
690
+ float * llama_get_logits(struct llama_context * ctx) {
691
+ llama_synchronize(ctx);
692
+
693
+ // reorder logits for backward compatibility
694
+ // TODO: maybe deprecate this
695
+ llama_output_reorder(*ctx);
696
+
697
+ return ctx->logits;
698
+ }
699
+
700
+ float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
701
+ int32_t j = -1;
702
+
703
+ llama_synchronize(ctx);
704
+
705
+ try {
706
+ if (ctx->logits == nullptr) {
707
+ throw std::runtime_error("no logits");
708
+ }
709
+
710
+ if (i < 0) {
711
+ j = ctx->n_outputs + i;
712
+ if (j < 0) {
713
+ throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
714
+ }
715
+ } else if ((size_t) i >= ctx->output_ids.size()) {
716
+ throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
717
+ } else {
718
+ j = ctx->output_ids[i];
719
+ }
720
+
721
+ if (j < 0) {
722
+ throw std::runtime_error(format("batch.logits[%d] != true", i));
723
+ }
724
+ if (j >= ctx->n_outputs) {
725
+ // This should not happen
726
+ throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
727
+ }
728
+
729
+ return ctx->logits + j*ctx->model.vocab.n_tokens();
730
+ } catch (const std::exception & err) {
731
+ LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
732
+ #ifndef NDEBUG
733
+ LM_GGML_ABORT("fatal error");
734
+ #else
735
+ return nullptr;
736
+ #endif
737
+ }
738
+ }
739
+
740
+ float * llama_get_embeddings(struct llama_context * ctx) {
741
+ llama_synchronize(ctx);
742
+
743
+ // reorder embeddings for backward compatibility
744
+ // TODO: maybe deprecate this
745
+ llama_output_reorder(*ctx);
746
+
747
+ return ctx->embd;
748
+ }
749
+
750
+ float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
751
+ int32_t j = -1;
752
+
753
+ llama_synchronize(ctx);
754
+
755
+ try {
756
+ if (ctx->embd == nullptr) {
757
+ throw std::runtime_error("no embeddings");
758
+ }
759
+
760
+ if (i < 0) {
761
+ j = ctx->n_outputs + i;
762
+ if (j < 0) {
763
+ throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
764
+ }
765
+ } else if ((size_t) i >= ctx->output_ids.size()) {
766
+ throw std::runtime_error(format("out of range [0, %zu)", ctx->output_ids.size()));
767
+ } else {
768
+ j = ctx->output_ids[i];
769
+ }
770
+
771
+ if (j < 0) {
772
+ throw std::runtime_error(format("batch.logits[%d] != true", i));
773
+ }
774
+ if (j >= ctx->n_outputs) {
775
+ // This should not happen
776
+ throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
777
+ }
778
+
779
+ return ctx->embd + j*ctx->model.hparams.n_embd;
780
+ } catch (const std::exception & err) {
781
+ LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
782
+ #ifndef NDEBUG
783
+ LM_GGML_ABORT("fatal error");
784
+ #else
785
+ return nullptr;
786
+ #endif
787
+ }
788
+ }
789
+
790
+ float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
791
+ llama_synchronize(ctx);
792
+
793
+ auto it = ctx->embd_seq.find(seq_id);
794
+ if (it == ctx->embd_seq.end()) {
795
+ return nullptr;
796
+ }
797
+
798
+ return it->second.data();
799
+ }
800
+
801
+ // llama state API
802
+
803
+ // deprecated
804
+ size_t llama_get_state_size(struct llama_context * ctx) {
805
+ return llama_state_get_size(ctx);
806
+ }
807
+
808
+ // deprecated
809
+ size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
810
+ return llama_state_get_data(ctx, dst, -1);
811
+ }
812
+
813
+ // deprecated
814
+ size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
815
+ return llama_state_set_data(ctx, src, -1);
816
+ }
817
+
818
+ // deprecated
819
+ bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
820
+ return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
821
+ }
822
+
823
+ // deprecated
824
+ bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
825
+ return llama_state_save_file(ctx, path_session, tokens, n_token_count);
826
+ }
827
+
828
+ // TODO: replace all non-fatal assertions with returned errors or exceptions
829
+ struct llama_data_write {
830
+ virtual void write(const void * src, size_t size) = 0;
831
+ virtual void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) = 0;
832
+ virtual size_t get_size_written() = 0;
833
+ virtual ~llama_data_write() = default;
834
+
835
+ void write_string(const std::string & str) {
836
+ uint32_t str_size = str.size();
837
+
838
+ write(&str_size, sizeof(str_size));
839
+ write(str.data(), str_size);
840
+ }
841
+
842
+ void write_model_info(const struct llama_context * ctx) {
843
+ const std::string arch_str = llm_arch_name(ctx->model.arch);
844
+ write_string(arch_str);
845
+ // TODO: add more model-specific info which should prevent loading the session file if not identical
846
+ }
847
+
848
+ //void write_rng(const std::mt19937 & rng) {
849
+ // std::ostringstream rng_ss;
850
+ // rng_ss << rng;
851
+
852
+ // const std::string & rng_str = rng_ss.str();
853
+
854
+ // write_string(rng_str);
855
+ //}
856
+
857
+ void write_output_ids(struct llama_context * ctx) {
858
+ llama_output_reorder(*ctx);
859
+
860
+ const uint32_t n_outputs = ctx->n_outputs;
861
+
862
+ std::vector<int32_t> output_pos;
863
+
864
+ const size_t n_batch = ctx->cparams.n_batch;
865
+ const auto & output_ids = ctx->output_ids;
866
+
867
+ LM_GGML_ASSERT(n_outputs <= ctx->output_size);
868
+
869
+ output_pos.resize(n_outputs);
870
+
871
+ // build a more compact representation of the output ids
872
+ for (size_t i = 0; i < n_batch; ++i) {
873
+ // map an output id to a position in the batch
874
+ int32_t pos = output_ids[i];
875
+ if (pos >= 0) {
876
+ LM_GGML_ASSERT((uint32_t) pos < n_outputs);
877
+ output_pos[pos] = i;
878
+ }
879
+ }
880
+
881
+ write(&n_outputs, sizeof(n_outputs));
882
+
883
+ if (n_outputs) {
884
+ write(output_pos.data(), n_outputs * sizeof(int32_t));
885
+ }
886
+ }
887
+
888
+ void write_logits(const struct llama_context * ctx) {
889
+ const uint64_t logits_size = std::min((uint64_t) ctx->logits_size, (uint64_t) ctx->n_outputs * ctx->model.vocab.n_tokens());
890
+
891
+ write(&logits_size, sizeof(logits_size));
892
+
893
+ if (logits_size) {
894
+ write(ctx->logits, logits_size * sizeof(float));
895
+ }
896
+ }
897
+
898
+ void write_embeddings(const struct llama_context * ctx) {
899
+ const uint64_t embeddings_size = std::min((uint64_t) ctx->embd_size, (uint64_t) ctx->n_outputs * ctx->model.hparams.n_embd);
900
+
901
+ write(&embeddings_size, sizeof(embeddings_size));
902
+
903
+ if (embeddings_size) {
904
+ write(ctx->embd, embeddings_size * sizeof(float));
905
+ }
906
+ }
907
+
908
+ void write_kv_cache_meta(const llama_kv_cache & kv_self, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id = -1) {
909
+ for (const auto & range : cell_ranges) {
910
+ for (uint32_t i = range.first; i < range.second; ++i) {
911
+ const auto & cell = kv_self.cells[i];
912
+ const llama_pos pos = cell.pos;
913
+ const uint32_t n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
914
+
915
+ write(&pos, sizeof(pos));
916
+ write(&n_seq_id, sizeof(n_seq_id));
917
+
918
+ if (n_seq_id) {
919
+ for (auto seq_id : cell.seq_id) {
920
+ write(&seq_id, sizeof(seq_id));
921
+ }
922
+ }
923
+ }
924
+ }
925
+ }
926
+
927
+ void write_kv_cache_data(const struct llama_context * ctx, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) {
928
+ const struct llama_kv_cache & kv_self = ctx->kv_self;
929
+ const struct llama_hparams & hparams = ctx->model.hparams;
930
+
931
+ const uint32_t v_trans = kv_self.v_trans ? 1 : 0;
932
+ const uint32_t n_layer = hparams.n_layer;
933
+
934
+ write(&v_trans, sizeof(v_trans));
935
+ write(&n_layer, sizeof(n_layer));
936
+
937
+ std::vector<uint8_t> tmp_buf;
938
+
939
+ // Iterate and write all the keys first, each row is a cell
940
+ // Get whole range at a time
941
+ for (uint32_t il = 0; il < n_layer; ++il) {
942
+ const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
943
+
944
+ // Write key type
945
+ const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
946
+ write(&k_type_i, sizeof(k_type_i));
947
+
948
+ // Write row size of key
949
+ const uint64_t k_size_row = lm_ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
950
+ write(&k_size_row, sizeof(k_size_row));
951
+
952
+ // Read each range of cells of k_size length each into tmp_buf and write out
953
+ for (const auto & range : cell_ranges) {
954
+ const size_t range_size = range.second - range.first;
955
+ const size_t buf_size = range_size * k_size_row;
956
+ write_tensor_data(kv_self.k_l[il], range.first * k_size_row, buf_size);
957
+ }
958
+ }
959
+
960
+ if (!kv_self.v_trans) {
961
+ for (uint32_t il = 0; il < n_layer; ++il) {
962
+ const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
963
+
964
+ // Write value type
965
+ const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
966
+ write(&v_type_i, sizeof(v_type_i));
967
+
968
+ // Write row size of value
969
+ const uint64_t v_size_row = lm_ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
970
+ write(&v_size_row, sizeof(v_size_row));
971
+
972
+ // Read each range of cells of v_size length each into tmp_buf and write out
973
+ for (const auto & range : cell_ranges) {
974
+ const size_t range_size = range.second - range.first;
975
+ const size_t buf_size = range_size * v_size_row;
976
+ write_tensor_data(kv_self.v_l[il], range.first * v_size_row, buf_size);
977
+ }
978
+ }
979
+ } else {
980
+ // When v is transposed, we also need the element size and get the element ranges from each row
981
+ const uint32_t kv_size = kv_self.size;
982
+ for (uint32_t il = 0; il < n_layer; ++il) {
983
+ const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
984
+
985
+ // Write value type
986
+ const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
987
+ write(&v_type_i, sizeof(v_type_i));
988
+
989
+ // Write element size
990
+ const uint32_t v_size_el = lm_ggml_type_size(kv_self.v_l[il]->type);
991
+ write(&v_size_el, sizeof(v_size_el));
992
+
993
+ // Write GQA embedding size
994
+ write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
995
+
996
+ // For each row, we get the element values of each cell
997
+ for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
998
+ // Read each range of cells of v_size_el length each into tmp_buf and write out
999
+ for (const auto & range : cell_ranges) {
1000
+ const size_t range_size = range.second - range.first;
1001
+ const size_t src_offset = (range.first + j * kv_size) * v_size_el;
1002
+ const size_t buf_size = range_size * v_size_el;
1003
+ write_tensor_data(kv_self.v_l[il], src_offset, buf_size);
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ void write_kv_cache(const struct llama_context * ctx, llama_seq_id seq_id = -1) {
1011
+ const struct llama_kv_cache & kv_self = ctx->kv_self;
1012
+ std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
1013
+ uint32_t cell_count = 0;
1014
+
1015
+ // Count the number of cells with the specified seq_id
1016
+ // Find all the ranges of cells with this seq id (or all, when -1)
1017
+ uint32_t cell_range_begin = kv_self.size;
1018
+ for (uint32_t i = 0; i < kv_self.size; ++i) {
1019
+ const auto & cell = kv_self.cells[i];
1020
+ if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
1021
+ ++cell_count;
1022
+ if (cell_range_begin == kv_self.size) {
1023
+ cell_range_begin = i;
1024
+ }
1025
+ } else {
1026
+ if (cell_range_begin != kv_self.size) {
1027
+ cell_ranges.emplace_back(cell_range_begin, i);
1028
+ cell_range_begin = kv_self.size;
1029
+ }
1030
+ }
1031
+ }
1032
+ if (cell_range_begin != kv_self.size) {
1033
+ cell_ranges.emplace_back(cell_range_begin, kv_self.size);
1034
+ }
1035
+
1036
+ // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
1037
+ uint32_t cell_count_check = 0;
1038
+ for (const auto & range : cell_ranges) {
1039
+ cell_count_check += range.second - range.first;
1040
+ }
1041
+ LM_GGML_ASSERT(cell_count == cell_count_check);
1042
+
1043
+ write(&cell_count, sizeof(cell_count));
1044
+
1045
+ write_kv_cache_meta(kv_self, cell_ranges, seq_id);
1046
+ write_kv_cache_data(ctx, cell_ranges);
1047
+ }
1048
+ };
1049
+
1050
+ struct llama_data_read {
1051
+ virtual const uint8_t * read(size_t size) = 0;
1052
+ virtual void read_to(void * dst, size_t size) = 0;
1053
+ virtual size_t get_size_read() = 0;
1054
+ virtual ~llama_data_read() = default;
1055
+
1056
+ void read_string(std::string & str) {
1057
+ uint32_t str_size;
1058
+ read_to(&str_size, sizeof(str_size));
1059
+
1060
+ str.assign((const char *) read(str_size), str_size);
1061
+ }
1062
+
1063
+ // validate model information
1064
+ void read_model_info(const struct llama_context * ctx) {
1065
+ const std::string cur_arch_str = llm_arch_name(ctx->model.arch);
1066
+
1067
+ std::string arch_str;
1068
+ read_string(arch_str);
1069
+ if (cur_arch_str != arch_str) {
1070
+ throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
1071
+ }
1072
+ // TODO: add more info which needs to be identical but which is not verified otherwise
1073
+ }
1074
+
1075
+ //void read_rng(std::mt19937 & rng) {
1076
+ // std::string rng_str;
1077
+ // read_string(rng_str);
1078
+
1079
+ // std::istringstream rng_ss(rng_str);
1080
+ // rng_ss >> rng;
1081
+
1082
+ // if (rng_ss.fail()) {
1083
+ // throw std::runtime_error("failed to load RNG state");
1084
+ // }
1085
+ //}
1086
+
1087
+ void read_output_ids(struct llama_context * ctx) {
1088
+ std::vector<int32_t> output_pos;
1089
+
1090
+ uint32_t n_outputs;
1091
+ read_to(&n_outputs, sizeof(n_outputs));
1092
+
1093
+ if (n_outputs > llama_output_reserve(*ctx, n_outputs)) {
1094
+ throw std::runtime_error("could not reserve outputs");
1095
+ }
1096
+
1097
+ if (n_outputs) {
1098
+ output_pos.resize(n_outputs);
1099
+ read_to(output_pos.data(), n_outputs * sizeof(int32_t));
1100
+
1101
+ for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
1102
+ int32_t id = output_pos[i];
1103
+ if ((uint32_t) id >= ctx->cparams.n_batch) {
1104
+ throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, ctx->cparams.n_batch));
1105
+ }
1106
+ ctx->output_ids[id] = i;
1107
+ }
1108
+
1109
+ ctx->n_outputs = n_outputs;
1110
+ }
1111
+ }
1112
+
1113
+ void read_logits(struct llama_context * ctx) {
1114
+ uint64_t logits_size;
1115
+ read_to(&logits_size, sizeof(logits_size));
1116
+
1117
+ if (ctx->logits_size < logits_size) {
1118
+ throw std::runtime_error("logits buffer too small");
1119
+ }
1120
+
1121
+ if (logits_size) {
1122
+ read_to(ctx->logits, logits_size * sizeof(float));
1123
+ }
1124
+ }
1125
+
1126
+ void read_embeddings(struct llama_context * ctx) {
1127
+ uint64_t embeddings_size;
1128
+ read_to(&embeddings_size, sizeof(embeddings_size));
1129
+
1130
+ if (ctx->embd_size < embeddings_size) {
1131
+ throw std::runtime_error("embeddings buffer too small");
1132
+ }
1133
+
1134
+ if (embeddings_size) {
1135
+ read_to(ctx->embd, embeddings_size * sizeof(float));
1136
+ }
1137
+ }
1138
+
1139
+ bool read_kv_cache_meta(struct llama_context * ctx, uint32_t cell_count, llama_seq_id dest_seq_id = -1) {
1140
+ struct llama_kv_cache & kv_self = ctx->kv_self;
1141
+
1142
+ if (dest_seq_id != -1) {
1143
+ // single sequence
1144
+
1145
+ llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
1146
+
1147
+ llama_ubatch batch = ctx->sbatch.reserve_ubatch(cell_count, /* has_embd */ false);
1148
+ batch.n_tokens = cell_count;
1149
+ batch.n_seq_tokens = cell_count;
1150
+ batch.n_seqs = 1;
1151
+
1152
+ for (uint32_t i = 0; i < cell_count; ++i) {
1153
+ llama_pos pos;
1154
+ uint32_t n_seq_id;
1155
+
1156
+ read_to(&pos, sizeof(pos));
1157
+ read_to(&n_seq_id, sizeof(n_seq_id));
1158
+
1159
+ if (n_seq_id != 0) {
1160
+ LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
1161
+ return false;
1162
+ }
1163
+
1164
+ batch.pos[i] = pos;
1165
+ }
1166
+ batch.n_seq_id[0] = 1;
1167
+ batch.seq_id[0] = &dest_seq_id;
1168
+ if (!llama_kv_cache_find_slot(kv_self, batch)) {
1169
+ LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
1170
+ return false;
1171
+ }
1172
+
1173
+ // DEBUG CHECK: kv_self.head should be our first cell, kv_self.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
1174
+ // Assume that this is one contiguous block of cells
1175
+ LM_GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
1176
+ LM_GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
1177
+ LM_GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
1178
+ LM_GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
1179
+ LM_GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
1180
+ } else {
1181
+ // whole KV cache restore
1182
+
1183
+ if (cell_count > kv_self.size) {
1184
+ LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
1185
+ return false;
1186
+ }
1187
+
1188
+ llama_kv_cache_clear(kv_self);
1189
+
1190
+ for (uint32_t i = 0; i < cell_count; ++i) {
1191
+ llama_kv_cell & cell = kv_self.cells[i];
1192
+
1193
+ llama_pos pos;
1194
+ uint32_t n_seq_id;
1195
+
1196
+ read_to(&pos, sizeof(pos));
1197
+ read_to(&n_seq_id, sizeof(n_seq_id));
1198
+
1199
+ cell.pos = pos;
1200
+
1201
+ for (uint32_t j = 0; j < n_seq_id; ++j) {
1202
+ llama_seq_id seq_id;
1203
+ read_to(&seq_id, sizeof(seq_id));
1204
+
1205
+ if (seq_id < 0 || (uint32_t) seq_id >= llama_n_seq_max(ctx)) {
1206
+ LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, llama_n_seq_max(ctx));
1207
+ return false;
1208
+ }
1209
+
1210
+ cell.seq_id.insert(seq_id);
1211
+
1212
+ if (kv_self.recurrent) {
1213
+ int32_t & tail = kv_self.cells[seq_id].tail;
1214
+ if (tail != -1) {
1215
+ LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
1216
+ return false;
1217
+ }
1218
+ tail = i;
1219
+ }
1220
+ }
1221
+ }
1222
+
1223
+ kv_self.head = 0;
1224
+ kv_self.used = cell_count;
1225
+ }
1226
+
1227
+ if (kv_self.recurrent) {
1228
+ for (uint32_t i = 0; i < cell_count; ++i) {
1229
+ uint32_t cell_id = kv_self.head + i;
1230
+ // make sure the recurrent states will keep their restored state
1231
+ kv_self.cells[cell_id].src = cell_id;
1232
+ }
1233
+ }
1234
+
1235
+ return true;
1236
+ }
1237
+
1238
+ bool read_kv_cache_data(struct llama_context * ctx, uint32_t cell_count) {
1239
+ const struct llama_hparams & hparams = ctx->model.hparams;
1240
+ struct llama_kv_cache & kv_self = ctx->kv_self;
1241
+ uint32_t v_trans;
1242
+ uint32_t n_layer;
1243
+ read_to(&v_trans, sizeof(v_trans));
1244
+ read_to(&n_layer, sizeof(n_layer));
1245
+
1246
+ if (n_layer != hparams.n_layer) {
1247
+ LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer);
1248
+ return false;
1249
+ }
1250
+ if (cell_count > kv_self.size) {
1251
+ LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, kv_self.size);
1252
+ return false;
1253
+ }
1254
+ if (kv_self.v_trans != (bool) v_trans) {
1255
+ LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
1256
+ return false;
1257
+ }
1258
+
1259
+ // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
1260
+ for (uint32_t il = 0; il < n_layer; ++il) {
1261
+ const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il) + hparams.n_embd_k_s();
1262
+
1263
+ // Read type of key
1264
+ int32_t k_type_i_ref;
1265
+ read_to(&k_type_i_ref, sizeof(k_type_i_ref));
1266
+ const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
1267
+ if (k_type_i != k_type_i_ref) {
1268
+ LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
1269
+ return false;
1270
+ }
1271
+
1272
+ // Read row size of key
1273
+ uint64_t k_size_row_ref;
1274
+ read_to(&k_size_row_ref, sizeof(k_size_row_ref));
1275
+ const size_t k_size_row = lm_ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
1276
+ if (k_size_row != k_size_row_ref) {
1277
+ LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
1278
+ return false;
1279
+ }
1280
+
1281
+ if (cell_count) {
1282
+ // Read and set the keys for the whole cell range
1283
+ lm_ggml_backend_tensor_set(kv_self.k_l[il], read(cell_count * k_size_row), kv_self.head * k_size_row, cell_count * k_size_row);
1284
+ }
1285
+ }
1286
+
1287
+ if (!kv_self.v_trans) {
1288
+ for (uint32_t il = 0; il < n_layer; ++il) {
1289
+ const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
1290
+
1291
+ // Read type of value
1292
+ int32_t v_type_i_ref;
1293
+ read_to(&v_type_i_ref, sizeof(v_type_i_ref));
1294
+ const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
1295
+ if (v_type_i != v_type_i_ref) {
1296
+ LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
1297
+ return false;
1298
+ }
1299
+
1300
+ // Read row size of value
1301
+ uint64_t v_size_row_ref;
1302
+ read_to(&v_size_row_ref, sizeof(v_size_row_ref));
1303
+ const size_t v_size_row = lm_ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa);
1304
+ if (v_size_row != v_size_row_ref) {
1305
+ LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
1306
+ return false;
1307
+ }
1308
+
1309
+ if (cell_count) {
1310
+ // Read and set the values for the whole cell range
1311
+ lm_ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_row), kv_self.head * v_size_row, cell_count * v_size_row);
1312
+ }
1313
+ }
1314
+ } else {
1315
+ // For each layer, read the values for each cell (transposed)
1316
+ for (uint32_t il = 0; il < n_layer; ++il) {
1317
+ const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il) + hparams.n_embd_v_s();
1318
+
1319
+ // Read type of value
1320
+ int32_t v_type_i_ref;
1321
+ read_to(&v_type_i_ref, sizeof(v_type_i_ref));
1322
+ const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
1323
+ if (v_type_i != v_type_i_ref) {
1324
+ LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
1325
+ return false;
1326
+ }
1327
+
1328
+ // Read element size of value
1329
+ uint32_t v_size_el_ref;
1330
+ read_to(&v_size_el_ref, sizeof(v_size_el_ref));
1331
+ const size_t v_size_el = lm_ggml_type_size(kv_self.v_l[il]->type);
1332
+ if (v_size_el != v_size_el_ref) {
1333
+ LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
1334
+ return false;
1335
+ }
1336
+
1337
+ // Read GQA embedding size
1338
+ uint32_t n_embd_v_gqa_ref;
1339
+ read_to(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
1340
+ if (n_embd_v_gqa != n_embd_v_gqa_ref) {
1341
+ LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
1342
+ return false;
1343
+ }
1344
+
1345
+ if (cell_count) {
1346
+ // For each row in the transposed matrix, read the values for the whole cell range
1347
+ for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
1348
+ const size_t dst_offset = (kv_self.head + j * kv_self.size) * v_size_el;
1349
+ lm_ggml_backend_tensor_set(kv_self.v_l[il], read(cell_count * v_size_el), dst_offset, cell_count * v_size_el);
1350
+ }
1351
+ }
1352
+ }
1353
+ }
1354
+ return true;
1355
+ }
1356
+
1357
+ void read_kv_cache(struct llama_context * ctx, llama_seq_id seq_id = -1) {
1358
+ uint32_t cell_count;
1359
+ read_to(&cell_count, sizeof(cell_count));
1360
+
1361
+ bool res = read_kv_cache_meta(ctx, cell_count, seq_id) && read_kv_cache_data(ctx, cell_count);
1362
+
1363
+ if (!res) {
1364
+ if (seq_id == -1) {
1365
+ llama_kv_cache_clear(ctx);
1366
+ } else {
1367
+ llama_kv_cache_seq_rm(ctx, seq_id, -1, -1);
1368
+ }
1369
+ throw std::runtime_error("failed to restore kv cache");
1370
+ }
1371
+ }
1372
+ };
1373
+
1374
+ struct llama_data_write_dummy : llama_data_write {
1375
+ size_t size_written = 0;
1376
+
1377
+ llama_data_write_dummy() {}
1378
+
1379
+ void write(const void * /* src */, size_t size) override {
1380
+ size_written += size;
1381
+ }
1382
+
1383
+ void write_tensor_data(const struct lm_ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
1384
+ size_written += size;
1385
+ }
1386
+
1387
+ size_t get_size_written() override {
1388
+ return size_written;
1389
+ }
1390
+ };
1391
+
1392
+ struct llama_data_write_buffer : llama_data_write {
1393
+ uint8_t * ptr;
1394
+ size_t buf_size = 0;
1395
+ size_t size_written = 0;
1396
+
1397
+ llama_data_write_buffer(uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
1398
+
1399
+ void write(const void * src, size_t size) override {
1400
+ if (size > buf_size) {
1401
+ throw std::runtime_error("unexpectedly reached end of buffer");
1402
+ }
1403
+ memcpy(ptr, src, size);
1404
+ ptr += size;
1405
+ size_written += size;
1406
+ buf_size -= size;
1407
+ }
1408
+
1409
+ void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) override {
1410
+ if (size > buf_size) {
1411
+ throw std::runtime_error("unexpectedly reached end of buffer");
1412
+ }
1413
+ lm_ggml_backend_tensor_get(tensor, ptr, offset, size);
1414
+ ptr += size;
1415
+ size_written += size;
1416
+ buf_size -= size;
1417
+ }
1418
+
1419
+ size_t get_size_written() override {
1420
+ return size_written;
1421
+ }
1422
+ };
1423
+
1424
+ struct llama_data_read_buffer : llama_data_read {
1425
+ const uint8_t * ptr;
1426
+ size_t buf_size = 0;
1427
+ size_t size_read = 0;
1428
+
1429
+ llama_data_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
1430
+
1431
+ const uint8_t * read(size_t size) override {
1432
+ const uint8_t * base_ptr = ptr;
1433
+ if (size > buf_size) {
1434
+ throw std::runtime_error("unexpectedly reached end of buffer");
1435
+ }
1436
+ ptr += size;
1437
+ size_read += size;
1438
+ buf_size -= size;
1439
+ return base_ptr;
1440
+ }
1441
+
1442
+ void read_to(void * dst, size_t size) override {
1443
+ memcpy(dst, read(size), size);
1444
+ }
1445
+
1446
+ size_t get_size_read() override {
1447
+ return size_read;
1448
+ }
1449
+ };
1450
+
1451
+ struct llama_data_write_file : llama_data_write {
1452
+ llama_file * file;
1453
+ size_t size_written = 0;
1454
+ std::vector<uint8_t> temp_buffer;
1455
+
1456
+ llama_data_write_file(llama_file * f) : file(f) {}
1457
+
1458
+ void write(const void * src, size_t size) override {
1459
+ file->write_raw(src, size);
1460
+ size_written += size;
1461
+ }
1462
+
1463
+ void write_tensor_data(const struct lm_ggml_tensor * tensor, size_t offset, size_t size) override {
1464
+ temp_buffer.resize(size);
1465
+ lm_ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
1466
+ write(temp_buffer.data(), temp_buffer.size());
1467
+ }
1468
+
1469
+ size_t get_size_written() override {
1470
+ return size_written;
1471
+ }
1472
+ };
1473
+
1474
+ struct llama_data_read_file : llama_data_read {
1475
+ llama_file * file;
1476
+ size_t size_read = 0;
1477
+ std::vector<uint8_t> temp_buffer;
1478
+
1479
+ llama_data_read_file(llama_file * f) : file(f) {}
1480
+
1481
+ void read_to(void * dst, size_t size) override {
1482
+ file->read_raw(dst, size);
1483
+ size_read += size;
1484
+ }
1485
+
1486
+ const uint8_t * read(size_t size) override {
1487
+ temp_buffer.resize(size);
1488
+ read_to(temp_buffer.data(), size);
1489
+ return temp_buffer.data();
1490
+ }
1491
+
1492
+ size_t get_size_read() override {
1493
+ return size_read;
1494
+ }
1495
+ };
1496
+
1497
+ /** copy state data into either a buffer or file depending on the passed in context
1498
+ *
1499
+ * file context:
1500
+ * llama_file file("/path", "wb");
1501
+ * llama_data_write_file data_ctx(&file);
1502
+ * llama_state_get_data_internal(ctx, data_ctx);
1503
+ *
1504
+ * buffer context:
1505
+ * std::vector<uint8_t> buf(max_size, 0);
1506
+ * llama_data_write_buffer data_ctx(buf.data(), max_size);
1507
+ * llama_state_get_data_internal(ctx, data_ctx);
1508
+ *
1509
+ */
1510
+ static size_t llama_state_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx) {
1511
+ llama_synchronize(ctx);
1512
+
1513
+ data_ctx.write_model_info(ctx);
1514
+
1515
+ // copy outputs
1516
+ data_ctx.write_output_ids(ctx);
1517
+ data_ctx.write_logits(ctx);
1518
+ data_ctx.write_embeddings(ctx);
1519
+
1520
+ data_ctx.write_kv_cache(ctx);
1521
+
1522
+ return data_ctx.get_size_written();
1523
+ }
1524
+
1525
+ size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst, size_t size) {
1526
+ llama_data_write_buffer data_ctx(dst, size);
1527
+ try {
1528
+ return llama_state_get_data_internal(ctx, data_ctx);
1529
+ } catch (const std::exception & err) {
1530
+ LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
1531
+ return 0;
1532
+ }
1533
+ }
1534
+
1535
+ // Returns the *actual* size of the state.
1536
+ // Intended to be used when saving to state to a buffer.
1537
+ size_t llama_state_get_size(struct llama_context * ctx) {
1538
+ llama_data_write_dummy data_ctx;
1539
+ try {
1540
+ return llama_state_get_data_internal(ctx, data_ctx);
1541
+ } catch (const std::exception & err) {
1542
+ LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
1543
+ return 0;
1544
+ }
1545
+ }
1546
+
1547
+ static size_t llama_state_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx) {
1548
+ llama_synchronize(ctx);
1549
+
1550
+ data_ctx.read_model_info(ctx);
1551
+
1552
+ // set outputs
1553
+ data_ctx.read_output_ids(ctx);
1554
+ data_ctx.read_logits(ctx);
1555
+ data_ctx.read_embeddings(ctx);
1556
+
1557
+ data_ctx.read_kv_cache(ctx);
1558
+
1559
+ return data_ctx.get_size_read();
1560
+ }
1561
+
1562
+ // Sets the state reading from the specified source address
1563
+ size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src, size_t size) {
1564
+ llama_data_read_buffer data_ctx(src, size);
1565
+ try {
1566
+ return llama_state_set_data_internal(ctx, data_ctx);
1567
+ } catch (const std::exception & err) {
1568
+ LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
1569
+ return 0;
1570
+ }
1571
+ }
1572
+
1573
+ static bool llama_state_load_file_internal(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1574
+ llama_file file(path_session, "rb");
1575
+
1576
+ // sanity checks
1577
+ {
1578
+ const uint32_t magic = file.read_u32();
1579
+ const uint32_t version = file.read_u32();
1580
+
1581
+ if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
1582
+ LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
1583
+ return false;
1584
+ }
1585
+ }
1586
+
1587
+ // load the prompt
1588
+ {
1589
+ const uint32_t n_token_count = file.read_u32();
1590
+
1591
+ if (n_token_count > n_token_capacity) {
1592
+ LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
1593
+ return false;
1594
+ }
1595
+
1596
+ file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
1597
+ *n_token_count_out = n_token_count;
1598
+ }
1599
+
1600
+ // restore the context state
1601
+ {
1602
+ const size_t n_state_size_cur = file.size() - file.tell();
1603
+
1604
+ llama_data_read_file data_ctx(&file);
1605
+ const size_t n_read = llama_state_set_data_internal(ctx, data_ctx);
1606
+
1607
+ if (n_read != n_state_size_cur) {
1608
+ LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
1609
+ return false;
1610
+ }
1611
+ }
1612
+ return true;
1613
+ }
1614
+
1615
+ bool llama_state_load_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1616
+ try {
1617
+ return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
1618
+ } catch (const std::exception & err) {
1619
+ LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
1620
+ return false;
1621
+ }
1622
+ }
1623
+
1624
+ static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
1625
+ llama_file file(path_session, "wb");
1626
+
1627
+ file.write_u32(LLAMA_SESSION_MAGIC);
1628
+ file.write_u32(LLAMA_SESSION_VERSION);
1629
+
1630
+ // save the prompt
1631
+ file.write_u32((uint32_t) n_token_count);
1632
+ file.write_raw(tokens, sizeof(llama_token) * n_token_count);
1633
+
1634
+ // save the context state using stream saving
1635
+ llama_data_write_file data_ctx(&file);
1636
+ llama_state_get_data_internal(ctx, data_ctx);
1637
+
1638
+ return true;
1639
+ }
1640
+
1641
+ bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
1642
+ try {
1643
+ return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
1644
+ } catch (const std::exception & err) {
1645
+ LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
1646
+ return false;
1647
+ }
1648
+ }
1649
+
1650
+ static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_write & data_ctx, llama_seq_id seq_id) {
1651
+ llama_synchronize(ctx);
1652
+
1653
+ data_ctx.write_kv_cache(ctx, seq_id);
1654
+
1655
+ return data_ctx.get_size_written();
1656
+ }
1657
+
1658
+ size_t llama_state_seq_get_size(struct llama_context * ctx, llama_seq_id seq_id) {
1659
+ llama_data_write_dummy data_ctx;
1660
+ return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1661
+ }
1662
+
1663
+ size_t llama_state_seq_get_data(struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
1664
+ llama_data_write_buffer data_ctx(dst, size);
1665
+ try {
1666
+ return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1667
+ } catch (const std::exception & err) {
1668
+ LLAMA_LOG_ERROR("%s: error saving sequence state: %s\n", __func__, err.what());
1669
+ return 0;
1670
+ }
1671
+ }
1672
+
1673
+ static size_t llama_state_seq_set_data_internal(struct llama_context * ctx, llama_data_read & data_ctx, llama_seq_id dest_seq_id) {
1674
+ llama_synchronize(ctx);
1675
+
1676
+ data_ctx.read_kv_cache(ctx, dest_seq_id);
1677
+
1678
+ return data_ctx.get_size_read();
1679
+ }
1680
+
1681
+ size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id) {
1682
+ llama_data_read_buffer data_ctx(src, size);
1683
+ try {
1684
+ return llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
1685
+ } catch (const std::exception & err) {
1686
+ LLAMA_LOG_ERROR("%s: error loading sequence state: %s\n", __func__, err.what());
1687
+ return 0;
1688
+ }
1689
+ }
1690
+
1691
+ static size_t llama_state_seq_save_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
1692
+ llama_file file(filepath, "wb");
1693
+
1694
+ file.write_u32(LLAMA_STATE_SEQ_MAGIC);
1695
+ file.write_u32(LLAMA_STATE_SEQ_VERSION);
1696
+
1697
+ // save the prompt
1698
+ file.write_u32((uint32_t) n_token_count);
1699
+ file.write_raw(tokens, sizeof(llama_token) * n_token_count);
1700
+
1701
+ // save the context state using stream saving
1702
+ llama_data_write_file data_ctx(&file);
1703
+ llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
1704
+
1705
+ const size_t res = file.tell();
1706
+ LM_GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
1707
+ return res;
1708
+ }
1709
+
1710
+ static size_t llama_state_seq_load_file_internal(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1711
+ llama_file file(filepath, "rb");
1712
+
1713
+ // version checks
1714
+ {
1715
+ const uint32_t magic = file.read_u32();
1716
+ const uint32_t version = file.read_u32();
1717
+
1718
+ if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
1719
+ LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
1720
+ return 0;
1721
+ }
1722
+ }
1723
+
1724
+ // load the prompt
1725
+ {
1726
+ const uint32_t n_token_count = file.read_u32();
1727
+
1728
+ if (n_token_count > n_token_capacity) {
1729
+ LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
1730
+ return 0;
1731
+ }
1732
+
1733
+ file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
1734
+ *n_token_count_out = n_token_count;
1735
+ }
1736
+
1737
+ // restore the context state
1738
+ {
1739
+ const size_t state_size = file.size() - file.tell();
1740
+ llama_data_read_file data_ctx(&file);
1741
+ const size_t nread = llama_state_seq_set_data_internal(ctx, data_ctx, dest_seq_id);
1742
+ if (!nread) {
1743
+ LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
1744
+ return 0;
1745
+ }
1746
+ LM_GGML_ASSERT(nread <= state_size);
1747
+ LM_GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
1748
+ }
1749
+
1750
+ return file.tell();
1751
+ }
1752
+
1753
+ size_t llama_state_seq_save_file(struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
1754
+ try {
1755
+ return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
1756
+ } catch (const std::exception & err) {
1757
+ LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
1758
+ return 0;
1759
+ }
1760
+ }
1761
+
1762
+ size_t llama_state_seq_load_file(struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
1763
+ try {
1764
+ return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
1765
+ } catch (const std::exception & err) {
1766
+ LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
1767
+ return 0;
1768
+ }
1769
+ }
1770
+
1771
+ const std::vector<std::pair<std::string, struct lm_ggml_tensor *>> & llama_internal_get_tensor_map(
1772
+ struct llama_context * ctx
1773
+ ) {
1774
+ return ctx->model.tensors_by_name;
1775
+ }