llama-context.cpp 66 KB

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