llama.cpp 143 KB

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