llama.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "llama_util.h"
  6. #include "llama.h"
  7. #include "ggml.h"
  8. #include <array>
  9. #include <cinttypes>
  10. #include <fstream>
  11. #include <random>
  12. #include <map>
  13. #include <unordered_map>
  14. #include <queue>
  15. #include <cassert>
  16. #include <cstring>
  17. #include <climits>
  18. #include <memory>
  19. #include <algorithm>
  20. #include <initializer_list>
  21. #define LLAMA_USE_SCRATCH
  22. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  23. // available llama models
  24. enum e_model {
  25. MODEL_UNKNOWN,
  26. MODEL_7B,
  27. MODEL_13B,
  28. MODEL_30B,
  29. MODEL_65B,
  30. };
  31. static const size_t MB = 1024*1024;
  32. // computed for n_ctx == 2048
  33. // TODO: dynamically determine these sizes
  34. // needs modifications in ggml
  35. static const std::map<e_model, size_t> MEM_REQ_SCRATCH0 = {
  36. { MODEL_7B, 512ull*MB },
  37. { MODEL_13B, 512ull*MB },
  38. { MODEL_30B, 512ull*MB },
  39. { MODEL_65B, 512ull*MB },
  40. };
  41. static const std::map<e_model, size_t> MEM_REQ_SCRATCH1 = {
  42. { MODEL_7B, 512ull*MB },
  43. { MODEL_13B, 512ull*MB },
  44. { MODEL_30B, 512ull*MB },
  45. { MODEL_65B, 512ull*MB },
  46. };
  47. // 2*n_embd*n_ctx*n_layer*sizeof(float16)
  48. static const std::map<e_model, size_t> MEM_REQ_KV_SELF = {
  49. { MODEL_7B, 1026ull*MB },
  50. { MODEL_13B, 1608ull*MB },
  51. { MODEL_30B, 3124ull*MB },
  52. { MODEL_65B, 5120ull*MB },
  53. };
  54. // this is mostly needed for temporary mul_mat buffers to dequantize the data
  55. // not actually needed if BLAS is disabled
  56. static const std::map<e_model, size_t> MEM_REQ_EVAL = {
  57. { MODEL_7B, 768ull*MB },
  58. { MODEL_13B, 1024ull*MB },
  59. { MODEL_30B, 1280ull*MB },
  60. { MODEL_65B, 1536ull*MB },
  61. };
  62. // default hparams (LLaMA 7B)
  63. struct llama_hparams {
  64. uint32_t n_vocab = 32000;
  65. uint32_t n_ctx = 512; // this is provided as user input?
  66. uint32_t n_embd = 4096;
  67. uint32_t n_mult = 256;
  68. uint32_t n_head = 32;
  69. uint32_t n_layer = 32;
  70. uint32_t n_rot = 64;
  71. enum llama_ftype ftype = LLAMA_FTYPE_MOSTLY_F16;
  72. bool operator!=(const llama_hparams & other) const {
  73. return memcmp(this, &other, sizeof(llama_hparams));
  74. }
  75. };
  76. struct llama_layer {
  77. // normalization
  78. struct ggml_tensor * attention_norm;
  79. // attention
  80. struct ggml_tensor * wq;
  81. struct ggml_tensor * wk;
  82. struct ggml_tensor * wv;
  83. struct ggml_tensor * wo;
  84. // normalization
  85. struct ggml_tensor * ffn_norm;
  86. // ff
  87. struct ggml_tensor * w1;
  88. struct ggml_tensor * w2;
  89. struct ggml_tensor * w3;
  90. };
  91. struct llama_kv_cache {
  92. struct ggml_tensor * k;
  93. struct ggml_tensor * v;
  94. struct ggml_context * ctx = NULL;
  95. llama_buffer buf;
  96. int n; // number of tokens currently in the cache
  97. ~llama_kv_cache() {
  98. if (ctx) {
  99. ggml_free(ctx);
  100. }
  101. }
  102. };
  103. struct llama_model {
  104. e_model type = MODEL_UNKNOWN;
  105. llama_hparams hparams;
  106. struct ggml_tensor * tok_embeddings;
  107. struct ggml_tensor * norm;
  108. struct ggml_tensor * output;
  109. std::vector<llama_layer> layers;
  110. // context
  111. struct ggml_context * ctx = NULL;
  112. // key + value cache for the self attention
  113. // TODO: move to llama_state
  114. struct llama_kv_cache kv_self;
  115. // the model memory buffer
  116. llama_buffer buf;
  117. // model memory mapped file
  118. std::unique_ptr<llama_mmap> mapping;
  119. // objects representing data potentially being locked in memory
  120. llama_mlock mlock_buf;
  121. llama_mlock mlock_mmap;
  122. // for quantize-stats only
  123. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  124. ~llama_model() {
  125. if (ctx) {
  126. ggml_free(ctx);
  127. }
  128. }
  129. };
  130. struct llama_vocab {
  131. using id = int32_t;
  132. using token = std::string;
  133. struct token_score {
  134. token tok;
  135. float score;
  136. };
  137. std::unordered_map<token, id> token_to_id;
  138. std::vector<token_score> id_to_token;
  139. };
  140. struct llama_context {
  141. std::mt19937 rng;
  142. int64_t t_load_us = 0;
  143. int64_t t_start_us = 0;
  144. bool has_evaluated_once = false;
  145. int64_t t_sample_us = 0;
  146. int64_t t_eval_us = 0;
  147. int64_t t_p_eval_us = 0;
  148. int32_t n_sample = 0; // number of tokens sampled
  149. int32_t n_eval = 0; // number of eval calls
  150. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  151. llama_model model;
  152. llama_vocab vocab;
  153. size_t mem_per_token = 0;
  154. // decode output (2-dimensional array: [n_tokens][n_vocab])
  155. std::vector<float> logits;
  156. bool logits_all = false;
  157. // input embedding (1-dimensional array: [n_embd])
  158. std::vector<float> embedding;
  159. // memory buffers used to evaluate the model
  160. // TODO: move in llama_state
  161. llama_buffer buf_compute;
  162. llama_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  163. int buf_last = 0;
  164. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  165. void use_buf(struct ggml_context * ctx, int i) {
  166. #if defined(LLAMA_USE_SCRATCH)
  167. size_t last_size = 0;
  168. if (i == -1) {
  169. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  170. } else {
  171. auto & buf = buf_scratch[i];
  172. last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
  173. }
  174. if (buf_last >= 0) {
  175. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  176. }
  177. buf_last = i;
  178. #else
  179. (void) i;
  180. (void) ctx;
  181. #endif
  182. }
  183. size_t get_buf_max_mem(int i) const {
  184. #if defined(LLAMA_USE_SCRATCH)
  185. return buf_max_size[i];
  186. #else
  187. (void) i;
  188. return 0;
  189. #endif
  190. }
  191. };
  192. template <typename T>
  193. static T checked_mul(T a, T b) {
  194. T ret = a * b;
  195. if (a != 0 && ret / a != b) {
  196. throw format("overflow multiplying %llu * %llu",
  197. (unsigned long long) a, (unsigned long long) b);
  198. }
  199. return ret;
  200. }
  201. static size_t checked_div(size_t a, size_t b) {
  202. if (b == 0 || a % b != 0) {
  203. throw format("error dividing %zu / %zu", a, b);
  204. }
  205. return a / b;
  206. }
  207. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  208. std::string ret = "[" + std::to_string(ne.at(0));
  209. for (size_t i = 1; i < ne.size(); i++) {
  210. ret += " x " + std::to_string(ne.at(i));
  211. }
  212. ret += "]";
  213. return ret;
  214. }
  215. static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
  216. size_t size = ggml_type_size(type);
  217. for (uint32_t dim : ne) {
  218. size = checked_mul<size_t>(size, dim);
  219. }
  220. return size / ggml_blck_size(type);
  221. }
  222. struct llama_load_tensor_shard {
  223. std::vector<uint32_t> ne;
  224. size_t size;
  225. enum ggml_type type;
  226. size_t file_idx;
  227. size_t file_off;
  228. void calc_size() {
  229. size = llama_calc_tensor_size(ne, type);
  230. }
  231. };
  232. enum llama_split_type {
  233. SPLIT_NONE,
  234. SPLIT_BY_COLUMNS,
  235. SPLIT_BY_ROWS
  236. };
  237. struct llama_load_tensor {
  238. std::vector<llama_load_tensor_shard> shards;
  239. std::string name;
  240. enum ggml_type type = GGML_TYPE_F32;
  241. llama_split_type split_type = SPLIT_NONE;
  242. std::vector<uint32_t> ne;
  243. size_t size;
  244. struct ggml_tensor * ggml_tensor = NULL;
  245. uint8_t * data;
  246. llama_load_tensor(const std::string & name) : name(name) {}
  247. void calc_all() {
  248. calc_type();
  249. calc_split_type();
  250. calc_ne();
  251. calc_size();
  252. }
  253. void calc_type() {
  254. const auto & first_shard = shards.at(0);
  255. for (const auto & shard : shards) {
  256. if (shard.type != first_shard.type) {
  257. throw format("inconsistent tensor shard type in '%s'", name.c_str());
  258. }
  259. }
  260. type = first_shard.type;
  261. }
  262. void calc_split_type() {
  263. if (shards.at(0).ne.size() == 1 || // 1D tensors are just duplicated in every file
  264. shards.size() == 1) { // only one file?
  265. split_type = SPLIT_NONE;
  266. } else if (name.find("tok_embeddings.") == 0 ||
  267. name.find(".attention.wo.weight") != std::string::npos ||
  268. name.find(".feed_forward.w2.weight") != std::string::npos) {
  269. split_type = SPLIT_BY_COLUMNS;
  270. } else {
  271. split_type = SPLIT_BY_ROWS;
  272. }
  273. }
  274. void calc_ne() {
  275. const auto & first_shard = shards.at(0);
  276. for (const auto & shard : shards) {
  277. if (shard.ne != first_shard.ne) {
  278. throw format("inconsistent tensor shard shape in '%s': first was %s, other was %s",
  279. name.c_str(), llama_format_tensor_shape(first_shard.ne).c_str(), llama_format_tensor_shape(shard.ne).c_str());
  280. }
  281. }
  282. ne = first_shard.ne;
  283. LLAMA_ASSERT(shards.size() <= UINT32_MAX);
  284. uint32_t n_shards = (uint32_t) shards.size();
  285. switch (split_type) {
  286. case SPLIT_NONE:
  287. ne = first_shard.ne;
  288. break;
  289. case SPLIT_BY_COLUMNS:
  290. ne = {checked_mul<uint32_t>(first_shard.ne[0], n_shards),
  291. first_shard.ne[1]};
  292. break;
  293. case SPLIT_BY_ROWS:
  294. ne = {first_shard.ne[0],
  295. checked_mul<uint32_t>(first_shard.ne[1], n_shards)};
  296. break;
  297. }
  298. }
  299. void calc_size() {
  300. size = llama_calc_tensor_size(ne, type);
  301. }
  302. };
  303. struct llama_load_tensors_map {
  304. // tensors is kept in a separate vector to preserve file order
  305. std::vector<llama_load_tensor> tensors;
  306. std::unordered_map<std::string, size_t> name_to_idx;
  307. };
  308. enum llama_file_version {
  309. LLAMA_FILE_VERSION_GGML,
  310. LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
  311. LLAMA_FILE_VERSION_GGJT_V1, // added padding
  312. };
  313. struct llama_file_loader {
  314. llama_file file;
  315. llama_file_version file_version;
  316. llama_hparams hparams;
  317. llama_vocab vocab;
  318. llama_file_loader(const char * fname, size_t file_idx, llama_load_tensors_map & tensors_map)
  319. : file(fname, "rb") {
  320. fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
  321. read_magic();
  322. read_hparams();
  323. read_vocab();
  324. read_tensor_metadata(file_idx, tensors_map);
  325. }
  326. void read_magic() {
  327. uint32_t magic = file.read_u32();
  328. uint32_t version = 0;
  329. if (magic != 'ggml') {
  330. version = file.read_u32();
  331. }
  332. if (magic == 'ggml' && version == 0) {
  333. file_version = LLAMA_FILE_VERSION_GGML;
  334. } else if (magic == 'ggmf' && version == 1) {
  335. file_version = LLAMA_FILE_VERSION_GGMF_V1;
  336. } else if (magic == 'ggjt' && version == 1) {
  337. file_version = LLAMA_FILE_VERSION_GGJT_V1;
  338. } else {
  339. throw format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
  340. magic, version);
  341. }
  342. }
  343. void read_hparams() {
  344. hparams.n_vocab = file.read_u32();
  345. hparams.n_embd = file.read_u32();
  346. hparams.n_mult = file.read_u32();
  347. hparams.n_head = file.read_u32();
  348. hparams.n_layer = file.read_u32();
  349. hparams.n_rot = file.read_u32();
  350. hparams.ftype = (enum llama_ftype) file.read_u32();
  351. }
  352. void read_vocab() {
  353. vocab.id_to_token.resize(hparams.n_vocab);
  354. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  355. uint32_t len = file.read_u32();
  356. std::string word = file.read_string(len);
  357. float score = 0.0f;
  358. if (file_version >= LLAMA_FILE_VERSION_GGMF_V1) {
  359. file.read_raw(&score, sizeof(score));
  360. }
  361. vocab.token_to_id[word] = i;
  362. auto & tok_score = vocab.id_to_token[i];
  363. tok_score.tok = std::move(word);
  364. tok_score.score = score;
  365. }
  366. }
  367. void read_tensor_metadata(size_t file_idx, llama_load_tensors_map & tensors_map) {
  368. while (file.tell() < file.size) {
  369. llama_load_tensor_shard shard;
  370. uint32_t n_dims = file.read_u32();
  371. uint32_t name_len = file.read_u32();
  372. shard.type = (enum ggml_type) file.read_u32();
  373. shard.ne.resize(n_dims);
  374. file.read_raw(shard.ne.data(), sizeof(shard.ne[0]) * n_dims);
  375. std::string name = file.read_string(name_len);
  376. if (n_dims < 1 || n_dims > 2) {
  377. throw format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims);
  378. }
  379. switch (shard.type) {
  380. case GGML_TYPE_F32:
  381. case GGML_TYPE_F16:
  382. case GGML_TYPE_Q4_0:
  383. case GGML_TYPE_Q4_1:
  384. break;
  385. default: {
  386. throw format("unrecognized tensor type %u\n", shard.type);
  387. }
  388. }
  389. if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
  390. // skip to the next multiple of 32 bytes
  391. file.seek(-file.tell() & 31, SEEK_CUR);
  392. }
  393. shard.file_idx = file_idx;
  394. shard.file_off = file.tell();
  395. shard.calc_size();
  396. file.seek(shard.size, SEEK_CUR);
  397. auto it = tensors_map.name_to_idx.find(name);
  398. size_t idx;
  399. if (it != tensors_map.name_to_idx.end()) {
  400. idx = it->second;
  401. } else {
  402. tensors_map.tensors.emplace_back(name);
  403. idx = tensors_map.tensors.size() - 1;
  404. tensors_map.name_to_idx.emplace(name, idx);
  405. }
  406. tensors_map.tensors.at(idx).shards.push_back(shard);
  407. }
  408. }
  409. };
  410. struct llama_file_saver {
  411. llama_file file;
  412. llama_file_loader * any_file_loader;
  413. llama_file_saver(const char * fname, llama_file_loader * any_file_loader, enum llama_ftype new_ftype)
  414. : file(fname, "wb"), any_file_loader(any_file_loader) {
  415. fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
  416. write_magic();
  417. write_hparams(new_ftype);
  418. write_vocab();
  419. }
  420. void write_magic() {
  421. file.write_u32('ggjt'); // magic
  422. file.write_u32(1); // version
  423. }
  424. void write_hparams(enum llama_ftype new_ftype) {
  425. const llama_hparams & hparams = any_file_loader->hparams;
  426. file.write_u32(hparams.n_vocab);
  427. file.write_u32(hparams.n_embd);
  428. file.write_u32(hparams.n_mult);
  429. file.write_u32(hparams.n_head);
  430. file.write_u32(hparams.n_layer);
  431. file.write_u32(hparams.n_rot);
  432. file.write_u32(new_ftype);
  433. }
  434. void write_vocab() {
  435. if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
  436. fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
  437. }
  438. uint32_t n_vocab = any_file_loader->hparams.n_vocab;
  439. for (uint32_t i = 0; i < n_vocab; i++) {
  440. const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
  441. file.write_u32((uint32_t) token_score.tok.size());
  442. file.write_raw(token_score.tok.data(), token_score.tok.size());
  443. file.write_raw(&token_score.score, sizeof(token_score.score));
  444. }
  445. }
  446. void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
  447. switch (new_type) {
  448. case GGML_TYPE_F32:
  449. case GGML_TYPE_F16:
  450. case GGML_TYPE_Q4_0:
  451. case GGML_TYPE_Q4_1:
  452. break;
  453. default: LLAMA_ASSERT(false);
  454. }
  455. file.write_u32((uint32_t) tensor.ne.size());
  456. file.write_u32((uint32_t) tensor.name.size());
  457. file.write_u32(new_type);
  458. file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
  459. file.write_raw(tensor.name.data(), tensor.name.size());
  460. file.seek(-file.tell() & 31, SEEK_CUR);
  461. LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
  462. file.write_raw(new_data, new_size);
  463. }
  464. };
  465. struct llama_model_loader {
  466. std::vector<std::unique_ptr<llama_file_loader>> file_loaders;
  467. llama_load_tensors_map tensors_map;
  468. bool use_mmap;
  469. size_t num_ggml_tensors_created = 0;
  470. struct ggml_context * ggml_ctx = NULL;
  471. std::unique_ptr<llama_mmap> mapping;
  472. llama_model_loader(const std::string & fname_base, bool use_mmap, bool vocab_only) {
  473. auto first_file = new llama_file_loader(fname_base.c_str(), 0, tensors_map);
  474. file_loaders.emplace_back(first_file);
  475. uint32_t n_parts = vocab_only ? 1 : guess_n_parts();
  476. for (uint32_t i = 1; i < n_parts; i++) {
  477. std::string fname = fname_base + "." + std::to_string(i);
  478. auto ith_file = new llama_file_loader(fname.c_str(), i, tensors_map);
  479. file_loaders.emplace_back(ith_file);
  480. if (ith_file->hparams != first_file->hparams) {
  481. throw format("llama.cpp: hparams inconsistent between files");
  482. }
  483. }
  484. if (!llama_mmap::SUPPORTED) {
  485. use_mmap = false;
  486. }
  487. if (use_mmap && alignment_prevents_mmap()) {
  488. fprintf(stderr, "llama.cpp: can't use mmap because tensors are not aligned; convert to new format to avoid this\n");
  489. use_mmap = false;
  490. }
  491. this->use_mmap = use_mmap;
  492. for (llama_load_tensor & lt : tensors_map.tensors) {
  493. lt.calc_all();
  494. }
  495. }
  496. bool alignment_prevents_mmap() {
  497. for (const llama_load_tensor & lt : tensors_map.tensors) {
  498. for (const llama_load_tensor_shard & shard : lt.shards) {
  499. if (shard.file_off & 3) {
  500. return true;
  501. }
  502. }
  503. }
  504. return false;
  505. }
  506. uint32_t guess_n_parts() const {
  507. auto it = tensors_map.name_to_idx.find("tok_embeddings.weight");
  508. if (it == tensors_map.name_to_idx.end()) {
  509. throw std::string("missing tok_embeddings.weight");
  510. }
  511. const llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  512. return file_loaders.at(0)->hparams.n_embd / lt.shards.at(0).ne.at(0);
  513. }
  514. void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
  515. *ctx_size_p = *mmapped_size_p = 0;
  516. for (const llama_load_tensor & lt : tensors_map.tensors) {
  517. *ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  518. *(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size;
  519. }
  520. }
  521. struct ggml_tensor * get_tensor(const std::string & name, std::vector<uint32_t> ne) {
  522. auto it = tensors_map.name_to_idx.find(name);
  523. if (it == tensors_map.name_to_idx.end()) {
  524. throw format("llama.cpp: tensor '%s' is missing from model", name.c_str());
  525. }
  526. llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  527. if (lt.ne != ne) {
  528. throw format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
  529. name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str());
  530. }
  531. return get_tensor_for(lt);
  532. }
  533. struct ggml_tensor * get_tensor_for(llama_load_tensor & lt) {
  534. struct ggml_tensor * tensor;
  535. if (lt.ne.size() == 2) {
  536. tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
  537. } else {
  538. LLAMA_ASSERT(lt.ne.size() == 1);
  539. tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
  540. }
  541. LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
  542. lt.ggml_tensor = tensor;
  543. num_ggml_tensors_created++;
  544. return tensor;
  545. }
  546. void done_getting_tensors() {
  547. if (num_ggml_tensors_created != tensors_map.tensors.size()) {
  548. throw std::string("llama.cpp: file contained more tensors than expected");
  549. }
  550. }
  551. void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  552. size_t data_size = 0;
  553. for (const llama_load_tensor & lt : tensors_map.tensors) {
  554. data_size += lt.size;
  555. }
  556. if (use_mmap) {
  557. mapping.reset(new llama_mmap(&file_loaders.at(0)->file));
  558. if (!lmlock) {
  559. // Don't call the callback since the actual loading will be lazy
  560. // and we can't measure it.
  561. progress_callback = NULL;
  562. }
  563. if (lmlock) {
  564. lmlock->init(mapping->addr);
  565. }
  566. }
  567. size_t done_size = 0;
  568. for (llama_load_tensor & lt : tensors_map.tensors) {
  569. if (progress_callback) {
  570. progress_callback((float) done_size / data_size, progress_callback_user_data);
  571. }
  572. LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
  573. lt.data = (uint8_t *) lt.ggml_tensor->data;
  574. load_data_for(lt);
  575. lt.ggml_tensor->data = lt.data;
  576. done_size += lt.size;
  577. if (use_mmap && lmlock) {
  578. lmlock->grow_to(done_size);
  579. }
  580. }
  581. if (progress_callback) {
  582. progress_callback(1.0f, progress_callback_user_data);
  583. }
  584. }
  585. void load_data_for(llama_load_tensor & lt) {
  586. if (use_mmap) {
  587. LLAMA_ASSERT(lt.shards.size() == 1);
  588. lt.data = (uint8_t *) mapping->addr + lt.shards.at(0).file_off;
  589. } else if (lt.split_type == SPLIT_NONE) {
  590. llama_file & file = file_loaders.at(lt.shards.at(0).file_idx)->file;
  591. file.seek(lt.shards.at(0).file_off, SEEK_SET);
  592. file.read_raw(lt.data, lt.size);
  593. } else if (lt.split_type == SPLIT_BY_ROWS) {
  594. size_t offset = 0;
  595. for (llama_load_tensor_shard & shard : lt.shards) {
  596. llama_file & file = file_loaders.at(shard.file_idx)->file;
  597. file.seek(shard.file_off, SEEK_SET);
  598. file.read_raw(lt.data + offset, shard.size);
  599. offset += shard.size;
  600. }
  601. LLAMA_ASSERT(offset == lt.size);
  602. } else if (lt.split_type == SPLIT_BY_COLUMNS) {
  603. // Let's load the data into temporary buffers to ensure the OS performs large loads.
  604. std::vector<llama_buffer> tmp_bufs;
  605. tmp_bufs.resize(lt.shards.size());
  606. for (size_t i = 0; i < lt.shards.size(); i++) {
  607. llama_load_tensor_shard & shard = lt.shards.at(i);
  608. llama_file & file = file_loaders.at(shard.file_idx)->file;
  609. file.seek(shard.file_off, SEEK_SET);
  610. tmp_bufs.at(i).resize(shard.size);
  611. file.read_raw(tmp_bufs.at(i).addr, shard.size);
  612. }
  613. // Then reshape.
  614. size_t num_rows = lt.ne.at(1);
  615. size_t per_shard_row_size = lt.shards.at(0).size / num_rows;
  616. size_t out_offset = 0;
  617. for (size_t row = 0; row < num_rows; row++) {
  618. for (llama_buffer & tmp_buf : tmp_bufs) {
  619. memcpy(lt.data + out_offset,
  620. tmp_buf.addr + row * per_shard_row_size,
  621. per_shard_row_size);
  622. out_offset += per_shard_row_size;
  623. }
  624. }
  625. LLAMA_ASSERT(out_offset == lt.size);
  626. }
  627. if (0) {
  628. print_checksum(lt);
  629. }
  630. }
  631. static void print_checksum(llama_load_tensor & lt) {
  632. uint32_t sum = 0;
  633. for (size_t i = 0; i < lt.size; i++) {
  634. uint8_t byte = lt.data[i];
  635. sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
  636. }
  637. fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
  638. llama_format_tensor_shape(lt.ne).c_str(), lt.size);
  639. }
  640. };
  641. //
  642. // kv cache
  643. //
  644. static bool kv_cache_init(
  645. const struct llama_hparams & hparams,
  646. struct llama_kv_cache & cache,
  647. ggml_type wtype,
  648. int n_ctx) {
  649. const int n_embd = hparams.n_embd;
  650. const int n_layer = hparams.n_layer;
  651. const int64_t n_mem = (int64_t)n_layer*n_ctx;
  652. const int64_t n_elements = n_embd*n_mem;
  653. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  654. struct ggml_init_params params;
  655. params.mem_size = cache.buf.size;
  656. params.mem_buffer = cache.buf.addr;
  657. params.no_alloc = false;
  658. cache.ctx = ggml_init(params);
  659. if (!cache.ctx) {
  660. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  661. return false;
  662. }
  663. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  664. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  665. return true;
  666. }
  667. struct llama_context_params llama_context_default_params() {
  668. struct llama_context_params result = {
  669. /*.n_ctx =*/ 512,
  670. /*.n_parts =*/ -1,
  671. /*.seed =*/ 0,
  672. /*.f16_kv =*/ false,
  673. /*.logits_all =*/ false,
  674. /*.vocab_only =*/ false,
  675. /*.use_mmap =*/ true,
  676. /*.use_mlock =*/ false,
  677. /*.embedding =*/ false,
  678. /*.progress_callback =*/ nullptr,
  679. /*.progress_callback_user_data =*/ nullptr,
  680. };
  681. return result;
  682. }
  683. bool llama_mmap_supported() {
  684. return llama_mmap::SUPPORTED;
  685. }
  686. bool llama_mlock_supported() {
  687. return llama_mlock::SUPPORTED;
  688. }
  689. //
  690. // model loading
  691. //
  692. static const char *llama_file_version_name(llama_file_version version) {
  693. switch (version) {
  694. case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
  695. case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
  696. case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (latest)";
  697. default: LLAMA_ASSERT(false);
  698. }
  699. }
  700. static const char *llama_ftype_name(enum llama_ftype ftype) {
  701. switch (ftype) {
  702. case LLAMA_FTYPE_ALL_F32: return "all F32";
  703. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  704. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  705. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  706. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  707. return "mostly Q4_1, some F16";
  708. default: return "unknown, may not work";
  709. }
  710. }
  711. static const char *llama_model_type_name(e_model type) {
  712. switch (type) {
  713. case MODEL_7B: return "7B";
  714. case MODEL_13B: return "13B";
  715. case MODEL_30B: return "30B";
  716. case MODEL_65B: return "65B";
  717. default: LLAMA_ASSERT(false);
  718. }
  719. }
  720. static void llama_model_load_internal(
  721. const std::string & fname,
  722. llama_context & lctx,
  723. int n_ctx,
  724. ggml_type memory_type,
  725. bool use_mmap,
  726. bool use_mlock,
  727. bool vocab_only,
  728. llama_progress_callback progress_callback,
  729. void * progress_callback_user_data) {
  730. lctx.t_start_us = ggml_time_us();
  731. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap, vocab_only));
  732. lctx.vocab = std::move(ml->file_loaders.at(0)->vocab);
  733. auto & model = lctx.model;
  734. model.hparams = ml->file_loaders.at(0)->hparams;
  735. llama_file_version file_version = ml->file_loaders.at(0)->file_version;
  736. auto & hparams = model.hparams;
  737. uint32_t n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  738. {
  739. switch (hparams.n_layer) {
  740. case 32: model.type = e_model::MODEL_7B; break;
  741. case 40: model.type = e_model::MODEL_13B; break;
  742. case 60: model.type = e_model::MODEL_30B; break;
  743. case 80: model.type = e_model::MODEL_65B; break;
  744. }
  745. hparams.n_ctx = n_ctx;
  746. }
  747. {
  748. fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
  749. fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  750. fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  751. fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
  752. fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
  753. fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
  754. fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
  755. fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot);
  756. fprintf(stderr, "%s: ftype = %u (%s)\n", __func__, hparams.ftype, llama_ftype_name(hparams.ftype));
  757. fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
  758. fprintf(stderr, "%s: n_parts = %zu\n", __func__, ml->file_loaders.size());
  759. fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
  760. }
  761. if (vocab_only) {
  762. return;
  763. }
  764. auto & ctx = model.ctx;
  765. size_t ctx_size, mmapped_size;
  766. ml->calc_sizes(&ctx_size, &mmapped_size);
  767. fprintf(stderr, "%s: ggml ctx size = %6.2f KB\n", __func__, ctx_size/1024.0);
  768. // print memory requirements
  769. {
  770. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  771. // this is the total memory required to run the inference
  772. const size_t mem_required =
  773. ctx_size +
  774. mmapped_size +
  775. MEM_REQ_SCRATCH0.at(model.type) +
  776. MEM_REQ_SCRATCH1.at(model.type) +
  777. MEM_REQ_EVAL.at (model.type);
  778. // this is the memory required by one llama_state
  779. const size_t mem_required_state =
  780. scale*MEM_REQ_KV_SELF.at(model.type);
  781. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  782. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  783. }
  784. // create the ggml context
  785. {
  786. lctx.model.buf.resize(ctx_size);
  787. if (use_mlock) {
  788. lctx.model.mlock_buf.init(lctx.model.buf.addr);
  789. lctx.model.mlock_buf.grow_to(lctx.model.buf.size);
  790. }
  791. struct ggml_init_params params = {
  792. /*.mem_size =*/ lctx.model.buf.size,
  793. /*.mem_buffer =*/ lctx.model.buf.addr,
  794. /*.no_alloc =*/ ml->use_mmap,
  795. };
  796. model.ctx = ggml_init(params);
  797. if (!model.ctx) {
  798. throw format("ggml_init() failed");
  799. }
  800. }
  801. // prepare memory for the weights
  802. {
  803. const auto & hparams = model.hparams;
  804. const uint32_t n_embd = hparams.n_embd;
  805. const uint32_t n_layer = hparams.n_layer;
  806. const uint32_t n_vocab = hparams.n_vocab;
  807. ml->ggml_ctx = ctx;
  808. model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab});
  809. model.norm = ml->get_tensor("norm.weight", {n_embd});
  810. model.output = ml->get_tensor("output.weight", {n_embd, n_vocab});
  811. model.layers.resize(n_layer);
  812. for (uint32_t i = 0; i < n_layer; ++i) {
  813. auto & layer = model.layers[i];
  814. std::string layers_i = "layers." + std::to_string(i);
  815. layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd});
  816. layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd});
  817. layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd});
  818. layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd});
  819. layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd});
  820. layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd});
  821. layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  822. layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  823. layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  824. }
  825. }
  826. ml->done_getting_tensors();
  827. // populate `tensors_by_name`
  828. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  829. model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
  830. }
  831. ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &lctx.model.mlock_mmap : NULL);
  832. model.mapping = std::move(ml->mapping);
  833. // loading time will be recalculate after the first eval, so
  834. // we take page faults deferred by mmap() into consideration
  835. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  836. }
  837. static bool llama_model_load(
  838. const std::string & fname,
  839. llama_context & lctx,
  840. int n_ctx,
  841. ggml_type memory_type,
  842. bool use_mmap,
  843. bool use_mlock,
  844. bool vocab_only,
  845. llama_progress_callback progress_callback,
  846. void *progress_callback_user_data) {
  847. try {
  848. llama_model_load_internal(fname, lctx, n_ctx, memory_type, use_mmap, use_mlock,
  849. vocab_only, progress_callback, progress_callback_user_data);
  850. return true;
  851. } catch (const std::string & err) {
  852. fprintf(stderr, "error loading model: %s\n", err.c_str());
  853. return false;
  854. }
  855. }
  856. // evaluate the transformer
  857. //
  858. // - lctx: llama context
  859. // - tokens: new batch of tokens to process
  860. // - n_past: the context size so far
  861. // - n_threads: number of threads to use
  862. //
  863. static bool llama_eval_internal(
  864. llama_context & lctx,
  865. const llama_token * tokens,
  866. const int n_tokens,
  867. const int n_past,
  868. const int n_threads) {
  869. const int64_t t_start_us = ggml_time_us();
  870. const int N = n_tokens;
  871. const auto & model = lctx.model;
  872. const auto & hparams = model.hparams;
  873. auto & kv_self = model.kv_self;
  874. LLAMA_ASSERT(!!kv_self.ctx);
  875. const int n_embd = hparams.n_embd;
  876. const int n_layer = hparams.n_layer;
  877. const int n_ctx = hparams.n_ctx;
  878. const int n_head = hparams.n_head;
  879. const int n_vocab = hparams.n_vocab;
  880. const int n_rot = hparams.n_embd/hparams.n_head;
  881. auto & mem_per_token = lctx.mem_per_token;
  882. auto & buf_compute = lctx.buf_compute;
  883. struct ggml_init_params params = {
  884. /*.mem_size =*/ buf_compute.size,
  885. /*.mem_buffer =*/ buf_compute.addr,
  886. /*.no_alloc =*/ false,
  887. };
  888. struct ggml_context * ctx0 = ggml_init(params);
  889. // for big prompts, if BLAS is enabled, it is better to use only one thread
  890. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  891. ggml_cgraph gf = {};
  892. gf.n_threads = N >= 32 && ggml_cpu_has_blas() ? 1 : n_threads;
  893. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  894. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  895. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  896. for (int il = 0; il < n_layer; ++il) {
  897. struct ggml_tensor * inpSA = inpL;
  898. struct ggml_tensor * cur;
  899. lctx.use_buf(ctx0, 0);
  900. // norm
  901. {
  902. cur = ggml_rms_norm(ctx0, inpL);
  903. // cur = attention_norm*cur
  904. cur = ggml_mul(ctx0,
  905. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  906. cur);
  907. }
  908. // self-attention
  909. {
  910. // compute Q and K and RoPE them
  911. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  912. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  913. // store key and value to memory
  914. {
  915. // compute the transposed [N, n_embd] V matrix
  916. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), n_embd, N));
  917. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
  918. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  919. ( n_ctx)*ggml_element_size(kv_self.v),
  920. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  921. // important: storing RoPE-ed version of K in the KV cache!
  922. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  923. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  924. }
  925. struct ggml_tensor * Q =
  926. ggml_permute(ctx0,
  927. Qcur,
  928. 0, 2, 1, 3);
  929. struct ggml_tensor * K =
  930. ggml_permute(ctx0,
  931. ggml_reshape_3d(ctx0,
  932. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  933. n_embd/n_head, n_head, n_past + N),
  934. 0, 2, 1, 3);
  935. // K * Q
  936. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  937. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  938. struct ggml_tensor * KQ_scaled =
  939. ggml_scale(ctx0,
  940. KQ,
  941. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  942. // KQ_masked = mask_past(KQ_scaled)
  943. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  944. // KQ = soft_max(KQ_masked)
  945. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  946. // split cached V into n_head heads
  947. struct ggml_tensor * V =
  948. ggml_view_3d(ctx0, kv_self.v,
  949. n_past + N, n_embd/n_head, n_head,
  950. n_ctx*ggml_element_size(kv_self.v),
  951. n_ctx*ggml_element_size(kv_self.v)*n_embd/n_head,
  952. il*n_ctx*ggml_element_size(kv_self.v)*n_embd);
  953. #if 1
  954. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  955. #else
  956. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  957. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  958. // is there a better way?
  959. struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd/n_head, n_head));
  960. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  961. #endif
  962. // KQV_merged = KQV.permute(0, 2, 1, 3)
  963. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  964. // cur = KQV_merged.contiguous().view(n_embd, N)
  965. cur = ggml_cpy(ctx0,
  966. KQV_merged,
  967. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  968. // projection (no bias)
  969. cur = ggml_mul_mat(ctx0,
  970. model.layers[il].wo,
  971. cur);
  972. }
  973. lctx.use_buf(ctx0, 1);
  974. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  975. // feed-forward network
  976. {
  977. // norm
  978. {
  979. cur = ggml_rms_norm(ctx0, inpFF);
  980. // cur = ffn_norm*cur
  981. cur = ggml_mul(ctx0,
  982. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  983. cur);
  984. }
  985. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  986. model.layers[il].w3,
  987. cur);
  988. cur = ggml_mul_mat(ctx0,
  989. model.layers[il].w1,
  990. cur);
  991. // SILU activation
  992. cur = ggml_silu(ctx0, cur);
  993. cur = ggml_mul(ctx0, cur, tmp);
  994. cur = ggml_mul_mat(ctx0,
  995. model.layers[il].w2,
  996. cur);
  997. }
  998. cur = ggml_add(ctx0, cur, inpFF);
  999. // input for next layer
  1000. inpL = cur;
  1001. }
  1002. lctx.use_buf(ctx0, 0);
  1003. // used at the end to optionally extract the embeddings
  1004. struct ggml_tensor * embeddings = NULL;
  1005. // norm
  1006. {
  1007. inpL = ggml_rms_norm(ctx0, inpL);
  1008. // inpL = norm*inpL
  1009. inpL = ggml_mul(ctx0,
  1010. ggml_repeat(ctx0, model.norm, inpL),
  1011. inpL);
  1012. embeddings = inpL;
  1013. }
  1014. // lm_head
  1015. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  1016. lctx.use_buf(ctx0, -1);
  1017. // logits -> probs
  1018. //inpL = ggml_soft_max(ctx0, inpL);
  1019. // run the computation
  1020. ggml_build_forward_expand(&gf, inpL);
  1021. ggml_graph_compute (ctx0, &gf);
  1022. // print timing information per ggml operation (for debugging purposes)
  1023. // requires GGML_PERF to be defined
  1024. //ggml_graph_print(&gf);
  1025. // plot the computation graph in dot format (for debugging purposes)
  1026. //if (n_past%100 == 0) {
  1027. // ggml_graph_dump_dot(&gf, NULL, "llama.dot");
  1028. //}
  1029. //embd_w.resize(n_vocab*N);
  1030. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1031. // extract logits
  1032. {
  1033. auto & logits_out = lctx.logits;
  1034. if (lctx.logits_all) {
  1035. logits_out.resize(n_vocab * N);
  1036. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1037. } else {
  1038. // return result for just the last token
  1039. logits_out.resize(n_vocab);
  1040. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1041. }
  1042. }
  1043. // extract embeddings
  1044. if (lctx.embedding.size()) {
  1045. auto & embedding_out = lctx.embedding;
  1046. embedding_out.resize(n_embd);
  1047. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1048. }
  1049. if (mem_per_token == 0) {
  1050. mem_per_token = ggml_used_mem(ctx0)/N;
  1051. }
  1052. #if 0
  1053. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  1054. ggml_used_mem(ctx0)/1024.0/1024.0,
  1055. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  1056. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  1057. #endif
  1058. ggml_free(ctx0);
  1059. // measure the performance only for the single-token evals
  1060. if (N == 1) {
  1061. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1062. lctx.n_eval++;
  1063. }
  1064. else if (N > 1) {
  1065. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1066. lctx.n_p_eval += N;
  1067. }
  1068. return true;
  1069. }
  1070. //
  1071. // tokenizer
  1072. //
  1073. static size_t utf8_len(char src) {
  1074. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1075. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1076. return lookup[highbits];
  1077. }
  1078. struct llama_sp_symbol {
  1079. using index = int;
  1080. index prev;
  1081. index next;
  1082. const char * text;
  1083. size_t n;
  1084. };
  1085. struct llama_sp_bigram {
  1086. struct comparator {
  1087. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1088. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1089. }
  1090. };
  1091. using queue_storage = std::vector<llama_sp_bigram>;
  1092. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1093. llama_sp_symbol::index left;
  1094. llama_sp_symbol::index right;
  1095. float score;
  1096. size_t size;
  1097. };
  1098. // original implementation:
  1099. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1100. struct llama_tokenizer {
  1101. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1102. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1103. // split string into utf8 chars
  1104. int index = 0;
  1105. size_t offs = 0;
  1106. while (offs < text.size()) {
  1107. llama_sp_symbol sym;
  1108. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  1109. sym.text = text.c_str() + offs;
  1110. sym.n = char_len;
  1111. offs += char_len;
  1112. sym.prev = index - 1;
  1113. sym.next = offs == text.size() ? -1 : index + 1;
  1114. index++;
  1115. symbols_.emplace_back(std::move(sym));
  1116. }
  1117. // seed the work queue with all possible 2-character tokens.
  1118. for (size_t i = 1; i < symbols_.size(); ++i) {
  1119. try_add_bigram(i - 1, i);
  1120. }
  1121. // keep substituting the highest frequency pairs for as long as we can.
  1122. while (!work_queue_.empty()) {
  1123. auto bigram = work_queue_.top();
  1124. work_queue_.pop();
  1125. auto & left_sym = symbols_[bigram.left];
  1126. auto & right_sym = symbols_[bigram.right];
  1127. // if one of the symbols already got merged, skip it.
  1128. if (left_sym.n == 0 || right_sym.n == 0 ||
  1129. left_sym.n + right_sym.n != bigram.size) {
  1130. continue;
  1131. }
  1132. // merge the right sym into the left one
  1133. left_sym.n += right_sym.n;
  1134. right_sym.n = 0;
  1135. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1136. // remove the right sym from the chain
  1137. left_sym.next = right_sym.next;
  1138. if (right_sym.next >= 0) {
  1139. symbols_[right_sym.next].prev = bigram.left;
  1140. }
  1141. // find more substitutions
  1142. try_add_bigram(left_sym.prev, bigram.left);
  1143. try_add_bigram(bigram.left, left_sym.next);
  1144. }
  1145. for (int i = 0; i != -1; i = symbols_[i].next) {
  1146. auto & symbol = symbols_[i];
  1147. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  1148. if (token == vocab_.token_to_id.end()) {
  1149. // output any symbols that did not form tokens as bytes.
  1150. for (int j = 0; j < (int) symbol.n; ++j) {
  1151. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  1152. output.push_back(token_id);
  1153. }
  1154. } else {
  1155. output.push_back((*token).second);
  1156. }
  1157. }
  1158. }
  1159. private:
  1160. void try_add_bigram(int left, int right) {
  1161. if (left == -1 || right == -1) {
  1162. return;
  1163. }
  1164. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1165. auto token = vocab_.token_to_id.find(text);
  1166. if (token == vocab_.token_to_id.end()) {
  1167. return;
  1168. }
  1169. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1170. return;
  1171. }
  1172. const auto &tok_score = vocab_.id_to_token[(*token).second];
  1173. llama_sp_bigram bigram;
  1174. bigram.left = left;
  1175. bigram.right = right;
  1176. bigram.score = tok_score.score;
  1177. bigram.size = text.size();
  1178. work_queue_.push(bigram);
  1179. }
  1180. const llama_vocab & vocab_;
  1181. std::vector<llama_sp_symbol> symbols_;
  1182. llama_sp_bigram::queue work_queue_;
  1183. };
  1184. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  1185. llama_tokenizer tokenizer(vocab);
  1186. std::vector<llama_vocab::id> output;
  1187. if (text.size() == 0) {
  1188. return output;
  1189. }
  1190. if (bos) {
  1191. output.push_back(1);
  1192. }
  1193. tokenizer.tokenize(text, output);
  1194. return output;
  1195. }
  1196. //
  1197. // sampling
  1198. //
  1199. static void sample_top_k(std::vector<std::pair<float, llama_vocab::id>> & logits_id, int top_k) {
  1200. // find the top k tokens
  1201. std::partial_sort(
  1202. logits_id.begin(),
  1203. logits_id.begin() + top_k, logits_id.end(),
  1204. [](const std::pair<float, llama_vocab::id> & a, const std::pair<float, llama_vocab::id> & b) {
  1205. return a.first > b.first;
  1206. });
  1207. logits_id.resize(top_k);
  1208. }
  1209. static llama_vocab::id llama_sample_top_p_top_k(
  1210. llama_context & lctx,
  1211. const std::vector<llama_vocab::id> & last_n_tokens,
  1212. int top_k,
  1213. float top_p,
  1214. float temp,
  1215. float repeat_penalty) {
  1216. auto & rng = lctx.rng;
  1217. const int n_logits = lctx.model.hparams.n_vocab;
  1218. const auto & logits = lctx.logits;
  1219. const auto * plogits = logits.data() + logits.size() - n_logits;
  1220. if (temp <= 0) {
  1221. // select the token with the highest logit directly
  1222. float max_logit = plogits[0];
  1223. llama_vocab::id max_id = 0;
  1224. for (int i = 1; i < n_logits; ++i) {
  1225. if (plogits[i] > max_logit) {
  1226. max_logit = plogits[i];
  1227. max_id = i;
  1228. }
  1229. }
  1230. return max_id;
  1231. }
  1232. std::vector<std::pair<float, llama_vocab::id>> logits_id;
  1233. logits_id.reserve(n_logits);
  1234. {
  1235. const float scale = 1.0f/temp;
  1236. for (int i = 0; i < n_logits; ++i) {
  1237. // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
  1238. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  1239. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  1240. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  1241. if (plogits[i] < 0.0f) {
  1242. logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
  1243. } else {
  1244. logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
  1245. }
  1246. } else {
  1247. logits_id.push_back(std::make_pair(plogits[i]*scale, i));
  1248. }
  1249. }
  1250. }
  1251. sample_top_k(logits_id, top_k > 0 ? std::min(top_k, n_logits) : n_logits);
  1252. // compute probs for the top k tokens
  1253. std::vector<float> probs;
  1254. probs.reserve(logits_id.size());
  1255. float maxl = logits_id[0].first;
  1256. double sum = 0.0;
  1257. for (const auto & kv : logits_id) {
  1258. const float p = expf(kv.first - maxl);
  1259. probs.push_back(p);
  1260. sum += p;
  1261. }
  1262. // normalize the probs
  1263. for (auto & p : probs) {
  1264. p /= sum;
  1265. }
  1266. if (top_p < 1.0) {
  1267. double cumsum = 0.0;
  1268. for (int i = 0; i < (int) probs.size(); i++) {
  1269. cumsum += probs[i];
  1270. if (cumsum >= top_p) {
  1271. probs.resize(i + 1);
  1272. logits_id.resize(i + 1);
  1273. break;
  1274. }
  1275. }
  1276. }
  1277. //printf("\n");
  1278. //for (int i = 0; i < (int) 10; i++) {
  1279. // printf("%d: '%s' %f\n", i, lctx.vocab.id_to_token.at(logits_id[i].second).tok.c_str(), probs[i]);
  1280. //}
  1281. //printf("\n\n");
  1282. //exit(0);
  1283. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1284. int idx = dist(rng);
  1285. return logits_id[idx].second;
  1286. }
  1287. //
  1288. // quantization
  1289. //
  1290. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, enum llama_ftype ftype) {
  1291. ggml_type quantized_type;
  1292. switch (ftype) {
  1293. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  1294. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  1295. default: throw format("invalid output file type %d\n", ftype);
  1296. };
  1297. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp.c_str(), /*use_mmap*/ false,
  1298. /*vocab_only*/ false));
  1299. llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loaders.at(0).get(), ftype);
  1300. size_t total_size_org = 0;
  1301. size_t total_size_new = 0;
  1302. std::vector<int64_t> hist_all(1 << 4, 0);
  1303. size_t idx = 0;
  1304. for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
  1305. llama_buffer read_data;
  1306. read_data.resize(tensor.size);
  1307. tensor.data = read_data.addr;
  1308. model_loader->load_data_for(tensor);
  1309. printf("[%zu/%zu] %36s - %s, type = %6s, ",
  1310. ++idx, model_loader->tensors_map.tensors.size(),
  1311. tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
  1312. ggml_type_name(tensor.type));
  1313. // This used to be a regex, but <regex> has an extreme cost to compile times.
  1314. bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
  1315. // quantize only 2D tensors
  1316. quantize &= (tensor.ne.size() == 2);
  1317. enum ggml_type new_type;
  1318. void * new_data;
  1319. size_t new_size;
  1320. llama_buffer work;
  1321. if (!quantize) {
  1322. new_type = tensor.type;
  1323. new_data = tensor.data;
  1324. new_size = tensor.size;
  1325. printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
  1326. } else {
  1327. new_type = quantized_type;
  1328. float * f32_data;
  1329. size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
  1330. llama_buffer f32_conv_buf;
  1331. if (tensor.type == GGML_TYPE_F32) {
  1332. f32_data = (float *) tensor.data;
  1333. } else if (tensor.type == GGML_TYPE_F16) {
  1334. f32_conv_buf.resize(nelements * sizeof(float));
  1335. f32_data = (float *) f32_conv_buf.addr;
  1336. auto f16_data = (const ggml_fp16_t *) tensor.data;
  1337. for (size_t i = 0; i < nelements; i++) {
  1338. f32_data[i] = ggml_fp16_to_fp32(f16_data[i]);
  1339. }
  1340. } else {
  1341. throw format("type %s unsupported for integer quantization", ggml_type_name(tensor.type));
  1342. }
  1343. printf("quantizing .. ");
  1344. fflush(stdout);
  1345. work.resize(nelements * 4); // upper bound on size
  1346. new_data = work.addr;
  1347. std::vector<int64_t> hist_cur(1 << 4, 0);
  1348. switch (new_type) {
  1349. case GGML_TYPE_Q4_0:
  1350. {
  1351. new_size = ggml_quantize_q4_0(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
  1352. } break;
  1353. case GGML_TYPE_Q4_1:
  1354. {
  1355. new_size = ggml_quantize_q4_1(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
  1356. } break;
  1357. default:
  1358. LLAMA_ASSERT(false);
  1359. }
  1360. printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
  1361. for (size_t i = 0; i < hist_cur.size(); i++) {
  1362. hist_all[i] += hist_cur[i];
  1363. }
  1364. for (size_t i = 0; i < hist_cur.size(); i++) {
  1365. printf("%5.3f ", hist_cur[i] / float(nelements));
  1366. }
  1367. printf("\n");
  1368. }
  1369. total_size_org += tensor.size;
  1370. total_size_new += new_size;
  1371. file_saver.write_tensor(tensor, new_type, new_data, new_size);
  1372. }
  1373. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1374. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1375. {
  1376. int64_t sum_all = 0;
  1377. for (size_t i = 0; i < hist_all.size(); i++) {
  1378. sum_all += hist_all[i];
  1379. }
  1380. printf("%s: hist: ", __func__);
  1381. for (size_t i = 0; i < hist_all.size(); i++) {
  1382. printf("%5.3f ", hist_all[i] / float(sum_all));
  1383. }
  1384. printf("\n");
  1385. }
  1386. }
  1387. //
  1388. // interface implementation
  1389. //
  1390. struct llama_context * llama_init_from_file(
  1391. const char * path_model,
  1392. struct llama_context_params params) {
  1393. ggml_time_init();
  1394. llama_context * ctx = new llama_context;
  1395. if (params.seed <= 0) {
  1396. params.seed = time(NULL);
  1397. }
  1398. unsigned cur_percentage = 0;
  1399. if (params.progress_callback == NULL) {
  1400. params.progress_callback_user_data = &cur_percentage;
  1401. params.progress_callback = [](float progress, void * ctx) {
  1402. unsigned * cur_percentage_p = (unsigned *) ctx;
  1403. unsigned percentage = (unsigned) (100 * progress);
  1404. while (percentage > *cur_percentage_p) {
  1405. ++*cur_percentage_p;
  1406. fprintf(stderr, ".");
  1407. fflush(stderr);
  1408. if (percentage >= 100) {
  1409. fprintf(stderr, "\n");
  1410. }
  1411. }
  1412. };
  1413. }
  1414. ctx->rng = std::mt19937(params.seed);
  1415. ctx->logits_all = params.logits_all;
  1416. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1417. if (!llama_model_load(path_model, *ctx, params.n_ctx, memory_type,
  1418. params.use_mmap, params.use_mlock, params.vocab_only,
  1419. params.progress_callback, params.progress_callback_user_data)) {
  1420. fprintf(stderr, "%s: failed to load model\n", __func__);
  1421. llama_free(ctx);
  1422. return nullptr;
  1423. }
  1424. // reserve memory for context buffers
  1425. if (!params.vocab_only) {
  1426. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1427. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1428. llama_free(ctx);
  1429. return nullptr;
  1430. }
  1431. {
  1432. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1433. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1434. }
  1435. const auto & hparams = ctx->model.hparams;
  1436. // resized during inference
  1437. if (params.logits_all) {
  1438. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1439. } else {
  1440. ctx->logits.reserve(hparams.n_ctx);
  1441. }
  1442. if (params.embedding){
  1443. ctx->embedding.resize(hparams.n_embd);
  1444. }
  1445. ctx->buf_compute.resize(MEM_REQ_EVAL.at(ctx->model.type));
  1446. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0.at(ctx->model.type));
  1447. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1.at(ctx->model.type));
  1448. }
  1449. return ctx;
  1450. }
  1451. void llama_free(struct llama_context * ctx) {
  1452. delete ctx;
  1453. }
  1454. int llama_model_quantize(
  1455. const char * fname_inp,
  1456. const char * fname_out,
  1457. enum llama_ftype ftype) {
  1458. try {
  1459. llama_model_quantize_internal(fname_inp, fname_out, ftype);
  1460. return 0;
  1461. } catch (const std::string & err) {
  1462. fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.c_str());
  1463. return 1;
  1464. }
  1465. }
  1466. // Returns the KV cache that will contain the context for the
  1467. // ongoing prediction with the model.
  1468. const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
  1469. return ctx->model.kv_self.buf.addr;
  1470. }
  1471. // Returns the size of the KV cache
  1472. size_t llama_get_kv_cache_size(struct llama_context * ctx) {
  1473. return ctx->model.kv_self.buf.size;
  1474. }
  1475. int llama_get_kv_cache_token_count(struct llama_context * ctx) {
  1476. return ctx->model.kv_self.n;
  1477. }
  1478. // Sets the KV cache containing the current context for the model
  1479. void llama_set_kv_cache(
  1480. struct llama_context * ctx,
  1481. const uint8_t * kv_cache,
  1482. size_t n_size,
  1483. int n_token_count) {
  1484. // Make sure we have the same kv cache setup
  1485. LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
  1486. memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
  1487. ctx->model.kv_self.n = n_token_count;
  1488. }
  1489. int llama_eval(
  1490. struct llama_context * ctx,
  1491. const llama_token * tokens,
  1492. int n_tokens,
  1493. int n_past,
  1494. int n_threads) {
  1495. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  1496. fprintf(stderr, "%s: failed to eval\n", __func__);
  1497. return 1;
  1498. }
  1499. // get a more accurate load time, upon first eval
  1500. if (!ctx->has_evaluated_once) {
  1501. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  1502. ctx->has_evaluated_once = true;
  1503. }
  1504. return 0;
  1505. }
  1506. int llama_tokenize(
  1507. struct llama_context * ctx,
  1508. const char * text,
  1509. llama_token * tokens,
  1510. int n_max_tokens,
  1511. bool add_bos) {
  1512. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  1513. if (n_max_tokens < (int) res.size()) {
  1514. fprintf(stderr, "%s: too many tokens\n", __func__);
  1515. return -((int) res.size());
  1516. }
  1517. for (size_t i = 0; i < res.size(); i++) {
  1518. tokens[i] = res[i];
  1519. }
  1520. return res.size();
  1521. }
  1522. int llama_n_vocab(struct llama_context * ctx) {
  1523. return ctx->vocab.id_to_token.size();
  1524. }
  1525. int llama_n_ctx(struct llama_context * ctx) {
  1526. return ctx->model.hparams.n_ctx;
  1527. }
  1528. int llama_n_embd(struct llama_context * ctx) {
  1529. return ctx->model.hparams.n_embd;
  1530. }
  1531. float * llama_get_logits(struct llama_context * ctx) {
  1532. return ctx->logits.data();
  1533. }
  1534. float * llama_get_embeddings(struct llama_context * ctx) {
  1535. return ctx->embedding.data();
  1536. }
  1537. const char * llama_token_to_str(struct llama_context * ctx, llama_token token) {
  1538. if (token >= llama_n_vocab(ctx)) {
  1539. return nullptr;
  1540. }
  1541. return ctx->vocab.id_to_token[token].tok.c_str();
  1542. }
  1543. llama_token llama_token_bos() {
  1544. return 1;
  1545. }
  1546. llama_token llama_token_eos() {
  1547. return 2;
  1548. }
  1549. llama_token llama_sample_top_p_top_k(
  1550. llama_context * ctx,
  1551. const llama_token * last_n_tokens_data,
  1552. int last_n_tokens_size,
  1553. int top_k,
  1554. float top_p,
  1555. float temp,
  1556. float repeat_penalty) {
  1557. const int64_t t_start_sample_us = ggml_time_us();
  1558. llama_token result = 0;
  1559. // TODO: avoid this ...
  1560. const auto last_n_tokens = std::vector<llama_token>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_size);
  1561. result = llama_sample_top_p_top_k(
  1562. *ctx,
  1563. last_n_tokens,
  1564. top_k,
  1565. top_p,
  1566. temp,
  1567. repeat_penalty);
  1568. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1569. ctx->n_sample++;
  1570. return result;
  1571. }
  1572. void llama_print_timings(struct llama_context * ctx) {
  1573. const int64_t t_end_us = ggml_time_us();
  1574. const int32_t n_sample = std::max(1, ctx->n_sample);
  1575. const int32_t n_eval = std::max(1, ctx->n_eval);
  1576. const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
  1577. fprintf(stderr, "\n");
  1578. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0);
  1579. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_sample_us, n_sample, 1e-3 * ctx->t_sample_us / n_sample);
  1580. fprintf(stderr, "%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token)\n", __func__, 1e-3 * ctx->t_p_eval_us, n_p_eval, 1e-3 * ctx->t_p_eval_us / n_p_eval);
  1581. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_eval_us, n_eval, 1e-3 * ctx->t_eval_us / n_eval);
  1582. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0);
  1583. }
  1584. void llama_reset_timings(struct llama_context * ctx) {
  1585. ctx->t_start_us = ggml_time_us();
  1586. ctx->t_sample_us = ctx->n_sample = 0;
  1587. ctx->t_eval_us = ctx->n_eval = 0;
  1588. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  1589. }
  1590. const char * llama_print_system_info(void) {
  1591. static std::string s;
  1592. s = "";
  1593. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  1594. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  1595. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  1596. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  1597. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  1598. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  1599. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  1600. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  1601. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  1602. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  1603. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  1604. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  1605. return s.c_str();
  1606. }
  1607. // For internal test use
  1608. std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  1609. return ctx->model.tensors_by_name;
  1610. }