llama-context.cpp 64 KB

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