llama.cpp 142 KB

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