llama.cpp 63 KB

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