llama.cpp 73 KB

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