llama.cpp 148 KB

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