llama.cpp 63 KB

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