llama.cpp 120 KB

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