llama.cpp 147 KB

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