llama.cpp 122 KB

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