llama.cpp 144 KB

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