llama.cpp 130 KB

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