llama.cpp 150 KB

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