llama.cpp 124 KB

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