llama.cpp 122 KB

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