llama.cpp 92 KB

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