llama.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <cstdio>
  7. #endif
  8. #include "llama-util.h"
  9. #include "llama.h"
  10. #include "ggml.h"
  11. #ifdef GGML_USE_CUBLAS
  12. #include "ggml-cuda.h"
  13. #endif
  14. #include <array>
  15. #include <ctime>
  16. #include <cinttypes>
  17. #include <fstream>
  18. #include <random>
  19. #include <map>
  20. #include <unordered_map>
  21. #include <queue>
  22. #include <cassert>
  23. #include <cstring>
  24. #include <climits>
  25. #include <memory>
  26. #include <algorithm>
  27. #include <initializer_list>
  28. #include <thread>
  29. #include <atomic>
  30. #include <mutex>
  31. #include <sstream>
  32. #include <numeric>
  33. #define LLAMA_USE_SCRATCH
  34. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  35. // available llama models
  36. enum e_model {
  37. MODEL_UNKNOWN,
  38. MODEL_7B,
  39. MODEL_13B,
  40. MODEL_30B,
  41. MODEL_65B,
  42. };
  43. static const size_t MB = 1024*1024;
  44. // computed for n_ctx == 2048
  45. // TODO: dynamically determine these sizes
  46. // needs modifications in ggml
  47. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH0()
  48. {
  49. static std::map<e_model, size_t> k_sizes = {
  50. { MODEL_7B, 512ull * MB },
  51. { MODEL_13B, 512ull * MB },
  52. { MODEL_30B, 512ull * MB },
  53. { MODEL_65B, 1024ull * MB },
  54. };
  55. return k_sizes;
  56. }
  57. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH1()
  58. {
  59. static std::map<e_model, size_t> k_sizes = {
  60. { MODEL_7B, 512ull * MB },
  61. { MODEL_13B, 512ull * MB },
  62. { MODEL_30B, 512ull * MB },
  63. { MODEL_65B, 1024ull * MB },
  64. };
  65. return k_sizes;
  66. }
  67. // 2*n_embd*n_ctx*n_layer*sizeof(float16)
  68. static const std::map<e_model, size_t> & MEM_REQ_KV_SELF()
  69. {
  70. static std::map<e_model, size_t> k_sizes = {
  71. { MODEL_7B, 1026ull * MB },
  72. { MODEL_13B, 1608ull * MB },
  73. { MODEL_30B, 3124ull * MB },
  74. { MODEL_65B, 5120ull * MB },
  75. };
  76. return k_sizes;
  77. }
  78. // this is mostly needed for temporary mul_mat buffers to dequantize the data
  79. // not actually needed if BLAS is disabled
  80. static const std::map<e_model, size_t> & MEM_REQ_EVAL()
  81. {
  82. static std::map<e_model, size_t> k_sizes = {
  83. { MODEL_7B, 768ull * MB },
  84. { MODEL_13B, 1024ull * MB },
  85. { MODEL_30B, 1280ull * MB },
  86. { MODEL_65B, 1536ull * MB },
  87. };
  88. return k_sizes;
  89. }
  90. // default hparams (LLaMA 7B)
  91. struct llama_hparams {
  92. uint32_t n_vocab = 32000;
  93. uint32_t n_ctx = 512; // this is provided as user input?
  94. uint32_t n_embd = 4096;
  95. uint32_t n_mult = 256;
  96. uint32_t n_head = 32;
  97. uint32_t n_layer = 32;
  98. uint32_t n_rot = 64;
  99. enum llama_ftype ftype = LLAMA_FTYPE_MOSTLY_F16;
  100. bool operator!=(const llama_hparams & other) const {
  101. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams)));
  102. }
  103. };
  104. struct llama_layer {
  105. // normalization
  106. struct ggml_tensor * attention_norm;
  107. // attention
  108. struct ggml_tensor * wq;
  109. struct ggml_tensor * wk;
  110. struct ggml_tensor * wv;
  111. struct ggml_tensor * wo;
  112. // normalization
  113. struct ggml_tensor * ffn_norm;
  114. // ff
  115. struct ggml_tensor * w1;
  116. struct ggml_tensor * w2;
  117. struct ggml_tensor * w3;
  118. };
  119. struct llama_kv_cache {
  120. struct ggml_tensor * k;
  121. struct ggml_tensor * v;
  122. struct ggml_context * ctx = NULL;
  123. llama_ctx_buffer buf;
  124. int n; // number of tokens currently in the cache
  125. ~llama_kv_cache() {
  126. if (ctx) {
  127. ggml_free(ctx);
  128. }
  129. }
  130. };
  131. struct llama_model {
  132. e_model type = MODEL_UNKNOWN;
  133. llama_hparams hparams;
  134. struct ggml_tensor * tok_embeddings;
  135. struct ggml_tensor * norm;
  136. struct ggml_tensor * output;
  137. std::vector<llama_layer> layers;
  138. // context
  139. struct ggml_context * ctx = NULL;
  140. // key + value cache for the self attention
  141. // TODO: move to llama_state
  142. struct llama_kv_cache kv_self;
  143. // the model memory buffer
  144. llama_ctx_buffer buf;
  145. // model memory mapped file
  146. std::unique_ptr<llama_mmap> mapping;
  147. // objects representing data potentially being locked in memory
  148. llama_mlock mlock_buf;
  149. llama_mlock mlock_mmap;
  150. // for quantize-stats only
  151. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  152. ~llama_model() {
  153. if (ctx) {
  154. ggml_free(ctx);
  155. }
  156. }
  157. };
  158. struct llama_vocab {
  159. using id = int32_t;
  160. using token = std::string;
  161. struct token_score {
  162. token tok;
  163. float score;
  164. };
  165. std::unordered_map<token, id> token_to_id;
  166. std::vector<token_score> id_to_token;
  167. };
  168. struct llama_context {
  169. std::mt19937 rng;
  170. int64_t t_load_us = 0;
  171. int64_t t_start_us = 0;
  172. bool has_evaluated_once = false;
  173. int64_t t_sample_us = 0;
  174. int64_t t_eval_us = 0;
  175. int64_t t_p_eval_us = 0;
  176. int32_t n_sample = 0; // number of tokens sampled
  177. int32_t n_eval = 0; // number of eval calls
  178. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  179. llama_model model;
  180. llama_vocab vocab;
  181. size_t mem_per_token = 0;
  182. // decode output (2-dimensional array: [n_tokens][n_vocab])
  183. std::vector<float> logits;
  184. bool logits_all = false;
  185. // input embedding (1-dimensional array: [n_embd])
  186. std::vector<float> embedding;
  187. // memory buffers used to evaluate the model
  188. // TODO: move in llama_state
  189. llama_ctx_buffer buf_compute;
  190. llama_ctx_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  191. int buf_last = 0;
  192. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  193. void use_buf(struct ggml_context * ctx, int i) {
  194. #if defined(LLAMA_USE_SCRATCH)
  195. size_t last_size = 0;
  196. if (i == -1) {
  197. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  198. } else {
  199. auto & buf = buf_scratch[i];
  200. last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
  201. }
  202. if (buf_last >= 0) {
  203. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  204. }
  205. buf_last = i;
  206. #else
  207. (void) i;
  208. (void) ctx;
  209. #endif
  210. }
  211. size_t get_buf_max_mem(int i) const {
  212. #if defined(LLAMA_USE_SCRATCH)
  213. return buf_max_size[i];
  214. #else
  215. (void) i;
  216. return 0;
  217. #endif
  218. }
  219. };
  220. template <typename T>
  221. static T checked_mul(T a, T b) {
  222. T ret = a * b;
  223. if (a != 0 && ret / a != b) {
  224. throw format("overflow multiplying %llu * %llu",
  225. (unsigned long long) a, (unsigned long long) b);
  226. }
  227. return ret;
  228. }
  229. static size_t checked_div(size_t a, size_t b) {
  230. if (b == 0 || a % b != 0) {
  231. throw format("error dividing %zu / %zu", a, b);
  232. }
  233. return a / b;
  234. }
  235. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  236. char buf[256];
  237. snprintf(buf, sizeof(buf), "%5u", ne.at(0));
  238. for (size_t i = 1; i < ne.size(); i++) {
  239. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " x %5u", ne.at(i));
  240. }
  241. return buf;
  242. }
  243. static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
  244. size_t size = ggml_type_size(type);
  245. for (uint32_t dim : ne) {
  246. size = checked_mul<size_t>(size, dim);
  247. }
  248. return size / ggml_blck_size(type);
  249. }
  250. struct llama_load_tensor_shard {
  251. std::vector<uint32_t> ne;
  252. size_t size;
  253. enum ggml_type type;
  254. size_t file_idx;
  255. size_t file_off;
  256. void calc_size() {
  257. size = llama_calc_tensor_size(ne, type);
  258. }
  259. };
  260. enum llama_split_type {
  261. SPLIT_NONE,
  262. SPLIT_BY_COLUMNS,
  263. SPLIT_BY_ROWS
  264. };
  265. struct llama_load_tensor {
  266. std::vector<llama_load_tensor_shard> shards;
  267. std::string name;
  268. enum ggml_type type = GGML_TYPE_F32;
  269. llama_split_type split_type = SPLIT_NONE;
  270. std::vector<uint32_t> ne;
  271. size_t size;
  272. struct ggml_tensor * ggml_tensor = NULL;
  273. uint8_t * data;
  274. llama_load_tensor(const std::string & name) : name(name) {}
  275. void calc_all() {
  276. calc_type();
  277. calc_split_type();
  278. calc_ne();
  279. calc_size();
  280. }
  281. void calc_type() {
  282. const auto & first_shard = shards.at(0);
  283. for (const auto & shard : shards) {
  284. if (shard.type != first_shard.type) {
  285. throw format("inconsistent tensor shard type in '%s'", name.c_str());
  286. }
  287. }
  288. type = first_shard.type;
  289. }
  290. void calc_split_type() {
  291. if (shards.at(0).ne.size() == 1 || // 1D tensors are just duplicated in every file
  292. shards.size() == 1) { // only one file?
  293. split_type = SPLIT_NONE;
  294. } else if (name.find("tok_embeddings.") == 0 ||
  295. name.find(".attention.wo.weight") != std::string::npos ||
  296. name.find(".feed_forward.w2.weight") != std::string::npos) {
  297. split_type = SPLIT_BY_COLUMNS;
  298. } else {
  299. split_type = SPLIT_BY_ROWS;
  300. }
  301. }
  302. void calc_ne() {
  303. const auto & first_shard = shards.at(0);
  304. for (const auto & shard : shards) {
  305. if (shard.ne != first_shard.ne) {
  306. throw format("inconsistent tensor shard shape in '%s': first was %s, other was %s",
  307. name.c_str(), llama_format_tensor_shape(first_shard.ne).c_str(), llama_format_tensor_shape(shard.ne).c_str());
  308. }
  309. }
  310. ne = first_shard.ne;
  311. LLAMA_ASSERT(shards.size() <= UINT32_MAX);
  312. uint32_t n_shards = (uint32_t) shards.size();
  313. switch (split_type) {
  314. case SPLIT_NONE:
  315. ne = first_shard.ne;
  316. break;
  317. case SPLIT_BY_COLUMNS:
  318. ne = {checked_mul<uint32_t>(first_shard.ne[0], n_shards),
  319. first_shard.ne[1]};
  320. break;
  321. case SPLIT_BY_ROWS:
  322. ne = {first_shard.ne[0],
  323. checked_mul<uint32_t>(first_shard.ne[1], n_shards)};
  324. break;
  325. }
  326. }
  327. void calc_size() {
  328. size = llama_calc_tensor_size(ne, type);
  329. }
  330. };
  331. struct llama_load_tensors_map {
  332. // tensors is kept in a separate vector to preserve file order
  333. std::vector<llama_load_tensor> tensors;
  334. std::unordered_map<std::string, size_t> name_to_idx;
  335. };
  336. enum llama_file_version {
  337. LLAMA_FILE_VERSION_GGML,
  338. LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
  339. LLAMA_FILE_VERSION_GGJT_V1, // added padding
  340. LLAMA_FILE_VERSION_GGJT_V2, // changed quantization format
  341. LLAMA_FILE_VERSION_GGJT_V3, // changed Q4 and Q8 quantization format
  342. };
  343. struct llama_file_loader {
  344. llama_file file;
  345. llama_file_version file_version;
  346. llama_hparams hparams;
  347. llama_vocab vocab;
  348. llama_file_loader(const char * fname, size_t file_idx, llama_load_tensors_map & tensors_map)
  349. : file(fname, "rb") {
  350. fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
  351. read_magic();
  352. read_hparams();
  353. read_vocab();
  354. read_tensor_metadata(file_idx, tensors_map);
  355. }
  356. void read_magic() {
  357. uint32_t magic = file.read_u32();
  358. if (magic == LLAMA_FILE_MAGIC_GGML) {
  359. file_version = LLAMA_FILE_VERSION_GGML;
  360. return;
  361. }
  362. uint32_t version = file.read_u32();
  363. switch (magic) {
  364. case LLAMA_FILE_MAGIC_GGMF:
  365. switch (version) {
  366. case 1: file_version = LLAMA_FILE_VERSION_GGMF_V1; return;
  367. }
  368. break;
  369. case LLAMA_FILE_MAGIC_GGJT:
  370. switch (version) {
  371. case 1: file_version = LLAMA_FILE_VERSION_GGJT_V1; return;
  372. case 2: file_version = LLAMA_FILE_VERSION_GGJT_V2; return;
  373. case 3: file_version = LLAMA_FILE_VERSION_GGJT_V3; return;
  374. }
  375. }
  376. throw format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
  377. magic, version);
  378. }
  379. void read_hparams() {
  380. hparams.n_vocab = file.read_u32();
  381. hparams.n_embd = file.read_u32();
  382. hparams.n_mult = file.read_u32();
  383. hparams.n_head = file.read_u32();
  384. hparams.n_layer = file.read_u32();
  385. hparams.n_rot = file.read_u32();
  386. hparams.ftype = (enum llama_ftype) file.read_u32();
  387. }
  388. void read_vocab() {
  389. vocab.id_to_token.resize(hparams.n_vocab);
  390. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  391. uint32_t len = file.read_u32();
  392. std::string word = file.read_string(len);
  393. float score = 0.0f;
  394. if (file_version >= LLAMA_FILE_VERSION_GGMF_V1) {
  395. file.read_raw(&score, sizeof(score));
  396. }
  397. vocab.token_to_id[word] = i;
  398. auto & tok_score = vocab.id_to_token[i];
  399. tok_score.tok = std::move(word);
  400. tok_score.score = score;
  401. }
  402. }
  403. void read_tensor_metadata(size_t file_idx, llama_load_tensors_map & tensors_map) {
  404. while (file.tell() < file.size) {
  405. llama_load_tensor_shard shard;
  406. uint32_t n_dims = file.read_u32();
  407. uint32_t name_len = file.read_u32();
  408. shard.type = (enum ggml_type) file.read_u32();
  409. shard.ne.resize(n_dims);
  410. file.read_raw(shard.ne.data(), sizeof(shard.ne[0]) * n_dims);
  411. std::string name = file.read_string(name_len);
  412. if (n_dims < 1 || n_dims > 2) {
  413. throw format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims);
  414. }
  415. switch (shard.type) {
  416. case GGML_TYPE_F32:
  417. case GGML_TYPE_F16:
  418. case GGML_TYPE_Q4_0:
  419. case GGML_TYPE_Q4_1:
  420. case GGML_TYPE_Q5_0:
  421. case GGML_TYPE_Q5_1:
  422. case GGML_TYPE_Q8_0:
  423. break;
  424. default: {
  425. throw format("unrecognized tensor type %u\n", shard.type);
  426. }
  427. }
  428. if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
  429. // skip to the next multiple of 32 bytes
  430. file.seek(-static_cast<ptrdiff_t>(file.tell()) & 31, SEEK_CUR);
  431. }
  432. shard.file_idx = file_idx;
  433. shard.file_off = file.tell();
  434. shard.calc_size();
  435. file.seek(shard.size, SEEK_CUR);
  436. auto it = tensors_map.name_to_idx.find(name);
  437. size_t idx;
  438. if (it != tensors_map.name_to_idx.end()) {
  439. idx = it->second;
  440. } else {
  441. tensors_map.tensors.emplace_back(name);
  442. idx = tensors_map.tensors.size() - 1;
  443. tensors_map.name_to_idx.emplace(name, idx);
  444. }
  445. tensors_map.tensors.at(idx).shards.push_back(shard);
  446. }
  447. }
  448. };
  449. struct llama_file_saver {
  450. llama_file file;
  451. llama_file_loader * any_file_loader;
  452. llama_file_saver(const char * fname, llama_file_loader * any_file_loader, enum llama_ftype new_ftype)
  453. : file(fname, "wb"), any_file_loader(any_file_loader) {
  454. fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
  455. write_magic();
  456. write_hparams(new_ftype);
  457. write_vocab();
  458. }
  459. void write_magic() {
  460. file.write_u32(LLAMA_FILE_MAGIC); // magic
  461. file.write_u32(LLAMA_FILE_VERSION); // version
  462. }
  463. void write_hparams(enum llama_ftype new_ftype) {
  464. const llama_hparams & hparams = any_file_loader->hparams;
  465. file.write_u32(hparams.n_vocab);
  466. file.write_u32(hparams.n_embd);
  467. file.write_u32(hparams.n_mult);
  468. file.write_u32(hparams.n_head);
  469. file.write_u32(hparams.n_layer);
  470. file.write_u32(hparams.n_rot);
  471. file.write_u32(new_ftype);
  472. }
  473. void write_vocab() {
  474. if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
  475. fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
  476. }
  477. uint32_t n_vocab = any_file_loader->hparams.n_vocab;
  478. for (uint32_t i = 0; i < n_vocab; i++) {
  479. const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
  480. file.write_u32((uint32_t) token_score.tok.size());
  481. file.write_raw(token_score.tok.data(), token_score.tok.size());
  482. file.write_raw(&token_score.score, sizeof(token_score.score));
  483. }
  484. }
  485. void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
  486. switch (new_type) {
  487. case GGML_TYPE_F32:
  488. case GGML_TYPE_F16:
  489. case GGML_TYPE_Q4_0:
  490. case GGML_TYPE_Q4_1:
  491. case GGML_TYPE_Q5_0:
  492. case GGML_TYPE_Q5_1:
  493. case GGML_TYPE_Q8_0:
  494. break;
  495. default: LLAMA_ASSERT(false);
  496. }
  497. file.write_u32((uint32_t) tensor.ne.size());
  498. file.write_u32((uint32_t) tensor.name.size());
  499. file.write_u32(new_type);
  500. file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
  501. file.write_raw(tensor.name.data(), tensor.name.size());
  502. file.seek(-static_cast<ptrdiff_t>(file.tell()) & 31, SEEK_CUR);
  503. LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
  504. file.write_raw(new_data, new_size);
  505. }
  506. };
  507. struct llama_model_loader {
  508. std::vector<std::unique_ptr<llama_file_loader>> file_loaders;
  509. llama_load_tensors_map tensors_map;
  510. bool use_mmap;
  511. size_t num_ggml_tensors_created = 0;
  512. struct ggml_context * ggml_ctx = NULL;
  513. std::unique_ptr<llama_mmap> mapping;
  514. llama_model_loader(const std::string & fname_base, bool use_mmap, bool vocab_only) {
  515. auto * first_file = new llama_file_loader(fname_base.c_str(), 0, tensors_map);
  516. file_loaders.emplace_back(first_file);
  517. uint32_t n_parts = vocab_only ? 1 : guess_n_parts();
  518. for (uint32_t i = 1; i < n_parts; i++) {
  519. std::string fname = fname_base + "." + std::to_string(i);
  520. auto * ith_file = new llama_file_loader(fname.c_str(), i, tensors_map);
  521. file_loaders.emplace_back(ith_file);
  522. if (ith_file->hparams != first_file->hparams) {
  523. throw format("llama.cpp: hparams inconsistent between files");
  524. }
  525. }
  526. if (!llama_mmap::SUPPORTED) {
  527. use_mmap = false;
  528. }
  529. if (use_mmap && alignment_prevents_mmap()) {
  530. fprintf(stderr, "llama.cpp: can't use mmap because tensors are not aligned; convert to new format to avoid this\n");
  531. use_mmap = false;
  532. }
  533. this->use_mmap = use_mmap;
  534. for (llama_load_tensor & lt : tensors_map.tensors) {
  535. lt.calc_all();
  536. }
  537. }
  538. bool alignment_prevents_mmap() {
  539. for (const llama_load_tensor & lt : tensors_map.tensors) {
  540. for (const llama_load_tensor_shard & shard : lt.shards) {
  541. if (shard.file_off & 3) {
  542. return true;
  543. }
  544. }
  545. }
  546. return false;
  547. }
  548. uint32_t guess_n_parts() const {
  549. auto it = tensors_map.name_to_idx.find("tok_embeddings.weight");
  550. if (it == tensors_map.name_to_idx.end()) {
  551. throw std::string("missing tok_embeddings.weight");
  552. }
  553. const llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  554. return file_loaders.at(0)->hparams.n_embd / lt.shards.at(0).ne.at(0);
  555. }
  556. void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
  557. *ctx_size_p = *mmapped_size_p = 0;
  558. for (const llama_load_tensor & lt : tensors_map.tensors) {
  559. *ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  560. *(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size;
  561. }
  562. }
  563. struct ggml_tensor * get_tensor(const std::string & name, const std::vector<uint32_t> & ne, ggml_backend backend) {
  564. auto it = tensors_map.name_to_idx.find(name);
  565. if (it == tensors_map.name_to_idx.end()) {
  566. throw format("llama.cpp: tensor '%s' is missing from model", name.c_str());
  567. }
  568. llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  569. if (lt.ne != ne) {
  570. throw format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
  571. name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str());
  572. }
  573. return get_tensor_for(lt, backend);
  574. }
  575. struct ggml_tensor * get_tensor_for(llama_load_tensor & lt, ggml_backend backend) {
  576. struct ggml_tensor * tensor;
  577. if (lt.ne.size() == 2) {
  578. tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
  579. } else {
  580. LLAMA_ASSERT(lt.ne.size() == 1);
  581. tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
  582. }
  583. ggml_set_name(tensor, lt.name.c_str());
  584. LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
  585. tensor->backend = backend;
  586. lt.ggml_tensor = tensor;
  587. num_ggml_tensors_created++;
  588. return tensor;
  589. }
  590. void done_getting_tensors() const {
  591. if (num_ggml_tensors_created != tensors_map.tensors.size()) {
  592. throw std::string("llama.cpp: file contained more tensors than expected");
  593. }
  594. }
  595. void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  596. size_t data_size = 0;
  597. size_t prefetch_size = 0;
  598. for (const llama_load_tensor & lt : tensors_map.tensors) {
  599. data_size += lt.size;
  600. if (lt.ggml_tensor->backend == GGML_BACKEND_CPU) {
  601. prefetch_size += lt.size;
  602. }
  603. }
  604. if (use_mmap) {
  605. mapping.reset(new llama_mmap(&file_loaders.at(0)->file, prefetch_size));
  606. if (!lmlock) {
  607. // Don't call the callback since the actual loading will be lazy
  608. // and we can't measure it.
  609. progress_callback = NULL;
  610. }
  611. if (lmlock) {
  612. lmlock->init(mapping->addr);
  613. }
  614. }
  615. size_t done_size = 0;
  616. for (llama_load_tensor & lt : tensors_map.tensors) {
  617. if (lt.ggml_tensor->backend != GGML_BACKEND_CPU) {
  618. continue;
  619. }
  620. if (progress_callback) {
  621. progress_callback((float) done_size / data_size, progress_callback_user_data);
  622. }
  623. LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
  624. lt.data = (uint8_t *) lt.ggml_tensor->data;
  625. load_data_for(lt);
  626. lt.ggml_tensor->data = lt.data;
  627. done_size += lt.size;
  628. if (use_mmap && lmlock) {
  629. lmlock->grow_to(done_size);
  630. }
  631. }
  632. }
  633. void load_data_for(llama_load_tensor & lt) {
  634. if (use_mmap) {
  635. LLAMA_ASSERT(lt.shards.size() == 1);
  636. lt.data = (uint8_t *) mapping->addr + lt.shards.at(0).file_off;
  637. } else if (lt.split_type == SPLIT_NONE) {
  638. llama_file & file = file_loaders.at(lt.shards.at(0).file_idx)->file;
  639. file.seek(lt.shards.at(0).file_off, SEEK_SET);
  640. file.read_raw(lt.data, lt.size);
  641. } else if (lt.split_type == SPLIT_BY_ROWS) {
  642. size_t offset = 0;
  643. for (llama_load_tensor_shard & shard : lt.shards) {
  644. llama_file & file = file_loaders.at(shard.file_idx)->file;
  645. file.seek(shard.file_off, SEEK_SET);
  646. file.read_raw(lt.data + offset, shard.size);
  647. offset += shard.size;
  648. }
  649. LLAMA_ASSERT(offset == lt.size);
  650. } else if (lt.split_type == SPLIT_BY_COLUMNS) {
  651. // Let's load the data into temporary buffers to ensure the OS performs large loads.
  652. std::vector<llama_buffer> tmp_bufs(lt.shards.size());
  653. for (size_t i = 0; i < lt.shards.size(); i++) {
  654. llama_load_tensor_shard & shard = lt.shards.at(i);
  655. llama_file & file = file_loaders.at(shard.file_idx)->file;
  656. file.seek(shard.file_off, SEEK_SET);
  657. tmp_bufs.at(i).resize(shard.size);
  658. file.read_raw(tmp_bufs.at(i).addr, shard.size);
  659. }
  660. // Then reshape.
  661. size_t num_rows = lt.ne.at(1);
  662. size_t per_shard_row_size = lt.shards.at(0).size / num_rows;
  663. size_t out_offset = 0;
  664. for (size_t row = 0; row < num_rows; row++) {
  665. for (llama_buffer & tmp_buf : tmp_bufs) {
  666. memcpy(lt.data + out_offset,
  667. tmp_buf.addr + row * per_shard_row_size,
  668. per_shard_row_size);
  669. out_offset += per_shard_row_size;
  670. }
  671. }
  672. LLAMA_ASSERT(out_offset == lt.size);
  673. }
  674. if (0) {
  675. print_checksum(lt);
  676. }
  677. }
  678. static void print_checksum(llama_load_tensor & lt) {
  679. uint32_t sum = 0;
  680. for (size_t i = 0; i < lt.size; i++) {
  681. uint8_t byte = lt.data[i];
  682. sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
  683. }
  684. fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
  685. llama_format_tensor_shape(lt.ne).c_str(), lt.size);
  686. }
  687. };
  688. //
  689. // kv cache
  690. //
  691. static bool kv_cache_init(
  692. const struct llama_hparams & hparams,
  693. struct llama_kv_cache & cache,
  694. ggml_type wtype,
  695. int n_ctx) {
  696. const int n_embd = hparams.n_embd;
  697. const int n_layer = hparams.n_layer;
  698. const int64_t n_mem = n_layer*n_ctx;
  699. const int64_t n_elements = n_embd*n_mem;
  700. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  701. struct ggml_init_params params;
  702. params.mem_size = cache.buf.size;
  703. params.mem_buffer = cache.buf.addr;
  704. params.no_alloc = false;
  705. cache.ctx = ggml_init(params);
  706. if (!cache.ctx) {
  707. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  708. return false;
  709. }
  710. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  711. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  712. ggml_set_name(cache.k, "cache_k");
  713. ggml_set_name(cache.v, "cache_v");
  714. return true;
  715. }
  716. struct llama_context_params llama_context_default_params() {
  717. struct llama_context_params result = {
  718. /*.n_ctx =*/ 512,
  719. /*.gpu_layers =*/ 0,
  720. /*.seed =*/ -1,
  721. /*.f16_kv =*/ true,
  722. /*.logits_all =*/ false,
  723. /*.vocab_only =*/ false,
  724. /*.use_mmap =*/ true,
  725. /*.use_mlock =*/ false,
  726. /*.embedding =*/ false,
  727. /*.progress_callback =*/ nullptr,
  728. /*.progress_callback_user_data =*/ nullptr,
  729. };
  730. return result;
  731. }
  732. bool llama_mmap_supported() {
  733. return llama_mmap::SUPPORTED;
  734. }
  735. bool llama_mlock_supported() {
  736. return llama_mlock::SUPPORTED;
  737. }
  738. void llama_init_backend() {
  739. ggml_time_init();
  740. // needed to initialize f16 tables
  741. {
  742. struct ggml_init_params params = { 0, NULL, false };
  743. struct ggml_context * ctx = ggml_init(params);
  744. ggml_free(ctx);
  745. }
  746. }
  747. int64_t llama_time_us() {
  748. return ggml_time_us();
  749. }
  750. //
  751. // model loading
  752. //
  753. static const char *llama_file_version_name(llama_file_version version) {
  754. switch (version) {
  755. case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
  756. case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
  757. case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (pre #1405)";
  758. case LLAMA_FILE_VERSION_GGJT_V2: return "ggjt v2 (pre #1508)";
  759. case LLAMA_FILE_VERSION_GGJT_V3: return "ggjt v3 (latest)";
  760. }
  761. return "unknown";
  762. }
  763. static const char *llama_ftype_name(enum llama_ftype ftype) {
  764. switch (ftype) {
  765. case LLAMA_FTYPE_ALL_F32: return "all F32";
  766. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  767. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  768. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  769. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  770. return "mostly Q4_1, some F16";
  771. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  772. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  773. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  774. default: return "unknown, may not work";
  775. }
  776. }
  777. static const char *llama_model_type_name(e_model type) {
  778. switch (type) {
  779. case MODEL_7B: return "7B";
  780. case MODEL_13B: return "13B";
  781. case MODEL_30B: return "30B";
  782. case MODEL_65B: return "65B";
  783. default: LLAMA_ASSERT(false);
  784. }
  785. }
  786. static void llama_model_load_internal(
  787. const std::string & fname,
  788. llama_context & lctx,
  789. int n_ctx,
  790. int n_gpu_layers,
  791. ggml_type memory_type,
  792. bool use_mmap,
  793. bool use_mlock,
  794. bool vocab_only,
  795. llama_progress_callback progress_callback,
  796. void * progress_callback_user_data) {
  797. lctx.t_start_us = ggml_time_us();
  798. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap, vocab_only));
  799. lctx.vocab = std::move(ml->file_loaders.at(0)->vocab);
  800. auto & model = lctx.model;
  801. model.hparams = ml->file_loaders.at(0)->hparams;
  802. llama_file_version file_version = ml->file_loaders.at(0)->file_version;
  803. auto & hparams = model.hparams;
  804. uint32_t n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  805. {
  806. switch (hparams.n_layer) {
  807. case 32: model.type = e_model::MODEL_7B; break;
  808. case 40: model.type = e_model::MODEL_13B; break;
  809. case 60: model.type = e_model::MODEL_30B; break;
  810. case 80: model.type = e_model::MODEL_65B; break;
  811. }
  812. hparams.n_ctx = n_ctx;
  813. }
  814. {
  815. fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
  816. fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  817. fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  818. fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
  819. fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
  820. fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
  821. fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
  822. fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot);
  823. fprintf(stderr, "%s: ftype = %u (%s)\n", __func__, hparams.ftype, llama_ftype_name(hparams.ftype));
  824. fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
  825. fprintf(stderr, "%s: n_parts = %zu\n", __func__, ml->file_loaders.size());
  826. fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
  827. }
  828. if (file_version < LLAMA_FILE_VERSION_GGJT_V2) {
  829. if (hparams.ftype != LLAMA_FTYPE_ALL_F32 &&
  830. hparams.ftype != LLAMA_FTYPE_MOSTLY_F16 &&
  831. hparams.ftype != LLAMA_FTYPE_MOSTLY_Q8_0) {
  832. throw format("this format is no longer supported (see https://github.com/ggerganov/llama.cpp/pull/1405)");
  833. }
  834. }
  835. if (file_version < LLAMA_FILE_VERSION_GGJT_V3) {
  836. if (hparams.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  837. hparams.ftype == LLAMA_FTYPE_MOSTLY_Q4_1 ||
  838. hparams.ftype == LLAMA_FTYPE_MOSTLY_Q8_0) {
  839. throw format("this format is no longer supported (see https://github.com/ggerganov/llama.cpp/pull/1508)");
  840. }
  841. }
  842. if (vocab_only) {
  843. return;
  844. }
  845. auto & ctx = model.ctx;
  846. size_t ctx_size;
  847. size_t mmapped_size;
  848. ml->calc_sizes(&ctx_size, &mmapped_size);
  849. fprintf(stderr, "%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  850. // create the ggml context
  851. {
  852. lctx.model.buf.resize(ctx_size);
  853. if (use_mlock) {
  854. lctx.model.mlock_buf.init(lctx.model.buf.addr);
  855. lctx.model.mlock_buf.grow_to(lctx.model.buf.size);
  856. }
  857. struct ggml_init_params params = {
  858. /*.mem_size =*/ lctx.model.buf.size,
  859. /*.mem_buffer =*/ lctx.model.buf.addr,
  860. /*.no_alloc =*/ ml->use_mmap,
  861. };
  862. model.ctx = ggml_init(params);
  863. if (!model.ctx) {
  864. throw format("ggml_init() failed");
  865. }
  866. }
  867. #ifdef GGML_USE_CUBLAS
  868. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CUDA
  869. #else
  870. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  871. #endif
  872. // prepare memory for the weights
  873. size_t vram_total = 0;
  874. {
  875. const uint32_t n_embd = hparams.n_embd;
  876. const uint32_t n_layer = hparams.n_layer;
  877. const uint32_t n_vocab = hparams.n_vocab;
  878. ml->ggml_ctx = ctx;
  879. model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab}, GGML_BACKEND_CPU);
  880. model.norm = ml->get_tensor("norm.weight", {n_embd}, GGML_BACKEND_CPU);
  881. // "output" tensor
  882. {
  883. ggml_backend backend_output;
  884. if (n_gpu_layers > int(n_layer)) { // NOLINT
  885. backend_output = LLAMA_BACKEND_OFFLOAD;
  886. } else {
  887. backend_output = GGML_BACKEND_CPU;
  888. }
  889. model.output = ml->get_tensor("output.weight", {n_embd, n_vocab}, backend_output);
  890. }
  891. const int i_gpu_start = n_layer - n_gpu_layers;
  892. model.layers.resize(n_layer);
  893. for (uint32_t i = 0; i < n_layer; ++i) {
  894. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  895. auto & layer = model.layers[i];
  896. std::string layers_i = "layers." + std::to_string(i);
  897. layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd}, backend);
  898. layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd}, backend);
  899. layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd}, backend);
  900. layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd}, backend);
  901. layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd}, backend);
  902. layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd}, backend);
  903. layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff}, backend);
  904. layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd}, backend);
  905. layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff}, backend);
  906. if (backend == GGML_BACKEND_CUDA) {
  907. vram_total +=
  908. ggml_nbytes(layer.attention_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  909. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.attention_norm) +
  910. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  911. }
  912. }
  913. }
  914. ml->done_getting_tensors();
  915. // print memory requirements
  916. {
  917. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  918. // this is the total memory required to run the inference
  919. const size_t mem_required =
  920. ctx_size +
  921. mmapped_size - vram_total + // weights in VRAM not in memory
  922. MEM_REQ_SCRATCH0().at(model.type) +
  923. MEM_REQ_SCRATCH1().at(model.type) +
  924. MEM_REQ_EVAL().at(model.type);
  925. // this is the memory required by one llama_state
  926. const size_t mem_required_state =
  927. scale*MEM_REQ_KV_SELF().at(model.type);
  928. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  929. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  930. #ifdef GGML_USE_CUBLAS
  931. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  932. fprintf(stderr, "%s: [cublas] offloading %d layers to GPU\n", __func__, n_gpu);
  933. if (n_gpu_layers > (int) hparams.n_layer) {
  934. fprintf(stderr, "%s: [cublas] offloading output layer to GPU\n", __func__);
  935. }
  936. fprintf(stderr, "%s: [cublas] total VRAM used: %zu MB\n", __func__, vram_total / 1024 / 1024);
  937. #else
  938. (void) n_gpu_layers;
  939. #endif
  940. }
  941. // populate `tensors_by_name`
  942. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  943. model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
  944. }
  945. ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &lctx.model.mlock_mmap : NULL);
  946. #ifdef GGML_USE_CUBLAS
  947. {
  948. size_t done_size = 0;
  949. size_t data_size = 0;
  950. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  951. data_size += lt.size;
  952. if (lt.ggml_tensor->backend == GGML_BACKEND_CPU) {
  953. done_size += lt.size;
  954. }
  955. }
  956. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  957. if (lt.ggml_tensor->backend != GGML_BACKEND_CUDA) {
  958. continue;
  959. }
  960. if (progress_callback) {
  961. progress_callback((float) done_size / data_size, progress_callback_user_data);
  962. }
  963. ggml_cuda_load_data(fname.c_str(), lt.ggml_tensor, lt.shards.at(0).file_off);
  964. done_size += lt.size;
  965. }
  966. }
  967. #endif // GGML_USE_CUBLAS
  968. if (progress_callback) {
  969. progress_callback(1.0f, progress_callback_user_data);
  970. }
  971. model.mapping = std::move(ml->mapping);
  972. // loading time will be recalculate after the first eval, so
  973. // we take page faults deferred by mmap() into consideration
  974. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  975. }
  976. static bool llama_model_load(
  977. const std::string & fname,
  978. llama_context & lctx,
  979. int n_ctx,
  980. int n_gpu_layers,
  981. ggml_type memory_type,
  982. bool use_mmap,
  983. bool use_mlock,
  984. bool vocab_only,
  985. llama_progress_callback progress_callback,
  986. void *progress_callback_user_data) {
  987. try {
  988. llama_model_load_internal(fname, lctx, n_ctx, n_gpu_layers, memory_type, use_mmap, use_mlock,
  989. vocab_only, progress_callback, progress_callback_user_data);
  990. return true;
  991. } catch (const std::string & err) {
  992. fprintf(stderr, "error loading model: %s\n", err.c_str());
  993. return false;
  994. }
  995. }
  996. // evaluate the transformer
  997. //
  998. // - lctx: llama context
  999. // - tokens: new batch of tokens to process
  1000. // - n_past: the context size so far
  1001. // - n_threads: number of threads to use
  1002. //
  1003. static bool llama_eval_internal(
  1004. llama_context & lctx,
  1005. const llama_token * tokens,
  1006. const int n_tokens,
  1007. const int n_past,
  1008. const int n_threads) {
  1009. // enforce that the first token is BOS
  1010. if (n_past == 0 && tokens[0] != llama_token_bos()) {
  1011. fprintf(stderr, "%s: first token must be BOS\n", __func__);
  1012. return false;
  1013. }
  1014. const int64_t t_start_us = ggml_time_us();
  1015. const int N = n_tokens;
  1016. const auto & model = lctx.model;
  1017. const auto & hparams = model.hparams;
  1018. const auto & kv_self = model.kv_self;
  1019. LLAMA_ASSERT(!!kv_self.ctx);
  1020. const int n_embd = hparams.n_embd;
  1021. const int n_layer = hparams.n_layer;
  1022. const int n_ctx = hparams.n_ctx;
  1023. const int n_head = hparams.n_head;
  1024. const int n_vocab = hparams.n_vocab;
  1025. const int n_rot = hparams.n_embd/hparams.n_head;
  1026. auto & mem_per_token = lctx.mem_per_token;
  1027. auto & buf_compute = lctx.buf_compute;
  1028. struct ggml_init_params params = {
  1029. /*.mem_size =*/ buf_compute.size,
  1030. /*.mem_buffer =*/ buf_compute.addr,
  1031. /*.no_alloc =*/ false,
  1032. };
  1033. struct ggml_context * ctx0 = ggml_init(params);
  1034. // for big prompts, if BLAS is enabled, it is better to use only one thread
  1035. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  1036. ggml_cgraph gf = {};
  1037. gf.n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  1038. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1039. ggml_set_name(embd, "embd");
  1040. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  1041. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  1042. for (int il = 0; il < n_layer; ++il) {
  1043. struct ggml_tensor * inpSA = inpL;
  1044. struct ggml_tensor * cur;
  1045. lctx.use_buf(ctx0, 0);
  1046. // norm
  1047. {
  1048. cur = ggml_rms_norm(ctx0, inpL);
  1049. // cur = cur*attention_norm(broadcasted)
  1050. cur = ggml_mul(ctx0, cur, model.layers[il].attention_norm);
  1051. }
  1052. // self-attention
  1053. {
  1054. // compute Q and K and RoPE them
  1055. struct ggml_tensor * Qcur = ggml_rope_inplace(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);
  1056. struct ggml_tensor * Kcur = ggml_rope_inplace(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);
  1057. ggml_set_name(Qcur, "Qcur");
  1058. ggml_set_name(Kcur, "Kcur");
  1059. // store key and value to memory
  1060. {
  1061. // compute the transposed [N, n_embd] V matrix
  1062. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), n_embd, N));
  1063. 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));
  1064. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  1065. ( n_ctx)*ggml_element_size(kv_self.v),
  1066. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  1067. // important: storing RoPE-ed version of K in the KV cache!
  1068. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  1069. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  1070. }
  1071. struct ggml_tensor * Q =
  1072. ggml_permute(ctx0,
  1073. Qcur,
  1074. 0, 2, 1, 3);
  1075. ggml_set_name(Q, "Q");
  1076. struct ggml_tensor * K =
  1077. ggml_permute(ctx0,
  1078. ggml_reshape_3d(ctx0,
  1079. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  1080. n_embd/n_head, n_head, n_past + N),
  1081. 0, 2, 1, 3);
  1082. ggml_set_name(K, "K");
  1083. // K * Q
  1084. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1085. ggml_set_name(KQ, "KQ");
  1086. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  1087. struct ggml_tensor * KQ_scale = ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head));
  1088. ggml_set_name(KQ_scale, "1/sqrt(n_embd/n_head)");
  1089. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1090. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1091. ggml_set_name(KQ_scaled, "KQ_scaled");
  1092. // KQ_masked = mask_past(KQ_scaled)
  1093. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1094. ggml_set_name(KQ_masked, "KQ_masked");
  1095. // KQ = soft_max(KQ_masked)
  1096. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1097. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1098. // split cached V into n_head heads
  1099. struct ggml_tensor * V =
  1100. ggml_view_3d(ctx0, kv_self.v,
  1101. n_past + N, n_embd/n_head, n_head,
  1102. n_ctx*ggml_element_size(kv_self.v),
  1103. n_ctx*ggml_element_size(kv_self.v)*n_embd/n_head,
  1104. il*n_ctx*ggml_element_size(kv_self.v)*n_embd);
  1105. ggml_set_name(V, "V");
  1106. #if 1
  1107. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1108. ggml_set_name(KQV, "KQV");
  1109. #else
  1110. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1111. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1112. // is there a better way?
  1113. 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));
  1114. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1115. #endif
  1116. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1117. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1118. ggml_set_name(KQV_merged, "KQV_merged");
  1119. // cur = KQV_merged.contiguous().view(n_embd, N)
  1120. cur = ggml_cpy(ctx0,
  1121. KQV_merged,
  1122. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1123. ggml_set_name(cur, "KQV_merged_contiguous");
  1124. // projection (no bias)
  1125. cur = ggml_mul_mat(ctx0,
  1126. model.layers[il].wo,
  1127. cur);
  1128. }
  1129. lctx.use_buf(ctx0, 1);
  1130. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1131. // feed-forward network
  1132. {
  1133. // norm
  1134. {
  1135. cur = ggml_rms_norm(ctx0, inpFF);
  1136. // cur = cur*ffn_norm(broadcasted)
  1137. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  1138. }
  1139. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1140. model.layers[il].w3,
  1141. cur);
  1142. cur = ggml_mul_mat(ctx0,
  1143. model.layers[il].w1,
  1144. cur);
  1145. // SILU activation
  1146. cur = ggml_silu(ctx0, cur);
  1147. cur = ggml_mul(ctx0, cur, tmp);
  1148. cur = ggml_mul_mat(ctx0,
  1149. model.layers[il].w2,
  1150. cur);
  1151. }
  1152. cur = ggml_add(ctx0, cur, inpFF);
  1153. // input for next layer
  1154. inpL = cur;
  1155. }
  1156. lctx.use_buf(ctx0, 0);
  1157. // used at the end to optionally extract the embeddings
  1158. struct ggml_tensor * embeddings = NULL;
  1159. // norm
  1160. {
  1161. inpL = ggml_rms_norm(ctx0, inpL);
  1162. // inpL = inpL*norm(broadcasted)
  1163. inpL = ggml_mul(ctx0, inpL, model.norm);
  1164. embeddings = inpL;
  1165. }
  1166. // lm_head
  1167. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  1168. lctx.use_buf(ctx0, -1);
  1169. // logits -> probs
  1170. //inpL = ggml_soft_max_inplace(ctx0, inpL);
  1171. // run the computation
  1172. ggml_build_forward_expand(&gf, inpL);
  1173. ggml_graph_compute (ctx0, &gf);
  1174. #ifdef GGML_PERF
  1175. // print timing information per ggml operation (for debugging purposes)
  1176. // requires GGML_PERF to be defined
  1177. ggml_graph_print(&gf);
  1178. #endif
  1179. // plot the computation graph in dot format (for debugging purposes)
  1180. //if (n_past%100 == 0) {
  1181. // ggml_graph_dump_dot(&gf, NULL, "llama.dot");
  1182. //}
  1183. //embd_w.resize(n_vocab*N);
  1184. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1185. // update kv token count
  1186. lctx.model.kv_self.n = n_past + N;
  1187. // extract logits
  1188. {
  1189. auto & logits_out = lctx.logits;
  1190. if (lctx.logits_all) {
  1191. logits_out.resize(n_vocab * N);
  1192. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1193. } else {
  1194. // return result for just the last token
  1195. logits_out.resize(n_vocab);
  1196. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1197. }
  1198. }
  1199. // extract embeddings
  1200. if (!lctx.embedding.empty()) {
  1201. auto & embedding_out = lctx.embedding;
  1202. embedding_out.resize(n_embd);
  1203. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1204. }
  1205. if (mem_per_token == 0) {
  1206. mem_per_token = ggml_used_mem(ctx0)/N;
  1207. }
  1208. #if 0
  1209. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  1210. ggml_used_mem(ctx0)/1024.0/1024.0,
  1211. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  1212. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  1213. #endif
  1214. ggml_free(ctx0);
  1215. // measure the performance only for the single-token evals
  1216. if (N == 1) {
  1217. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1218. lctx.n_eval++;
  1219. }
  1220. else if (N > 1) {
  1221. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1222. lctx.n_p_eval += N;
  1223. }
  1224. return true;
  1225. }
  1226. //
  1227. // tokenizer
  1228. //
  1229. static size_t utf8_len(char src) {
  1230. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1231. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1232. return lookup[highbits];
  1233. }
  1234. struct llama_sp_symbol {
  1235. using index = int;
  1236. index prev;
  1237. index next;
  1238. const char * text;
  1239. size_t n;
  1240. };
  1241. static_assert(std::is_trivially_copyable<llama_sp_symbol>::value, "llama_sp_symbol is not trivially copyable");
  1242. struct llama_sp_bigram {
  1243. struct comparator {
  1244. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1245. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1246. }
  1247. };
  1248. using queue_storage = std::vector<llama_sp_bigram>;
  1249. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1250. llama_sp_symbol::index left;
  1251. llama_sp_symbol::index right;
  1252. float score;
  1253. size_t size;
  1254. };
  1255. // original implementation:
  1256. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1257. struct llama_tokenizer {
  1258. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1259. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1260. // split string into utf8 chars
  1261. int index = 0;
  1262. size_t offs = 0;
  1263. while (offs < text.size()) {
  1264. llama_sp_symbol sym;
  1265. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  1266. sym.text = text.c_str() + offs;
  1267. sym.n = char_len;
  1268. offs += char_len;
  1269. sym.prev = index - 1;
  1270. sym.next = offs == text.size() ? -1 : index + 1;
  1271. index++;
  1272. symbols_.emplace_back(sym);
  1273. }
  1274. // seed the work queue with all possible 2-character tokens.
  1275. for (size_t i = 1; i < symbols_.size(); ++i) {
  1276. try_add_bigram(i - 1, i);
  1277. }
  1278. // keep substituting the highest frequency pairs for as long as we can.
  1279. while (!work_queue_.empty()) {
  1280. auto bigram = work_queue_.top();
  1281. work_queue_.pop();
  1282. auto & left_sym = symbols_[bigram.left];
  1283. auto & right_sym = symbols_[bigram.right];
  1284. // if one of the symbols already got merged, skip it.
  1285. if (left_sym.n == 0 || right_sym.n == 0 ||
  1286. left_sym.n + right_sym.n != bigram.size) {
  1287. continue;
  1288. }
  1289. // merge the right sym into the left one
  1290. left_sym.n += right_sym.n;
  1291. right_sym.n = 0;
  1292. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1293. // remove the right sym from the chain
  1294. left_sym.next = right_sym.next;
  1295. if (right_sym.next >= 0) {
  1296. symbols_[right_sym.next].prev = bigram.left;
  1297. }
  1298. // find more substitutions
  1299. try_add_bigram(left_sym.prev, bigram.left);
  1300. try_add_bigram(bigram.left, left_sym.next);
  1301. }
  1302. for (int i = 0; i != -1; i = symbols_[i].next) {
  1303. auto & symbol = symbols_[i];
  1304. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  1305. if (token == vocab_.token_to_id.end()) {
  1306. // output any symbols that did not form tokens as bytes.
  1307. for (int j = 0; j < (int) symbol.n; ++j) {
  1308. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  1309. output.push_back(token_id);
  1310. }
  1311. } else {
  1312. output.push_back((*token).second);
  1313. }
  1314. }
  1315. }
  1316. private:
  1317. void try_add_bigram(int left, int right) {
  1318. if (left == -1 || right == -1) {
  1319. return;
  1320. }
  1321. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1322. auto token = vocab_.token_to_id.find(text);
  1323. if (token == vocab_.token_to_id.end()) {
  1324. return;
  1325. }
  1326. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1327. return;
  1328. }
  1329. const auto &tok_score = vocab_.id_to_token[(*token).second];
  1330. llama_sp_bigram bigram;
  1331. bigram.left = left;
  1332. bigram.right = right;
  1333. bigram.score = tok_score.score;
  1334. bigram.size = text.size();
  1335. work_queue_.push(bigram);
  1336. }
  1337. const llama_vocab & vocab_;
  1338. std::vector<llama_sp_symbol> symbols_;
  1339. llama_sp_bigram::queue work_queue_;
  1340. };
  1341. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  1342. llama_tokenizer tokenizer(vocab);
  1343. std::vector<llama_vocab::id> output;
  1344. if (text.empty()) {
  1345. return output;
  1346. }
  1347. if (bos) {
  1348. output.push_back(llama_token_bos());
  1349. }
  1350. tokenizer.tokenize(text, output);
  1351. return output;
  1352. }
  1353. //
  1354. // sampling
  1355. //
  1356. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  1357. assert(candidates->size > 0);
  1358. const int64_t t_start_sample_us = ggml_time_us();
  1359. // Sort the logits in descending order
  1360. if (!candidates->sorted) {
  1361. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  1362. return a.logit > b.logit;
  1363. });
  1364. candidates->sorted = true;
  1365. }
  1366. float max_l = candidates->data[0].logit;
  1367. float cum_sum = 0.0f;
  1368. for (size_t i = 0; i < candidates->size; ++i) {
  1369. float p = expf(candidates->data[i].logit - max_l);
  1370. candidates->data[i].p = p;
  1371. cum_sum += p;
  1372. }
  1373. for (size_t i = 0; i < candidates->size; ++i) {
  1374. candidates->data[i].p /= cum_sum;
  1375. }
  1376. if (ctx) {
  1377. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1378. }
  1379. }
  1380. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  1381. const int64_t t_start_sample_us = ggml_time_us();
  1382. k = std::max(k, (int) min_keep);
  1383. k = std::min(k, (int) candidates->size);
  1384. // Sort scores in descending order
  1385. if (!candidates->sorted) {
  1386. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  1387. return a.logit > b.logit;
  1388. };
  1389. if (k == (int) candidates->size) {
  1390. std::sort(candidates->data, candidates->data + candidates->size, comp);
  1391. } else {
  1392. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  1393. }
  1394. candidates->sorted = true;
  1395. }
  1396. candidates->size = k;
  1397. if (ctx) {
  1398. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1399. }
  1400. }
  1401. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  1402. if (p >= 1.0f) {
  1403. return;
  1404. }
  1405. const int64_t t_start_sample_us = ggml_time_us();
  1406. llama_sample_softmax(ctx, candidates);
  1407. // Compute the cumulative probabilities
  1408. float cum_sum = 0.0f;
  1409. size_t last_idx = candidates->size;
  1410. for (size_t i = 0; i < candidates->size; ++i) {
  1411. cum_sum += candidates->data[i].p;
  1412. // Check if the running sum is greater than p or if we have kept at least min_keep tokens
  1413. if (cum_sum > p && i >= min_keep) {
  1414. last_idx = i;
  1415. break;
  1416. }
  1417. }
  1418. // Resize the output vector to keep only the top-p tokens
  1419. candidates->size = last_idx;
  1420. if (ctx) {
  1421. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1422. }
  1423. }
  1424. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  1425. if (z >= 1.0f || candidates->size <= 2) {
  1426. return;
  1427. }
  1428. const int64_t t_start_sample_us = ggml_time_us();
  1429. llama_sample_softmax(nullptr, candidates);
  1430. // Compute the first and second derivatives
  1431. std::vector<float> first_derivatives(candidates->size - 1);
  1432. std::vector<float> second_derivatives(candidates->size - 2);
  1433. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  1434. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  1435. }
  1436. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1437. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  1438. }
  1439. // Calculate absolute value of second derivatives
  1440. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1441. second_derivatives[i] = abs(second_derivatives[i]);
  1442. }
  1443. // Normalize the second derivatives
  1444. float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  1445. for (float & value : second_derivatives) {
  1446. value /= second_derivatives_sum;
  1447. }
  1448. float cum_sum = 0.0f;
  1449. size_t last_idx = candidates->size;
  1450. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1451. cum_sum += second_derivatives[i];
  1452. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  1453. if (cum_sum > z && i >= min_keep) {
  1454. last_idx = i;
  1455. break;
  1456. }
  1457. }
  1458. // Resize the output vector to keep only the tokens above the tail location
  1459. candidates->size = last_idx;
  1460. if (ctx) {
  1461. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1462. }
  1463. }
  1464. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  1465. // Reference implementation:
  1466. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  1467. if (p >= 1.0f) {
  1468. return;
  1469. }
  1470. const int64_t t_start_sample_us = ggml_time_us();
  1471. // Compute the softmax of logits and calculate entropy
  1472. llama_sample_softmax(nullptr, candidates);
  1473. float entropy = 0.0f;
  1474. for (size_t i = 0; i < candidates->size; ++i) {
  1475. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  1476. }
  1477. // Compute the absolute difference between negative log probability and entropy for each candidate
  1478. std::vector<float> shifted_scores;
  1479. for (size_t i = 0; i < candidates->size; ++i) {
  1480. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  1481. shifted_scores.push_back(shifted_score);
  1482. }
  1483. // Sort tokens based on the shifted_scores and their corresponding indices
  1484. std::vector<size_t> indices(candidates->size);
  1485. std::iota(indices.begin(), indices.end(), 0);
  1486. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  1487. return shifted_scores[a] < shifted_scores[b];
  1488. });
  1489. // Compute the cumulative probabilities
  1490. float cum_sum = 0.0f;
  1491. size_t last_idx = indices.size();
  1492. for (size_t i = 0; i < indices.size(); ++i) {
  1493. size_t idx = indices[i];
  1494. cum_sum += candidates->data[idx].p;
  1495. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  1496. if (cum_sum > p && i >= min_keep - 1) {
  1497. last_idx = i + 1;
  1498. break;
  1499. }
  1500. }
  1501. // Resize the output vector to keep only the locally typical tokens
  1502. std::vector<llama_token_data> new_candidates;
  1503. for (size_t i = 0; i < last_idx; ++i) {
  1504. size_t idx = indices[i];
  1505. new_candidates.push_back(candidates->data[idx]);
  1506. }
  1507. // Replace the data in candidates with the new_candidates data
  1508. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  1509. candidates->size = new_candidates.size();
  1510. if (ctx) {
  1511. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1512. }
  1513. }
  1514. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  1515. const int64_t t_start_sample_us = ggml_time_us();
  1516. for (size_t i = 0; i < candidates_p->size; ++i) {
  1517. candidates_p->data[i].logit /= temp;
  1518. }
  1519. if (ctx) {
  1520. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1521. }
  1522. }
  1523. void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty) {
  1524. if (last_tokens_size == 0 || penalty == 1.0f) {
  1525. return;
  1526. }
  1527. const int64_t t_start_sample_us = ggml_time_us();
  1528. for (size_t i = 0; i < candidates->size; ++i) {
  1529. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  1530. if (token_iter == last_tokens + last_tokens_size) {
  1531. continue;
  1532. }
  1533. // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
  1534. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  1535. if (candidates->data[i].logit <= 0) {
  1536. candidates->data[i].logit *= penalty;
  1537. } else {
  1538. candidates->data[i].logit /= penalty;
  1539. }
  1540. }
  1541. candidates->sorted = false;
  1542. if (ctx) {
  1543. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1544. }
  1545. }
  1546. void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens_p, size_t last_tokens_size, float alpha_frequency, float alpha_presence) {
  1547. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  1548. return;
  1549. }
  1550. const int64_t t_start_sample_us = ggml_time_us();
  1551. // Create a frequency map to count occurrences of each token in last_tokens
  1552. std::unordered_map<llama_token, int> token_count;
  1553. for (size_t i = 0; i < last_tokens_size; ++i) {
  1554. token_count[last_tokens_p[i]]++;
  1555. }
  1556. // Apply frequency and presence penalties to the candidates
  1557. for (size_t i = 0; i < candidates->size; ++i) {
  1558. auto token_iter = token_count.find(candidates->data[i].id);
  1559. if (token_iter == token_count.end()) {
  1560. continue;
  1561. }
  1562. int count = token_iter->second;
  1563. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  1564. }
  1565. candidates->sorted = false;
  1566. if (ctx) {
  1567. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1568. }
  1569. }
  1570. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  1571. assert(ctx);
  1572. auto N = float(llama_n_vocab(ctx));
  1573. int64_t t_start_sample_us;
  1574. t_start_sample_us = ggml_time_us();
  1575. llama_sample_softmax(nullptr, candidates);
  1576. // Estimate s_hat using the most probable m tokens
  1577. float s_hat = 0.0;
  1578. float sum_ti_bi = 0.0;
  1579. float sum_ti_sq = 0.0;
  1580. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  1581. float t_i = logf(float(i + 2) / float(i + 1));
  1582. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  1583. sum_ti_bi += t_i * b_i;
  1584. sum_ti_sq += t_i * t_i;
  1585. }
  1586. s_hat = sum_ti_bi / sum_ti_sq;
  1587. // Compute k from the estimated s_hat and target surprise value
  1588. float epsilon_hat = s_hat - 1;
  1589. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  1590. // Sample the next word X using top-k sampling
  1591. llama_sample_top_k(nullptr, candidates, int(k), 1);
  1592. if (ctx) {
  1593. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1594. }
  1595. llama_token X = llama_sample_token(ctx, candidates);
  1596. t_start_sample_us = ggml_time_us();
  1597. // Compute error as the difference between observed surprise and target surprise value
  1598. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1599. return candidate.id == X;
  1600. }));
  1601. float observed_surprise = -log2f(candidates->data[X_idx].p);
  1602. float e = observed_surprise - tau;
  1603. // Update mu using the learning rate and error
  1604. *mu = *mu - eta * e;
  1605. if (ctx) {
  1606. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1607. ctx->n_sample++;
  1608. }
  1609. return X;
  1610. }
  1611. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  1612. assert(ctx);
  1613. int64_t t_start_sample_us;
  1614. t_start_sample_us = ggml_time_us();
  1615. llama_sample_softmax(ctx, candidates);
  1616. // Truncate the words with surprise values greater than mu
  1617. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1618. return -log2f(candidate.p) > *mu;
  1619. }));
  1620. // Normalize the probabilities of the remaining words
  1621. llama_sample_softmax(ctx, candidates);
  1622. // Sample the next word X from the remaining words
  1623. if (ctx) {
  1624. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1625. }
  1626. llama_token X = llama_sample_token(ctx, candidates);
  1627. t_start_sample_us = ggml_time_us();
  1628. // Compute error as the difference between observed surprise and target surprise value
  1629. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1630. return candidate.id == X;
  1631. }));
  1632. float observed_surprise = -log2f(candidates->data[X_idx].p);
  1633. float e = observed_surprise - tau;
  1634. // Update mu using the learning rate and error
  1635. *mu = *mu - eta * e;
  1636. if (ctx) {
  1637. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1638. }
  1639. return X;
  1640. }
  1641. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  1642. const int64_t t_start_sample_us = ggml_time_us();
  1643. // Find max element
  1644. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  1645. return a.logit < b.logit;
  1646. });
  1647. llama_token result = max_iter->id;
  1648. if (ctx) {
  1649. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1650. ctx->n_sample++;
  1651. }
  1652. return result;
  1653. }
  1654. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  1655. assert(ctx);
  1656. const int64_t t_start_sample_us = ggml_time_us();
  1657. llama_sample_softmax(nullptr, candidates);
  1658. std::vector<float> probs;
  1659. probs.reserve(candidates->size);
  1660. for (size_t i = 0; i < candidates->size; ++i) {
  1661. probs.push_back(candidates->data[i].p);
  1662. }
  1663. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1664. auto & rng = ctx->rng;
  1665. int idx = dist(rng);
  1666. llama_token result = candidates->data[idx].id;
  1667. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1668. ctx->n_sample++;
  1669. return result;
  1670. }
  1671. //
  1672. // quantization
  1673. //
  1674. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, enum llama_ftype ftype, int nthread) {
  1675. ggml_type quantized_type;
  1676. switch (ftype) {
  1677. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  1678. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  1679. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  1680. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  1681. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  1682. default: throw format("invalid output file type %d\n", ftype);
  1683. };
  1684. if (nthread <= 0) {
  1685. nthread = std::thread::hardware_concurrency();
  1686. }
  1687. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp, /*use_mmap*/ false,
  1688. /*vocab_only*/ false));
  1689. llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loaders.at(0).get(), ftype);
  1690. size_t total_size_org = 0;
  1691. size_t total_size_new = 0;
  1692. std::vector<int64_t> hist_all(1 << 4, 0);
  1693. std::vector<std::thread> workers;
  1694. std::mutex mutex;
  1695. size_t idx = 0;
  1696. for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
  1697. llama_buffer read_data;
  1698. read_data.resize(tensor.size);
  1699. tensor.data = read_data.addr;
  1700. model_loader->load_data_for(tensor);
  1701. printf("[%4zu/%4zu] %36s - %16s, type = %6s, ",
  1702. ++idx, model_loader->tensors_map.tensors.size(),
  1703. tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
  1704. ggml_type_name(tensor.type));
  1705. // This used to be a regex, but <regex> has an extreme cost to compile times.
  1706. bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
  1707. // quantize only 2D tensors
  1708. quantize &= (tensor.ne.size() == 2);
  1709. // uncomment this to keep the output layer in FP16
  1710. //if (tensor.name == "output.weight") {
  1711. // quantize = false;
  1712. //}
  1713. enum ggml_type new_type;
  1714. void * new_data;
  1715. size_t new_size;
  1716. llama_buffer work;
  1717. if (!quantize) {
  1718. new_type = tensor.type;
  1719. new_data = tensor.data;
  1720. new_size = tensor.size;
  1721. printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
  1722. } else {
  1723. new_type = quantized_type;
  1724. float * f32_data;
  1725. size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
  1726. llama_buffer f32_conv_buf;
  1727. if (tensor.type == GGML_TYPE_F32) {
  1728. f32_data = (float *) tensor.data;
  1729. } else if (tensor.type == GGML_TYPE_F16) {
  1730. f32_conv_buf.resize(nelements * sizeof(float));
  1731. f32_data = (float *) f32_conv_buf.addr;
  1732. const auto * f16_data = (const ggml_fp16_t *) tensor.data;
  1733. for (size_t i = 0; i < nelements; i++) {
  1734. f32_data[i] = ggml_fp16_to_fp32(f16_data[i]);
  1735. }
  1736. } else {
  1737. throw format("type %s unsupported for integer quantization", ggml_type_name(tensor.type));
  1738. }
  1739. printf("quantizing .. ");
  1740. fflush(stdout);
  1741. work.resize(nelements * 4); // upper bound on size
  1742. new_data = work.addr;
  1743. std::vector<int64_t> hist_cur(1 << 4, 0);
  1744. int chunk_size = 32 * 512;
  1745. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  1746. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  1747. if (nthread_use < 2) {
  1748. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  1749. } else {
  1750. size_t counter = 0;
  1751. new_size = 0;
  1752. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements, chunk_size] () {
  1753. std::vector<int64_t> local_hist;
  1754. size_t local_size = 0;
  1755. while (true) {
  1756. std::unique_lock<std::mutex> lock(mutex);
  1757. size_t first = counter; counter += chunk_size;
  1758. if (first >= nelements) {
  1759. if (!local_hist.empty()) {
  1760. for (int j=0; j<int(local_hist.size()); ++j) {
  1761. hist_cur[j] += local_hist[j];
  1762. }
  1763. new_size += local_size;
  1764. }
  1765. break;
  1766. }
  1767. lock.unlock();
  1768. size_t last = std::min(nelements, first + chunk_size);
  1769. if (local_hist.empty()) {
  1770. local_hist.resize(hist_cur.size(), 0);
  1771. }
  1772. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  1773. }
  1774. };
  1775. if ((int) workers.size() < nthread_use - 1) {
  1776. workers.resize(nthread_use - 1);
  1777. }
  1778. for (int it = 0; it < nthread_use - 1; ++it) {
  1779. workers[it] = std::thread(compute);
  1780. }
  1781. compute();
  1782. for (int it = 0; it < nthread_use - 1; ++it) {
  1783. workers[it].join();
  1784. }
  1785. }
  1786. printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
  1787. for (size_t i = 0; i < hist_cur.size(); i++) {
  1788. hist_all[i] += hist_cur[i];
  1789. }
  1790. for (size_t i = 0; i < hist_cur.size(); i++) {
  1791. printf("%5.3f ", hist_cur[i] / float(nelements));
  1792. }
  1793. printf("\n");
  1794. }
  1795. total_size_org += tensor.size;
  1796. total_size_new += new_size;
  1797. file_saver.write_tensor(tensor, new_type, new_data, new_size);
  1798. }
  1799. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1800. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1801. {
  1802. int64_t sum_all = 0;
  1803. for (size_t i = 0; i < hist_all.size(); i++) {
  1804. sum_all += hist_all[i];
  1805. }
  1806. printf("%s: hist: ", __func__);
  1807. for (size_t i = 0; i < hist_all.size(); i++) {
  1808. printf("%5.3f ", hist_all[i] / float(sum_all));
  1809. }
  1810. printf("\n");
  1811. }
  1812. }
  1813. //
  1814. // interface implementation
  1815. //
  1816. struct llama_context * llama_init_from_file(
  1817. const char * path_model,
  1818. struct llama_context_params params) {
  1819. ggml_time_init();
  1820. llama_context * ctx = new llama_context;
  1821. if (params.seed < 0) {
  1822. params.seed = time(NULL);
  1823. }
  1824. unsigned cur_percentage = 0;
  1825. if (params.progress_callback == NULL) {
  1826. params.progress_callback_user_data = &cur_percentage;
  1827. params.progress_callback = [](float progress, void * ctx) {
  1828. unsigned * cur_percentage_p = (unsigned *) ctx;
  1829. unsigned percentage = (unsigned) (100 * progress);
  1830. while (percentage > *cur_percentage_p) {
  1831. *cur_percentage_p = percentage;
  1832. fprintf(stderr, ".");
  1833. fflush(stderr);
  1834. if (percentage >= 100) {
  1835. fprintf(stderr, "\n");
  1836. }
  1837. }
  1838. };
  1839. }
  1840. ctx->rng = std::mt19937(params.seed);
  1841. ctx->logits_all = params.logits_all;
  1842. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1843. if (!llama_model_load(path_model, *ctx, params.n_ctx, params.n_gpu_layers, memory_type,
  1844. params.use_mmap, params.use_mlock, params.vocab_only,
  1845. params.progress_callback, params.progress_callback_user_data)) {
  1846. fprintf(stderr, "%s: failed to load model\n", __func__);
  1847. llama_free(ctx);
  1848. return nullptr;
  1849. }
  1850. // reserve memory for context buffers
  1851. if (!params.vocab_only) {
  1852. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1853. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1854. llama_free(ctx);
  1855. return nullptr;
  1856. }
  1857. {
  1858. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1859. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1860. }
  1861. const auto & hparams = ctx->model.hparams;
  1862. // resized during inference
  1863. if (params.logits_all) {
  1864. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1865. } else {
  1866. ctx->logits.reserve(hparams.n_vocab);
  1867. }
  1868. if (params.embedding){
  1869. ctx->embedding.resize(hparams.n_embd);
  1870. }
  1871. ctx->buf_compute.resize(MEM_REQ_EVAL().at(ctx->model.type));
  1872. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0().at(ctx->model.type));
  1873. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1().at(ctx->model.type));
  1874. }
  1875. return ctx;
  1876. }
  1877. void llama_free(struct llama_context * ctx) {
  1878. delete ctx;
  1879. }
  1880. int llama_model_quantize(
  1881. const char * fname_inp,
  1882. const char * fname_out,
  1883. enum llama_ftype ftype,
  1884. int nthread) {
  1885. try {
  1886. llama_model_quantize_internal(fname_inp, fname_out, ftype, nthread);
  1887. return 0;
  1888. } catch (const std::string & err) {
  1889. fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.c_str());
  1890. return 1;
  1891. }
  1892. }
  1893. int llama_apply_lora_from_file_internal(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  1894. fprintf(stderr, "%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  1895. auto & model = ctx->model;
  1896. const int64_t t_start_lora_us = ggml_time_us();
  1897. auto fin = std::ifstream(path_lora, std::ios::binary);
  1898. if (!fin) {
  1899. fprintf(stderr, "%s: failed to open '%s'\n", __func__, path_lora);
  1900. return 1;
  1901. }
  1902. // verify magic and version
  1903. {
  1904. uint32_t magic;
  1905. fin.read((char *) &magic, sizeof(magic));
  1906. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  1907. fprintf(stderr, "%s: bad file magic\n", __func__);
  1908. return 1;
  1909. }
  1910. uint32_t format_version;
  1911. fin.read((char *) &format_version, sizeof(format_version));
  1912. if (format_version != 1) {
  1913. fprintf(stderr, "%s: unsupported file version\n", __func__ );
  1914. return 1;
  1915. }
  1916. }
  1917. int32_t lora_r;
  1918. int32_t lora_alpha;
  1919. fin.read((char *) &lora_r, sizeof(lora_r));
  1920. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  1921. float scaling = (float)lora_alpha / (float)lora_r;
  1922. fprintf(stderr, "%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  1923. // create a temporary ggml context to store the lora tensors
  1924. // todo: calculate size from biggest possible tensor
  1925. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  1926. struct ggml_init_params params;
  1927. params.mem_size = lora_buf.size();
  1928. params.mem_buffer = lora_buf.data();
  1929. params.no_alloc = false;
  1930. ggml_context * lora_ctx = ggml_init(params);
  1931. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  1932. // create a name -> tensor map of the model to accelerate lookups
  1933. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  1934. for (auto & kv: model.tensors_by_name) {
  1935. model_tensors.insert(kv);
  1936. }
  1937. // load base model
  1938. std::unique_ptr<llama_model_loader> model_loader;
  1939. ggml_context * base_ctx = NULL;
  1940. llama_buffer base_buf;
  1941. if (path_base_model) {
  1942. fprintf(stderr, "%s: loading base model from '%s'\n", __func__, path_base_model);
  1943. model_loader.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*vocab_only*/ false));
  1944. size_t ctx_size;
  1945. size_t mmapped_size;
  1946. model_loader->calc_sizes(&ctx_size, &mmapped_size);
  1947. base_buf.resize(ctx_size);
  1948. ggml_init_params base_params;
  1949. base_params.mem_size = base_buf.size;
  1950. base_params.mem_buffer = base_buf.addr;
  1951. base_params.no_alloc = model_loader->use_mmap;
  1952. base_ctx = ggml_init(base_params);
  1953. model_loader->ggml_ctx = base_ctx;
  1954. // maybe this should in llama_model_loader
  1955. if (model_loader->use_mmap) {
  1956. model_loader->mapping.reset(new llama_mmap(&model_loader->file_loaders.at(0)->file, /* prefetch */ 0));
  1957. }
  1958. }
  1959. // read tensors and apply
  1960. bool warned = false;
  1961. int n_tensors = 0;
  1962. while (true) {
  1963. int32_t n_dims;
  1964. int32_t length;
  1965. int32_t ftype;
  1966. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1967. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  1968. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1969. if (fin.eof()) {
  1970. break;
  1971. }
  1972. int32_t ne[2] = { 1, 1 };
  1973. for (int i = 0; i < n_dims; ++i) {
  1974. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1975. }
  1976. std::string name;
  1977. {
  1978. char buf[1024];
  1979. fin.read(buf, length);
  1980. name = std::string(buf, length);
  1981. }
  1982. // check for lora suffix and get the type of tensor
  1983. const std::string lora_suffix = ".lora";
  1984. size_t pos = name.rfind(lora_suffix);
  1985. if (pos == std::string::npos) {
  1986. fprintf(stderr, "%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  1987. return 1;
  1988. }
  1989. std::string lora_type = name.substr(pos + lora_suffix.length());
  1990. std::string base_name = name;
  1991. base_name.erase(pos);
  1992. // fprintf(stderr, "%s: %s => %s (lora type %s) ", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  1993. if (model_tensors.find(base_name) == model_tensors.end()) {
  1994. fprintf(stderr, "%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  1995. return 1;
  1996. }
  1997. // create ggml tensor
  1998. ggml_type wtype;
  1999. switch (ftype) {
  2000. case 0: wtype = GGML_TYPE_F32; break;
  2001. case 1: wtype = GGML_TYPE_F16; break;
  2002. default:
  2003. {
  2004. fprintf(stderr, "%s: invalid tensor data type '%d'\n",
  2005. __func__, ftype);
  2006. return false;
  2007. }
  2008. }
  2009. ggml_tensor* lora_tensor;
  2010. if (n_dims == 2) {
  2011. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  2012. }
  2013. else {
  2014. fprintf(stderr, "%s: unsupported tensor dimension %d\n", __func__, n_dims);
  2015. return 1;
  2016. }
  2017. // load tensor data
  2018. size_t offset = fin.tellg();
  2019. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  2020. offset = (offset + 31) & -32;
  2021. fin.seekg(offset);
  2022. fin.read((char*)lora_tensor->data, tensor_data_size);
  2023. lora_tensors[name] = lora_tensor;
  2024. // check if we have both A and B tensors and apply
  2025. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  2026. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  2027. ggml_tensor * dest_t = model_tensors[base_name];
  2028. ggml_tensor * base_t;
  2029. if (model_loader) {
  2030. // load from base model
  2031. if (model_loader->tensors_map.name_to_idx.find(base_name) == model_loader->tensors_map.name_to_idx.end()) {
  2032. fprintf(stderr, "%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  2033. return 1;
  2034. }
  2035. size_t idx = model_loader->tensors_map.name_to_idx[base_name];
  2036. llama_load_tensor & lt = model_loader->tensors_map.tensors[idx];
  2037. base_t = model_loader->get_tensor(base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  2038. lt.data = (uint8_t *) lt.ggml_tensor->data;
  2039. model_loader->load_data_for(lt);
  2040. lt.ggml_tensor->data = lt.data;
  2041. }
  2042. else {
  2043. base_t = dest_t;
  2044. }
  2045. if (ggml_is_quantized(base_t->type)) {
  2046. if (!warned) {
  2047. fprintf(stderr, "%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  2048. "use a f16 or f32 base model with --lora-base\n", __func__);
  2049. warned = true;
  2050. }
  2051. }
  2052. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  2053. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  2054. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  2055. fprintf(stderr, "%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  2056. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  2057. return 1;
  2058. }
  2059. // w = w + BA*s
  2060. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  2061. if (scaling != 1.0f) {
  2062. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  2063. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  2064. }
  2065. ggml_tensor * r;
  2066. if (base_t == dest_t) {
  2067. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  2068. }
  2069. else {
  2070. r = ggml_add(lora_ctx, base_t, BA);
  2071. r = ggml_cpy(lora_ctx, r, dest_t);
  2072. }
  2073. struct ggml_cgraph gf = ggml_build_forward(r);
  2074. gf.n_threads = n_threads;
  2075. ggml_graph_compute(lora_ctx, &gf);
  2076. // we won't need these tensors again, reset the context to save memory
  2077. ggml_free(lora_ctx);
  2078. lora_ctx = ggml_init(params);
  2079. lora_tensors.clear();
  2080. n_tensors++;
  2081. if (n_tensors % 4 == 0) {
  2082. fprintf(stderr, ".");
  2083. }
  2084. }
  2085. }
  2086. // TODO: this should be in a destructor, it will leak on failure
  2087. ggml_free(lora_ctx);
  2088. if (base_ctx) {
  2089. ggml_free(base_ctx);
  2090. }
  2091. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  2092. fprintf(stderr, " done (%.2f ms)\n", t_lora_us / 1000.0);
  2093. return 0;
  2094. }
  2095. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  2096. try {
  2097. return llama_apply_lora_from_file_internal(ctx, path_lora, path_base_model, n_threads);
  2098. } catch (const std::string & err) {
  2099. fprintf(stderr, "%s: failed to apply lora adapter: %s\n", __func__, err.c_str());
  2100. return 1;
  2101. }
  2102. }
  2103. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  2104. return ctx->model.kv_self.n;
  2105. }
  2106. #define LLAMA_MAX_RNG_STATE (64*1024)
  2107. void llama_set_rng_seed(struct llama_context * ctx, int seed) {
  2108. if (seed < 0) {
  2109. seed = time(NULL);
  2110. }
  2111. ctx->rng.seed(seed);
  2112. }
  2113. // Returns the *maximum* size of the state
  2114. size_t llama_get_state_size(const struct llama_context * ctx) {
  2115. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  2116. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  2117. const size_t s_rng_size = sizeof(size_t);
  2118. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  2119. const size_t s_logits_capacity = sizeof(size_t);
  2120. const size_t s_logits_size = sizeof(size_t);
  2121. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  2122. const size_t s_embedding_size = sizeof(size_t);
  2123. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  2124. const size_t s_kv_size = sizeof(size_t);
  2125. const size_t s_kv_ntok = sizeof(int);
  2126. const size_t s_kv = ctx->model.kv_self.buf.size;
  2127. const size_t s_total = (
  2128. + s_rng_size
  2129. + s_rng
  2130. + s_logits_capacity
  2131. + s_logits_size
  2132. + s_logits
  2133. + s_embedding_size
  2134. + s_embedding
  2135. + s_kv_size
  2136. + s_kv_ntok
  2137. + s_kv
  2138. );
  2139. return s_total;
  2140. }
  2141. // Copies the state to the specified destination address
  2142. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  2143. uint8_t * out = dst;
  2144. // copy rng
  2145. {
  2146. std::stringstream rng_ss;
  2147. rng_ss << ctx->rng;
  2148. const size_t rng_size = rng_ss.str().size();
  2149. char rng_buf[LLAMA_MAX_RNG_STATE];
  2150. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  2151. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  2152. memcpy(out, &rng_size, sizeof(rng_size)); out += sizeof(rng_size);
  2153. memcpy(out, &rng_buf[0], LLAMA_MAX_RNG_STATE); out += LLAMA_MAX_RNG_STATE;
  2154. }
  2155. // copy logits
  2156. {
  2157. const size_t logits_cap = ctx->logits.capacity();
  2158. const size_t logits_size = ctx->logits.size();
  2159. memcpy(out, &logits_cap, sizeof(logits_cap)); out += sizeof(logits_cap);
  2160. memcpy(out, &logits_size, sizeof(logits_size)); out += sizeof(logits_size);
  2161. if (logits_size) {
  2162. memcpy(out, ctx->logits.data(), logits_size * sizeof(float));
  2163. }
  2164. out += logits_cap * sizeof(float);
  2165. }
  2166. // copy embeddings
  2167. {
  2168. const size_t embedding_size = ctx->embedding.size();
  2169. memcpy(out, &embedding_size, sizeof(embedding_size)); out += sizeof(embedding_size);
  2170. if (embedding_size) {
  2171. memcpy(out, ctx->embedding.data(), embedding_size * sizeof(float));
  2172. out += embedding_size * sizeof(float);
  2173. }
  2174. }
  2175. // copy kv cache
  2176. {
  2177. const auto & kv_self = ctx->model.kv_self;
  2178. const auto & hparams = ctx->model.hparams;
  2179. const int n_layer = hparams.n_layer;
  2180. const int n_embd = hparams.n_embd;
  2181. const int n_ctx = hparams.n_ctx;
  2182. const size_t kv_size = kv_self.buf.size;
  2183. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  2184. memcpy(out, &kv_size, sizeof(kv_size)); out += sizeof(kv_size);
  2185. memcpy(out, &kv_ntok, sizeof(kv_ntok)); out += sizeof(kv_ntok);
  2186. if (kv_size) {
  2187. const size_t elt_size = ggml_element_size(kv_self.k);
  2188. char buffer[4096];
  2189. ggml_context * cpy_ctx = ggml_init({ sizeof(buffer), buffer, /* no_alloc */ true });
  2190. ggml_cgraph gf{};
  2191. gf.n_threads = 1;
  2192. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  2193. kout3d->data = out;
  2194. out += ggml_nbytes(kout3d);
  2195. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  2196. vout3d->data = out;
  2197. out += ggml_nbytes(vout3d);
  2198. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  2199. n_embd, kv_ntok, n_layer,
  2200. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  2201. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  2202. kv_ntok, n_embd, n_layer,
  2203. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  2204. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  2205. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  2206. ggml_graph_compute(cpy_ctx, &gf);
  2207. ggml_free(cpy_ctx);
  2208. }
  2209. }
  2210. const size_t written = out - dst;
  2211. const size_t max_size = llama_get_state_size(ctx);
  2212. LLAMA_ASSERT(written <= max_size);
  2213. return written;
  2214. }
  2215. // Sets the state reading from the specified source address
  2216. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  2217. uint8_t * inp = src;
  2218. // set rng
  2219. {
  2220. size_t rng_size;
  2221. char rng_buf[LLAMA_MAX_RNG_STATE];
  2222. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  2223. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  2224. std::stringstream rng_ss;
  2225. rng_ss.str(std::string(&rng_buf[0], rng_size));
  2226. rng_ss >> ctx->rng;
  2227. LLAMA_ASSERT(rng_ss.fail() == false);
  2228. }
  2229. // set logits
  2230. {
  2231. size_t logits_cap;
  2232. size_t logits_size;
  2233. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  2234. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  2235. LLAMA_ASSERT(ctx->logits.capacity() == logits_cap);
  2236. if (logits_size) {
  2237. ctx->logits.resize(logits_size);
  2238. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  2239. }
  2240. inp += logits_cap * sizeof(float);
  2241. }
  2242. // set embeddings
  2243. {
  2244. size_t embedding_size;
  2245. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  2246. LLAMA_ASSERT(ctx->embedding.capacity() == embedding_size);
  2247. if (embedding_size) {
  2248. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  2249. inp += embedding_size * sizeof(float);
  2250. }
  2251. }
  2252. // set kv cache
  2253. {
  2254. const auto & kv_self = ctx->model.kv_self;
  2255. const auto & hparams = ctx->model.hparams;
  2256. const int n_layer = hparams.n_layer;
  2257. const int n_embd = hparams.n_embd;
  2258. const int n_ctx = hparams.n_ctx;
  2259. size_t kv_size;
  2260. int kv_ntok;
  2261. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  2262. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  2263. if (kv_size) {
  2264. LLAMA_ASSERT(kv_self.buf.size == kv_size);
  2265. const size_t elt_size = ggml_element_size(kv_self.k);
  2266. char buffer[4096];
  2267. ggml_context * cpy_ctx = ggml_init({ sizeof(buffer), buffer, /* no_alloc */ true });
  2268. ggml_cgraph gf{};
  2269. gf.n_threads = 1;
  2270. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  2271. kin3d->data = (void *) inp;
  2272. inp += ggml_nbytes(kin3d);
  2273. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  2274. vin3d->data = (void *) inp;
  2275. inp += ggml_nbytes(vin3d);
  2276. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  2277. n_embd, kv_ntok, n_layer,
  2278. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  2279. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  2280. kv_ntok, n_embd, n_layer,
  2281. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  2282. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  2283. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  2284. ggml_graph_compute(cpy_ctx, &gf);
  2285. ggml_free(cpy_ctx);
  2286. }
  2287. ctx->model.kv_self.n = kv_ntok;
  2288. }
  2289. const size_t nread = inp - src;
  2290. const size_t max_size = llama_get_state_size(ctx);
  2291. LLAMA_ASSERT(nread <= max_size);
  2292. return nread;
  2293. }
  2294. bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  2295. llama_file file(path_session, "rb");
  2296. // sanity checks
  2297. {
  2298. const uint32_t magic = file.read_u32();
  2299. const uint32_t version = file.read_u32();
  2300. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  2301. fprintf(stderr, "%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  2302. return false;
  2303. }
  2304. llama_hparams session_hparams;
  2305. file.read_raw(&session_hparams, sizeof(llama_hparams));
  2306. if (session_hparams != ctx->model.hparams) {
  2307. fprintf(stderr, "%s : model hparams didn't match from session file!\n", __func__);
  2308. return false;
  2309. }
  2310. }
  2311. // load the prompt
  2312. {
  2313. const uint32_t n_token_count = file.read_u32();
  2314. if (n_token_count > n_token_capacity) {
  2315. fprintf(stderr, "%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  2316. return false;
  2317. }
  2318. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  2319. *n_token_count_out = n_token_count;
  2320. }
  2321. // restore the context state
  2322. {
  2323. const size_t n_state_size_cur = file.size - file.tell();
  2324. const size_t n_state_size_max = llama_get_state_size(ctx);
  2325. if (n_state_size_cur > n_state_size_max) {
  2326. fprintf(stderr, "%s : the state size in session file is too big! max %zu, got %zu\n", __func__, n_state_size_max, n_state_size_cur);
  2327. return false;
  2328. }
  2329. std::vector<uint8_t> state_data(n_state_size_max);
  2330. file.read_raw(state_data.data(), n_state_size_cur);
  2331. llama_set_state_data(ctx, state_data.data());
  2332. }
  2333. return true;
  2334. }
  2335. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2336. llama_file file(path_session, "wb");
  2337. file.write_u32(LLAMA_SESSION_MAGIC);
  2338. file.write_u32(LLAMA_SESSION_VERSION);
  2339. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  2340. // save the prompt
  2341. file.write_u32((uint32_t) n_token_count);
  2342. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  2343. // save the context state
  2344. {
  2345. const size_t n_state_size_max = llama_get_state_size(ctx);
  2346. std::vector<uint8_t> state_data(n_state_size_max);
  2347. const size_t n_state_size_cur = llama_copy_state_data(ctx, state_data.data());
  2348. file.write_raw(state_data.data(), n_state_size_cur);
  2349. }
  2350. return true;
  2351. }
  2352. int llama_eval(
  2353. struct llama_context * ctx,
  2354. const llama_token * tokens,
  2355. int n_tokens,
  2356. int n_past,
  2357. int n_threads) {
  2358. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  2359. fprintf(stderr, "%s: failed to eval\n", __func__);
  2360. return 1;
  2361. }
  2362. // get a more accurate load time, upon first eval
  2363. // TODO: fix this
  2364. if (!ctx->has_evaluated_once) {
  2365. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  2366. ctx->has_evaluated_once = true;
  2367. }
  2368. return 0;
  2369. }
  2370. int llama_tokenize(
  2371. struct llama_context * ctx,
  2372. const char * text,
  2373. llama_token * tokens,
  2374. int n_max_tokens,
  2375. bool add_bos) {
  2376. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  2377. if (n_max_tokens < (int) res.size()) {
  2378. fprintf(stderr, "%s: too many tokens\n", __func__);
  2379. return -((int) res.size());
  2380. }
  2381. for (size_t i = 0; i < res.size(); i++) {
  2382. tokens[i] = res[i];
  2383. }
  2384. return res.size();
  2385. }
  2386. int llama_n_vocab(const struct llama_context * ctx) {
  2387. return ctx->vocab.id_to_token.size();
  2388. }
  2389. int llama_n_ctx(const struct llama_context * ctx) {
  2390. return ctx->model.hparams.n_ctx;
  2391. }
  2392. int llama_n_embd(const struct llama_context * ctx) {
  2393. return ctx->model.hparams.n_embd;
  2394. }
  2395. float * llama_get_logits(struct llama_context * ctx) {
  2396. return ctx->logits.data();
  2397. }
  2398. float * llama_get_embeddings(struct llama_context * ctx) {
  2399. return ctx->embedding.data();
  2400. }
  2401. const char * llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  2402. if (token >= llama_n_vocab(ctx)) {
  2403. return nullptr;
  2404. }
  2405. return ctx->vocab.id_to_token[token].tok.c_str();
  2406. }
  2407. llama_token llama_token_bos() {
  2408. return 1;
  2409. }
  2410. llama_token llama_token_eos() {
  2411. return 2;
  2412. }
  2413. llama_token llama_token_nl() {
  2414. return 13;
  2415. }
  2416. void llama_print_timings(struct llama_context * ctx) {
  2417. const int64_t t_end_us = ggml_time_us();
  2418. const int32_t n_sample = std::max(1, ctx->n_sample);
  2419. const int32_t n_eval = std::max(1, ctx->n_eval);
  2420. const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
  2421. fprintf(stderr, "\n");
  2422. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0);
  2423. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token)\n", __func__, 1e-3 * ctx->t_sample_us, n_sample, 1e-3 * ctx->t_sample_us / n_sample);
  2424. 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);
  2425. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token)\n", __func__, 1e-3 * ctx->t_eval_us, n_eval, 1e-3 * ctx->t_eval_us / n_eval);
  2426. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0);
  2427. }
  2428. void llama_reset_timings(struct llama_context * ctx) {
  2429. ctx->t_start_us = ggml_time_us();
  2430. ctx->t_sample_us = ctx->n_sample = 0;
  2431. ctx->t_eval_us = ctx->n_eval = 0;
  2432. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  2433. }
  2434. const char * llama_print_system_info(void) {
  2435. static std::string s;
  2436. s = "";
  2437. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  2438. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  2439. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  2440. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  2441. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  2442. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  2443. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  2444. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  2445. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  2446. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  2447. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  2448. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  2449. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  2450. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  2451. return s.c_str();
  2452. }
  2453. // For internal test use
  2454. std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  2455. return ctx->model.tensors_by_name;
  2456. }