llama.cpp 105 KB

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