llama.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #include <cstdint>
  5. #include <cstdio>
  6. #endif
  7. #include "llama-util.h"
  8. #include "llama.h"
  9. #include "ggml.h"
  10. #include <array>
  11. #include <ctime>
  12. #include <cinttypes>
  13. #include <fstream>
  14. #include <random>
  15. #include <map>
  16. #include <unordered_map>
  17. #include <queue>
  18. #include <cassert>
  19. #include <cstring>
  20. #include <climits>
  21. #include <memory>
  22. #include <algorithm>
  23. #include <initializer_list>
  24. #include <thread>
  25. #include <atomic>
  26. #include <mutex>
  27. #include <sstream>
  28. #include <numeric>
  29. #define LLAMA_USE_SCRATCH
  30. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  31. // available llama models
  32. enum e_model {
  33. MODEL_UNKNOWN,
  34. MODEL_7B,
  35. MODEL_13B,
  36. MODEL_30B,
  37. MODEL_65B,
  38. };
  39. static const size_t MB = 1024*1024;
  40. // computed for n_ctx == 2048
  41. // TODO: dynamically determine these sizes
  42. // needs modifications in ggml
  43. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH0()
  44. {
  45. static std::map<e_model, size_t> _MEM_REQ_SCRATCH0 = {
  46. { MODEL_7B, 512ull * MB },
  47. { MODEL_13B, 512ull * MB },
  48. { MODEL_30B, 512ull * MB },
  49. { MODEL_65B, 1024ull * MB },
  50. };
  51. return _MEM_REQ_SCRATCH0;
  52. }
  53. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH1()
  54. {
  55. static std::map<e_model, size_t> _MEM_REQ_SCRATCH1 = {
  56. { MODEL_7B, 512ull * MB },
  57. { MODEL_13B, 512ull * MB },
  58. { MODEL_30B, 512ull * MB },
  59. { MODEL_65B, 1024ull * MB },
  60. };
  61. return _MEM_REQ_SCRATCH1;
  62. }
  63. // 2*n_embd*n_ctx*n_layer*sizeof(float16)
  64. static const std::map<e_model, size_t> & MEM_REQ_KV_SELF()
  65. {
  66. static std::map<e_model, size_t> _MEM_REQ_KV_SELF = {
  67. { MODEL_7B, 1026ull * MB },
  68. { MODEL_13B, 1608ull * MB },
  69. { MODEL_30B, 3124ull * MB },
  70. { MODEL_65B, 5120ull * MB },
  71. };
  72. return _MEM_REQ_KV_SELF;
  73. }
  74. // this is mostly needed for temporary mul_mat buffers to dequantize the data
  75. // not actually needed if BLAS is disabled
  76. static const std::map<e_model, size_t> & MEM_REQ_EVAL()
  77. {
  78. static std::map<e_model, size_t> _MEM_REQ_EVAL = {
  79. { MODEL_7B, 768ull * MB },
  80. { MODEL_13B, 1024ull * MB },
  81. { MODEL_30B, 1280ull * MB },
  82. { MODEL_65B, 1536ull * MB },
  83. };
  84. return _MEM_REQ_EVAL;
  85. }
  86. // default hparams (LLaMA 7B)
  87. struct llama_hparams {
  88. uint32_t n_vocab = 32000;
  89. uint32_t n_ctx = 512; // this is provided as user input?
  90. uint32_t n_embd = 4096;
  91. uint32_t n_mult = 256;
  92. uint32_t n_head = 32;
  93. uint32_t n_layer = 32;
  94. uint32_t n_rot = 64;
  95. enum llama_ftype ftype = LLAMA_FTYPE_MOSTLY_F16;
  96. bool operator!=(const llama_hparams & other) const {
  97. return memcmp(this, &other, sizeof(llama_hparams));
  98. }
  99. };
  100. struct llama_layer {
  101. // normalization
  102. struct ggml_tensor * attention_norm;
  103. // attention
  104. struct ggml_tensor * wq;
  105. struct ggml_tensor * wk;
  106. struct ggml_tensor * wv;
  107. struct ggml_tensor * wo;
  108. // normalization
  109. struct ggml_tensor * ffn_norm;
  110. // ff
  111. struct ggml_tensor * w1;
  112. struct ggml_tensor * w2;
  113. struct ggml_tensor * w3;
  114. };
  115. struct llama_kv_cache {
  116. struct ggml_tensor * k;
  117. struct ggml_tensor * v;
  118. struct ggml_context * ctx = NULL;
  119. llama_ctx_buffer buf;
  120. int n; // number of tokens currently in the cache
  121. ~llama_kv_cache() {
  122. if (ctx) {
  123. ggml_free(ctx);
  124. }
  125. }
  126. };
  127. struct llama_model {
  128. e_model type = MODEL_UNKNOWN;
  129. llama_hparams hparams;
  130. struct ggml_tensor * tok_embeddings;
  131. struct ggml_tensor * norm;
  132. struct ggml_tensor * output;
  133. std::vector<llama_layer> layers;
  134. // context
  135. struct ggml_context * ctx = NULL;
  136. // key + value cache for the self attention
  137. // TODO: move to llama_state
  138. struct llama_kv_cache kv_self;
  139. // the model memory buffer
  140. llama_ctx_buffer buf;
  141. // model memory mapped file
  142. std::unique_ptr<llama_mmap> mapping;
  143. // objects representing data potentially being locked in memory
  144. llama_mlock mlock_buf;
  145. llama_mlock mlock_mmap;
  146. // for quantize-stats only
  147. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  148. ~llama_model() {
  149. if (ctx) {
  150. ggml_free(ctx);
  151. }
  152. }
  153. };
  154. struct llama_vocab {
  155. using id = int32_t;
  156. using token = std::string;
  157. struct token_score {
  158. token tok;
  159. float score;
  160. };
  161. std::unordered_map<token, id> token_to_id;
  162. std::vector<token_score> id_to_token;
  163. };
  164. struct llama_context {
  165. std::mt19937 rng;
  166. int64_t t_load_us = 0;
  167. int64_t t_start_us = 0;
  168. bool has_evaluated_once = false;
  169. int64_t t_sample_us = 0;
  170. int64_t t_eval_us = 0;
  171. int64_t t_p_eval_us = 0;
  172. int32_t n_sample = 0; // number of tokens sampled
  173. int32_t n_eval = 0; // number of eval calls
  174. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  175. llama_model model;
  176. llama_vocab vocab;
  177. size_t mem_per_token = 0;
  178. // decode output (2-dimensional array: [n_tokens][n_vocab])
  179. std::vector<float> logits;
  180. bool logits_all = false;
  181. // input embedding (1-dimensional array: [n_embd])
  182. std::vector<float> embedding;
  183. // memory buffers used to evaluate the model
  184. // TODO: move in llama_state
  185. llama_ctx_buffer buf_compute;
  186. llama_ctx_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  187. int buf_last = 0;
  188. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  189. void use_buf(struct ggml_context * ctx, int i) {
  190. #if defined(LLAMA_USE_SCRATCH)
  191. size_t last_size = 0;
  192. if (i == -1) {
  193. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  194. } else {
  195. auto & buf = buf_scratch[i];
  196. last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
  197. }
  198. if (buf_last >= 0) {
  199. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  200. }
  201. buf_last = i;
  202. #else
  203. (void) i;
  204. (void) ctx;
  205. #endif
  206. }
  207. size_t get_buf_max_mem(int i) const {
  208. #if defined(LLAMA_USE_SCRATCH)
  209. return buf_max_size[i];
  210. #else
  211. (void) i;
  212. return 0;
  213. #endif
  214. }
  215. };
  216. template <typename T>
  217. static T checked_mul(T a, T b) {
  218. T ret = a * b;
  219. if (a != 0 && ret / a != b) {
  220. throw format("overflow multiplying %llu * %llu",
  221. (unsigned long long) a, (unsigned long long) b);
  222. }
  223. return ret;
  224. }
  225. static size_t checked_div(size_t a, size_t b) {
  226. if (b == 0 || a % b != 0) {
  227. throw format("error dividing %zu / %zu", a, b);
  228. }
  229. return a / b;
  230. }
  231. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  232. char buf[256];
  233. snprintf(buf, sizeof(buf), "%5u", ne.at(0));
  234. for (size_t i = 1; i < ne.size(); i++) {
  235. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " x %5u", ne.at(i));
  236. }
  237. return buf;
  238. }
  239. static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
  240. size_t size = ggml_type_size(type);
  241. for (uint32_t dim : ne) {
  242. size = checked_mul<size_t>(size, dim);
  243. }
  244. return size / ggml_blck_size(type);
  245. }
  246. struct llama_load_tensor_shard {
  247. std::vector<uint32_t> ne;
  248. size_t size;
  249. enum ggml_type type;
  250. size_t file_idx;
  251. size_t file_off;
  252. void calc_size() {
  253. size = llama_calc_tensor_size(ne, type);
  254. }
  255. };
  256. enum llama_split_type {
  257. SPLIT_NONE,
  258. SPLIT_BY_COLUMNS,
  259. SPLIT_BY_ROWS
  260. };
  261. struct llama_load_tensor {
  262. std::vector<llama_load_tensor_shard> shards;
  263. std::string name;
  264. enum ggml_type type = GGML_TYPE_F32;
  265. llama_split_type split_type = SPLIT_NONE;
  266. std::vector<uint32_t> ne;
  267. size_t size;
  268. struct ggml_tensor * ggml_tensor = NULL;
  269. uint8_t * data;
  270. llama_load_tensor(const std::string & name) : name(name) {}
  271. void calc_all() {
  272. calc_type();
  273. calc_split_type();
  274. calc_ne();
  275. calc_size();
  276. }
  277. void calc_type() {
  278. const auto & first_shard = shards.at(0);
  279. for (const auto & shard : shards) {
  280. if (shard.type != first_shard.type) {
  281. throw format("inconsistent tensor shard type in '%s'", name.c_str());
  282. }
  283. }
  284. type = first_shard.type;
  285. }
  286. void calc_split_type() {
  287. if (shards.at(0).ne.size() == 1 || // 1D tensors are just duplicated in every file
  288. shards.size() == 1) { // only one file?
  289. split_type = SPLIT_NONE;
  290. } else if (name.find("tok_embeddings.") == 0 ||
  291. name.find(".attention.wo.weight") != std::string::npos ||
  292. name.find(".feed_forward.w2.weight") != std::string::npos) {
  293. split_type = SPLIT_BY_COLUMNS;
  294. } else {
  295. split_type = SPLIT_BY_ROWS;
  296. }
  297. }
  298. void calc_ne() {
  299. const auto & first_shard = shards.at(0);
  300. for (const auto & shard : shards) {
  301. if (shard.ne != first_shard.ne) {
  302. throw format("inconsistent tensor shard shape in '%s': first was %s, other was %s",
  303. name.c_str(), llama_format_tensor_shape(first_shard.ne).c_str(), llama_format_tensor_shape(shard.ne).c_str());
  304. }
  305. }
  306. ne = first_shard.ne;
  307. LLAMA_ASSERT(shards.size() <= UINT32_MAX);
  308. uint32_t n_shards = (uint32_t) shards.size();
  309. switch (split_type) {
  310. case SPLIT_NONE:
  311. ne = first_shard.ne;
  312. break;
  313. case SPLIT_BY_COLUMNS:
  314. ne = {checked_mul<uint32_t>(first_shard.ne[0], n_shards),
  315. first_shard.ne[1]};
  316. break;
  317. case SPLIT_BY_ROWS:
  318. ne = {first_shard.ne[0],
  319. checked_mul<uint32_t>(first_shard.ne[1], n_shards)};
  320. break;
  321. }
  322. }
  323. void calc_size() {
  324. size = llama_calc_tensor_size(ne, type);
  325. }
  326. };
  327. struct llama_load_tensors_map {
  328. // tensors is kept in a separate vector to preserve file order
  329. std::vector<llama_load_tensor> tensors;
  330. std::unordered_map<std::string, size_t> name_to_idx;
  331. };
  332. enum llama_file_version {
  333. LLAMA_FILE_VERSION_GGML,
  334. LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
  335. LLAMA_FILE_VERSION_GGJT_V1, // added padding
  336. };
  337. struct llama_file_loader {
  338. llama_file file;
  339. llama_file_version file_version;
  340. llama_hparams hparams;
  341. llama_vocab vocab;
  342. llama_file_loader(const char * fname, size_t file_idx, llama_load_tensors_map & tensors_map)
  343. : file(fname, "rb") {
  344. fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
  345. read_magic();
  346. read_hparams();
  347. read_vocab();
  348. read_tensor_metadata(file_idx, tensors_map);
  349. }
  350. void read_magic() {
  351. uint32_t magic = file.read_u32();
  352. uint32_t version = 0;
  353. if (magic != 'ggml') {
  354. version = file.read_u32();
  355. }
  356. if (magic == 'ggml' && version == 0) {
  357. file_version = LLAMA_FILE_VERSION_GGML;
  358. } else if (magic == 'ggmf' && version == 1) {
  359. file_version = LLAMA_FILE_VERSION_GGMF_V1;
  360. } else if (magic == 'ggjt' && version == 1) {
  361. file_version = LLAMA_FILE_VERSION_GGJT_V1;
  362. } else {
  363. throw format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
  364. magic, version);
  365. }
  366. }
  367. void read_hparams() {
  368. hparams.n_vocab = file.read_u32();
  369. hparams.n_embd = file.read_u32();
  370. hparams.n_mult = file.read_u32();
  371. hparams.n_head = file.read_u32();
  372. hparams.n_layer = file.read_u32();
  373. hparams.n_rot = file.read_u32();
  374. hparams.ftype = (enum llama_ftype) file.read_u32();
  375. }
  376. void read_vocab() {
  377. vocab.id_to_token.resize(hparams.n_vocab);
  378. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  379. uint32_t len = file.read_u32();
  380. std::string word = file.read_string(len);
  381. float score = 0.0f;
  382. if (file_version >= LLAMA_FILE_VERSION_GGMF_V1) {
  383. file.read_raw(&score, sizeof(score));
  384. }
  385. vocab.token_to_id[word] = i;
  386. auto & tok_score = vocab.id_to_token[i];
  387. tok_score.tok = std::move(word);
  388. tok_score.score = score;
  389. }
  390. }
  391. void read_tensor_metadata(size_t file_idx, llama_load_tensors_map & tensors_map) {
  392. while (file.tell() < file.size) {
  393. llama_load_tensor_shard shard;
  394. uint32_t n_dims = file.read_u32();
  395. uint32_t name_len = file.read_u32();
  396. shard.type = (enum ggml_type) file.read_u32();
  397. shard.ne.resize(n_dims);
  398. file.read_raw(shard.ne.data(), sizeof(shard.ne[0]) * n_dims);
  399. std::string name = file.read_string(name_len);
  400. if (n_dims < 1 || n_dims > 2) {
  401. throw format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims);
  402. }
  403. switch (shard.type) {
  404. case GGML_TYPE_F32:
  405. case GGML_TYPE_F16:
  406. case GGML_TYPE_Q4_0:
  407. case GGML_TYPE_Q4_1:
  408. case GGML_TYPE_Q4_2:
  409. case GGML_TYPE_Q5_0:
  410. case GGML_TYPE_Q5_1:
  411. case GGML_TYPE_Q8_0:
  412. break;
  413. default: {
  414. throw format("unrecognized tensor type %u\n", shard.type);
  415. }
  416. }
  417. if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
  418. // skip to the next multiple of 32 bytes
  419. file.seek(-file.tell() & 31, SEEK_CUR);
  420. }
  421. shard.file_idx = file_idx;
  422. shard.file_off = file.tell();
  423. shard.calc_size();
  424. file.seek(shard.size, SEEK_CUR);
  425. auto it = tensors_map.name_to_idx.find(name);
  426. size_t idx;
  427. if (it != tensors_map.name_to_idx.end()) {
  428. idx = it->second;
  429. } else {
  430. tensors_map.tensors.emplace_back(name);
  431. idx = tensors_map.tensors.size() - 1;
  432. tensors_map.name_to_idx.emplace(name, idx);
  433. }
  434. tensors_map.tensors.at(idx).shards.push_back(shard);
  435. }
  436. }
  437. };
  438. struct llama_file_saver {
  439. llama_file file;
  440. llama_file_loader * any_file_loader;
  441. llama_file_saver(const char * fname, llama_file_loader * any_file_loader, enum llama_ftype new_ftype)
  442. : file(fname, "wb"), any_file_loader(any_file_loader) {
  443. fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
  444. write_magic();
  445. write_hparams(new_ftype);
  446. write_vocab();
  447. }
  448. void write_magic() {
  449. file.write_u32('ggjt'); // magic
  450. file.write_u32(1); // version
  451. }
  452. void write_hparams(enum llama_ftype new_ftype) {
  453. const llama_hparams & hparams = any_file_loader->hparams;
  454. file.write_u32(hparams.n_vocab);
  455. file.write_u32(hparams.n_embd);
  456. file.write_u32(hparams.n_mult);
  457. file.write_u32(hparams.n_head);
  458. file.write_u32(hparams.n_layer);
  459. file.write_u32(hparams.n_rot);
  460. file.write_u32(new_ftype);
  461. }
  462. void write_vocab() {
  463. if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
  464. fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
  465. }
  466. uint32_t n_vocab = any_file_loader->hparams.n_vocab;
  467. for (uint32_t i = 0; i < n_vocab; i++) {
  468. const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
  469. file.write_u32((uint32_t) token_score.tok.size());
  470. file.write_raw(token_score.tok.data(), token_score.tok.size());
  471. file.write_raw(&token_score.score, sizeof(token_score.score));
  472. }
  473. }
  474. void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
  475. switch (new_type) {
  476. case GGML_TYPE_F32:
  477. case GGML_TYPE_F16:
  478. case GGML_TYPE_Q4_0:
  479. case GGML_TYPE_Q4_1:
  480. case GGML_TYPE_Q4_2:
  481. case GGML_TYPE_Q5_0:
  482. case GGML_TYPE_Q5_1:
  483. case GGML_TYPE_Q8_0:
  484. break;
  485. default: LLAMA_ASSERT(false);
  486. }
  487. file.write_u32((uint32_t) tensor.ne.size());
  488. file.write_u32((uint32_t) tensor.name.size());
  489. file.write_u32(new_type);
  490. file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
  491. file.write_raw(tensor.name.data(), tensor.name.size());
  492. file.seek(-file.tell() & 31, SEEK_CUR);
  493. LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
  494. file.write_raw(new_data, new_size);
  495. }
  496. };
  497. struct llama_model_loader {
  498. std::vector<std::unique_ptr<llama_file_loader>> file_loaders;
  499. llama_load_tensors_map tensors_map;
  500. bool use_mmap;
  501. size_t num_ggml_tensors_created = 0;
  502. struct ggml_context * ggml_ctx = NULL;
  503. std::unique_ptr<llama_mmap> mapping;
  504. llama_model_loader(const std::string & fname_base, bool use_mmap, bool vocab_only) {
  505. auto first_file = new llama_file_loader(fname_base.c_str(), 0, tensors_map);
  506. file_loaders.emplace_back(first_file);
  507. uint32_t n_parts = vocab_only ? 1 : guess_n_parts();
  508. for (uint32_t i = 1; i < n_parts; i++) {
  509. std::string fname = fname_base + "." + std::to_string(i);
  510. auto ith_file = new llama_file_loader(fname.c_str(), i, tensors_map);
  511. file_loaders.emplace_back(ith_file);
  512. if (ith_file->hparams != first_file->hparams) {
  513. throw format("llama.cpp: hparams inconsistent between files");
  514. }
  515. }
  516. if (!llama_mmap::SUPPORTED) {
  517. use_mmap = false;
  518. }
  519. if (use_mmap && alignment_prevents_mmap()) {
  520. fprintf(stderr, "llama.cpp: can't use mmap because tensors are not aligned; convert to new format to avoid this\n");
  521. use_mmap = false;
  522. }
  523. this->use_mmap = use_mmap;
  524. for (llama_load_tensor & lt : tensors_map.tensors) {
  525. lt.calc_all();
  526. }
  527. }
  528. bool alignment_prevents_mmap() {
  529. for (const llama_load_tensor & lt : tensors_map.tensors) {
  530. for (const llama_load_tensor_shard & shard : lt.shards) {
  531. if (shard.file_off & 3) {
  532. return true;
  533. }
  534. }
  535. }
  536. return false;
  537. }
  538. uint32_t guess_n_parts() const {
  539. auto it = tensors_map.name_to_idx.find("tok_embeddings.weight");
  540. if (it == tensors_map.name_to_idx.end()) {
  541. throw std::string("missing tok_embeddings.weight");
  542. }
  543. const llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  544. return file_loaders.at(0)->hparams.n_embd / lt.shards.at(0).ne.at(0);
  545. }
  546. void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
  547. *ctx_size_p = *mmapped_size_p = 0;
  548. for (const llama_load_tensor & lt : tensors_map.tensors) {
  549. *ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  550. *(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size;
  551. }
  552. }
  553. struct ggml_tensor * get_tensor(const std::string & name, std::vector<uint32_t> ne) {
  554. auto it = tensors_map.name_to_idx.find(name);
  555. if (it == tensors_map.name_to_idx.end()) {
  556. throw format("llama.cpp: tensor '%s' is missing from model", name.c_str());
  557. }
  558. llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  559. if (lt.ne != ne) {
  560. throw format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
  561. name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str());
  562. }
  563. return get_tensor_for(lt);
  564. }
  565. struct ggml_tensor * get_tensor_for(llama_load_tensor & lt) {
  566. struct ggml_tensor * tensor;
  567. if (lt.ne.size() == 2) {
  568. tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
  569. } else {
  570. LLAMA_ASSERT(lt.ne.size() == 1);
  571. tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
  572. }
  573. ggml_set_name(tensor, lt.name.c_str());
  574. LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
  575. lt.ggml_tensor = tensor;
  576. num_ggml_tensors_created++;
  577. return tensor;
  578. }
  579. void done_getting_tensors() {
  580. if (num_ggml_tensors_created != tensors_map.tensors.size()) {
  581. throw std::string("llama.cpp: file contained more tensors than expected");
  582. }
  583. }
  584. void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  585. size_t data_size = 0;
  586. for (const llama_load_tensor & lt : tensors_map.tensors) {
  587. data_size += lt.size;
  588. }
  589. if (use_mmap) {
  590. mapping.reset(new llama_mmap(&file_loaders.at(0)->file));
  591. if (!lmlock) {
  592. // Don't call the callback since the actual loading will be lazy
  593. // and we can't measure it.
  594. progress_callback = NULL;
  595. }
  596. if (lmlock) {
  597. lmlock->init(mapping->addr);
  598. }
  599. }
  600. size_t done_size = 0;
  601. for (llama_load_tensor & lt : tensors_map.tensors) {
  602. if (progress_callback) {
  603. progress_callback((float) done_size / data_size, progress_callback_user_data);
  604. }
  605. LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
  606. lt.data = (uint8_t *) lt.ggml_tensor->data;
  607. load_data_for(lt);
  608. lt.ggml_tensor->data = lt.data;
  609. done_size += lt.size;
  610. if (use_mmap && lmlock) {
  611. lmlock->grow_to(done_size);
  612. }
  613. }
  614. if (progress_callback) {
  615. progress_callback(1.0f, progress_callback_user_data);
  616. }
  617. }
  618. void load_data_for(llama_load_tensor & lt) {
  619. if (use_mmap) {
  620. LLAMA_ASSERT(lt.shards.size() == 1);
  621. lt.data = (uint8_t *) mapping->addr + lt.shards.at(0).file_off;
  622. } else if (lt.split_type == SPLIT_NONE) {
  623. llama_file & file = file_loaders.at(lt.shards.at(0).file_idx)->file;
  624. file.seek(lt.shards.at(0).file_off, SEEK_SET);
  625. file.read_raw(lt.data, lt.size);
  626. } else if (lt.split_type == SPLIT_BY_ROWS) {
  627. size_t offset = 0;
  628. for (llama_load_tensor_shard & shard : lt.shards) {
  629. llama_file & file = file_loaders.at(shard.file_idx)->file;
  630. file.seek(shard.file_off, SEEK_SET);
  631. file.read_raw(lt.data + offset, shard.size);
  632. offset += shard.size;
  633. }
  634. LLAMA_ASSERT(offset == lt.size);
  635. } else if (lt.split_type == SPLIT_BY_COLUMNS) {
  636. // Let's load the data into temporary buffers to ensure the OS performs large loads.
  637. std::vector<llama_buffer> tmp_bufs(lt.shards.size());
  638. for (size_t i = 0; i < lt.shards.size(); i++) {
  639. llama_load_tensor_shard & shard = lt.shards.at(i);
  640. llama_file & file = file_loaders.at(shard.file_idx)->file;
  641. file.seek(shard.file_off, SEEK_SET);
  642. tmp_bufs.at(i).resize(shard.size);
  643. file.read_raw(tmp_bufs.at(i).addr, shard.size);
  644. }
  645. // Then reshape.
  646. size_t num_rows = lt.ne.at(1);
  647. size_t per_shard_row_size = lt.shards.at(0).size / num_rows;
  648. size_t out_offset = 0;
  649. for (size_t row = 0; row < num_rows; row++) {
  650. for (llama_buffer & tmp_buf : tmp_bufs) {
  651. memcpy(lt.data + out_offset,
  652. tmp_buf.addr + row * per_shard_row_size,
  653. per_shard_row_size);
  654. out_offset += per_shard_row_size;
  655. }
  656. }
  657. LLAMA_ASSERT(out_offset == lt.size);
  658. }
  659. if (0) {
  660. print_checksum(lt);
  661. }
  662. }
  663. static void print_checksum(llama_load_tensor & lt) {
  664. uint32_t sum = 0;
  665. for (size_t i = 0; i < lt.size; i++) {
  666. uint8_t byte = lt.data[i];
  667. sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
  668. }
  669. fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
  670. llama_format_tensor_shape(lt.ne).c_str(), lt.size);
  671. }
  672. };
  673. //
  674. // kv cache
  675. //
  676. static bool kv_cache_init(
  677. const struct llama_hparams & hparams,
  678. struct llama_kv_cache & cache,
  679. ggml_type wtype,
  680. int n_ctx) {
  681. const int n_embd = hparams.n_embd;
  682. const int n_layer = hparams.n_layer;
  683. const int64_t n_mem = n_layer*n_ctx;
  684. const int64_t n_elements = n_embd*n_mem;
  685. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  686. struct ggml_init_params params;
  687. params.mem_size = cache.buf.size;
  688. params.mem_buffer = cache.buf.addr;
  689. params.no_alloc = false;
  690. cache.ctx = ggml_init(params);
  691. if (!cache.ctx) {
  692. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  693. return false;
  694. }
  695. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  696. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  697. ggml_set_name(cache.k, "cache_k");
  698. ggml_set_name(cache.v, "cache_v");
  699. return true;
  700. }
  701. struct llama_context_params llama_context_default_params() {
  702. struct llama_context_params result = {
  703. /*.n_ctx =*/ 512,
  704. /*.n_parts =*/ -1,
  705. /*.seed =*/ -1,
  706. /*.f16_kv =*/ false,
  707. /*.logits_all =*/ false,
  708. /*.vocab_only =*/ false,
  709. /*.use_mmap =*/ true,
  710. /*.use_mlock =*/ false,
  711. /*.embedding =*/ false,
  712. /*.progress_callback =*/ nullptr,
  713. /*.progress_callback_user_data =*/ nullptr,
  714. };
  715. return result;
  716. }
  717. bool llama_mmap_supported() {
  718. return llama_mmap::SUPPORTED;
  719. }
  720. bool llama_mlock_supported() {
  721. return llama_mlock::SUPPORTED;
  722. }
  723. //
  724. // model loading
  725. //
  726. static const char *llama_file_version_name(llama_file_version version) {
  727. switch (version) {
  728. case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
  729. case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
  730. case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (latest)";
  731. default: LLAMA_ASSERT(false);
  732. }
  733. }
  734. static const char *llama_ftype_name(enum llama_ftype ftype) {
  735. switch (ftype) {
  736. case LLAMA_FTYPE_ALL_F32: return "all F32";
  737. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  738. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  739. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  740. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  741. return "mostly Q4_1, some F16";
  742. case LLAMA_FTYPE_MOSTLY_Q4_2: return "mostly Q4_2";
  743. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  744. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  745. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  746. default: return "unknown, may not work";
  747. }
  748. }
  749. static const char *llama_model_type_name(e_model type) {
  750. switch (type) {
  751. case MODEL_7B: return "7B";
  752. case MODEL_13B: return "13B";
  753. case MODEL_30B: return "30B";
  754. case MODEL_65B: return "65B";
  755. default: LLAMA_ASSERT(false);
  756. }
  757. }
  758. static void llama_model_load_internal(
  759. const std::string & fname,
  760. llama_context & lctx,
  761. int n_ctx,
  762. ggml_type memory_type,
  763. bool use_mmap,
  764. bool use_mlock,
  765. bool vocab_only,
  766. llama_progress_callback progress_callback,
  767. void * progress_callback_user_data) {
  768. lctx.t_start_us = ggml_time_us();
  769. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap, vocab_only));
  770. lctx.vocab = std::move(ml->file_loaders.at(0)->vocab);
  771. auto & model = lctx.model;
  772. model.hparams = ml->file_loaders.at(0)->hparams;
  773. llama_file_version file_version = ml->file_loaders.at(0)->file_version;
  774. auto & hparams = model.hparams;
  775. uint32_t n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  776. {
  777. switch (hparams.n_layer) {
  778. case 32: model.type = e_model::MODEL_7B; break;
  779. case 40: model.type = e_model::MODEL_13B; break;
  780. case 60: model.type = e_model::MODEL_30B; break;
  781. case 80: model.type = e_model::MODEL_65B; break;
  782. }
  783. hparams.n_ctx = n_ctx;
  784. }
  785. {
  786. fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
  787. fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  788. fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  789. fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
  790. fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
  791. fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
  792. fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
  793. fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot);
  794. fprintf(stderr, "%s: ftype = %u (%s)\n", __func__, hparams.ftype, llama_ftype_name(hparams.ftype));
  795. fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
  796. fprintf(stderr, "%s: n_parts = %zu\n", __func__, ml->file_loaders.size());
  797. fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
  798. }
  799. if (vocab_only) {
  800. return;
  801. }
  802. auto & ctx = model.ctx;
  803. size_t ctx_size, mmapped_size;
  804. ml->calc_sizes(&ctx_size, &mmapped_size);
  805. fprintf(stderr, "%s: ggml ctx size = %6.2f KB\n", __func__, ctx_size/1024.0);
  806. // print memory requirements
  807. {
  808. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  809. // this is the total memory required to run the inference
  810. const size_t mem_required =
  811. ctx_size +
  812. mmapped_size +
  813. MEM_REQ_SCRATCH0().at(model.type) +
  814. MEM_REQ_SCRATCH1().at(model.type) +
  815. MEM_REQ_EVAL().at(model.type);
  816. // this is the memory required by one llama_state
  817. const size_t mem_required_state =
  818. scale*MEM_REQ_KV_SELF().at(model.type);
  819. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  820. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  821. }
  822. // create the ggml context
  823. {
  824. lctx.model.buf.resize(ctx_size);
  825. if (use_mlock) {
  826. lctx.model.mlock_buf.init(lctx.model.buf.addr);
  827. lctx.model.mlock_buf.grow_to(lctx.model.buf.size);
  828. }
  829. struct ggml_init_params params = {
  830. /*.mem_size =*/ lctx.model.buf.size,
  831. /*.mem_buffer =*/ lctx.model.buf.addr,
  832. /*.no_alloc =*/ ml->use_mmap,
  833. };
  834. model.ctx = ggml_init(params);
  835. if (!model.ctx) {
  836. throw format("ggml_init() failed");
  837. }
  838. }
  839. // prepare memory for the weights
  840. {
  841. const auto & hparams = model.hparams;
  842. const uint32_t n_embd = hparams.n_embd;
  843. const uint32_t n_layer = hparams.n_layer;
  844. const uint32_t n_vocab = hparams.n_vocab;
  845. ml->ggml_ctx = ctx;
  846. model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab});
  847. model.norm = ml->get_tensor("norm.weight", {n_embd});
  848. model.output = ml->get_tensor("output.weight", {n_embd, n_vocab});
  849. model.layers.resize(n_layer);
  850. for (uint32_t i = 0; i < n_layer; ++i) {
  851. auto & layer = model.layers[i];
  852. std::string layers_i = "layers." + std::to_string(i);
  853. layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd});
  854. layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd});
  855. layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd});
  856. layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd});
  857. layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd});
  858. layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd});
  859. layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  860. layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  861. layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  862. }
  863. }
  864. ml->done_getting_tensors();
  865. // populate `tensors_by_name`
  866. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  867. model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
  868. }
  869. ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &lctx.model.mlock_mmap : NULL);
  870. model.mapping = std::move(ml->mapping);
  871. // loading time will be recalculate after the first eval, so
  872. // we take page faults deferred by mmap() into consideration
  873. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  874. }
  875. static bool llama_model_load(
  876. const std::string & fname,
  877. llama_context & lctx,
  878. int n_ctx,
  879. ggml_type memory_type,
  880. bool use_mmap,
  881. bool use_mlock,
  882. bool vocab_only,
  883. llama_progress_callback progress_callback,
  884. void *progress_callback_user_data) {
  885. try {
  886. llama_model_load_internal(fname, lctx, n_ctx, memory_type, use_mmap, use_mlock,
  887. vocab_only, progress_callback, progress_callback_user_data);
  888. return true;
  889. } catch (const std::string & err) {
  890. fprintf(stderr, "error loading model: %s\n", err.c_str());
  891. return false;
  892. }
  893. }
  894. // evaluate the transformer
  895. //
  896. // - lctx: llama context
  897. // - tokens: new batch of tokens to process
  898. // - n_past: the context size so far
  899. // - n_threads: number of threads to use
  900. //
  901. static bool llama_eval_internal(
  902. llama_context & lctx,
  903. const llama_token * tokens,
  904. const int n_tokens,
  905. const int n_past,
  906. const int n_threads) {
  907. const int64_t t_start_us = ggml_time_us();
  908. const int N = n_tokens;
  909. const auto & model = lctx.model;
  910. const auto & hparams = model.hparams;
  911. auto & kv_self = model.kv_self;
  912. LLAMA_ASSERT(!!kv_self.ctx);
  913. const int n_embd = hparams.n_embd;
  914. const int n_layer = hparams.n_layer;
  915. const int n_ctx = hparams.n_ctx;
  916. const int n_head = hparams.n_head;
  917. const int n_vocab = hparams.n_vocab;
  918. const int n_rot = hparams.n_embd/hparams.n_head;
  919. auto & mem_per_token = lctx.mem_per_token;
  920. auto & buf_compute = lctx.buf_compute;
  921. struct ggml_init_params params = {
  922. /*.mem_size =*/ buf_compute.size,
  923. /*.mem_buffer =*/ buf_compute.addr,
  924. /*.no_alloc =*/ false,
  925. };
  926. struct ggml_context * ctx0 = ggml_init(params);
  927. // for big prompts, if BLAS is enabled, it is better to use only one thread
  928. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  929. ggml_cgraph gf = {};
  930. gf.n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  931. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  932. ggml_set_name(embd, "embd");
  933. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  934. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  935. for (int il = 0; il < n_layer; ++il) {
  936. struct ggml_tensor * inpSA = inpL;
  937. struct ggml_tensor * cur;
  938. lctx.use_buf(ctx0, 0);
  939. // norm
  940. {
  941. cur = ggml_rms_norm(ctx0, inpL);
  942. // cur = attention_norm*cur
  943. cur = ggml_mul(ctx0,
  944. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  945. cur);
  946. }
  947. // self-attention
  948. {
  949. // compute Q and K and RoPE them
  950. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  951. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  952. ggml_set_name(Qcur, "Qcur");
  953. ggml_set_name(Kcur, "Kcur");
  954. // store key and value to memory
  955. {
  956. // compute the transposed [N, n_embd] V matrix
  957. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), n_embd, N));
  958. 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));
  959. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  960. ( n_ctx)*ggml_element_size(kv_self.v),
  961. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  962. // important: storing RoPE-ed version of K in the KV cache!
  963. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  964. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  965. }
  966. struct ggml_tensor * Q =
  967. ggml_permute(ctx0,
  968. Qcur,
  969. 0, 2, 1, 3);
  970. ggml_set_name(Q, "Q");
  971. struct ggml_tensor * K =
  972. ggml_permute(ctx0,
  973. ggml_reshape_3d(ctx0,
  974. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  975. n_embd/n_head, n_head, n_past + N),
  976. 0, 2, 1, 3);
  977. ggml_set_name(K, "K");
  978. // K * Q
  979. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  980. ggml_set_name(KQ, "KQ");
  981. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  982. struct ggml_tensor * KQ_scale = ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head));
  983. ggml_set_name(KQ_scale, "1/sqrt(n_embd/n_head)");
  984. struct ggml_tensor * KQ_scaled = ggml_scale(ctx0, KQ, KQ_scale);
  985. ggml_set_name(KQ_scaled, "KQ_scaled");
  986. // KQ_masked = mask_past(KQ_scaled)
  987. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  988. ggml_set_name(KQ_masked, "KQ_masked");
  989. // KQ = soft_max(KQ_masked)
  990. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  991. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  992. // split cached V into n_head heads
  993. struct ggml_tensor * V =
  994. ggml_view_3d(ctx0, kv_self.v,
  995. n_past + N, n_embd/n_head, n_head,
  996. n_ctx*ggml_element_size(kv_self.v),
  997. n_ctx*ggml_element_size(kv_self.v)*n_embd/n_head,
  998. il*n_ctx*ggml_element_size(kv_self.v)*n_embd);
  999. ggml_set_name(V, "V");
  1000. #if 1
  1001. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1002. ggml_set_name(KQV, "KQV");
  1003. #else
  1004. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1005. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1006. // is there a better way?
  1007. 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));
  1008. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1009. #endif
  1010. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1011. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1012. ggml_set_name(KQV_merged, "KQV_merged");
  1013. // cur = KQV_merged.contiguous().view(n_embd, N)
  1014. cur = ggml_cpy(ctx0,
  1015. KQV_merged,
  1016. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1017. ggml_set_name(cur, "KQV_merged_contiguous");
  1018. // projection (no bias)
  1019. cur = ggml_mul_mat(ctx0,
  1020. model.layers[il].wo,
  1021. cur);
  1022. }
  1023. lctx.use_buf(ctx0, 1);
  1024. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1025. // feed-forward network
  1026. {
  1027. // norm
  1028. {
  1029. cur = ggml_rms_norm(ctx0, inpFF);
  1030. // cur = ffn_norm*cur
  1031. cur = ggml_mul(ctx0,
  1032. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  1033. cur);
  1034. }
  1035. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1036. model.layers[il].w3,
  1037. cur);
  1038. cur = ggml_mul_mat(ctx0,
  1039. model.layers[il].w1,
  1040. cur);
  1041. // SILU activation
  1042. cur = ggml_silu(ctx0, cur);
  1043. cur = ggml_mul(ctx0, cur, tmp);
  1044. cur = ggml_mul_mat(ctx0,
  1045. model.layers[il].w2,
  1046. cur);
  1047. }
  1048. cur = ggml_add(ctx0, cur, inpFF);
  1049. // input for next layer
  1050. inpL = cur;
  1051. }
  1052. lctx.use_buf(ctx0, 0);
  1053. // used at the end to optionally extract the embeddings
  1054. struct ggml_tensor * embeddings = NULL;
  1055. // norm
  1056. {
  1057. inpL = ggml_rms_norm(ctx0, inpL);
  1058. // inpL = norm*inpL
  1059. inpL = ggml_mul(ctx0,
  1060. ggml_repeat(ctx0, model.norm, inpL),
  1061. inpL);
  1062. embeddings = inpL;
  1063. }
  1064. // lm_head
  1065. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  1066. lctx.use_buf(ctx0, -1);
  1067. // logits -> probs
  1068. //inpL = ggml_soft_max(ctx0, inpL);
  1069. // run the computation
  1070. ggml_build_forward_expand(&gf, inpL);
  1071. ggml_graph_compute (ctx0, &gf);
  1072. #ifdef GGML_PERF
  1073. // print timing information per ggml operation (for debugging purposes)
  1074. // requires GGML_PERF to be defined
  1075. ggml_graph_print(&gf);
  1076. #endif
  1077. // plot the computation graph in dot format (for debugging purposes)
  1078. //if (n_past%100 == 0) {
  1079. // ggml_graph_dump_dot(&gf, NULL, "llama.dot");
  1080. //}
  1081. //embd_w.resize(n_vocab*N);
  1082. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1083. // update kv token count
  1084. lctx.model.kv_self.n = n_past + N;
  1085. // extract logits
  1086. {
  1087. auto & logits_out = lctx.logits;
  1088. if (lctx.logits_all) {
  1089. logits_out.resize(n_vocab * N);
  1090. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1091. } else {
  1092. // return result for just the last token
  1093. logits_out.resize(n_vocab);
  1094. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1095. }
  1096. }
  1097. // extract embeddings
  1098. if (lctx.embedding.size()) {
  1099. auto & embedding_out = lctx.embedding;
  1100. embedding_out.resize(n_embd);
  1101. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1102. }
  1103. if (mem_per_token == 0) {
  1104. mem_per_token = ggml_used_mem(ctx0)/N;
  1105. }
  1106. #if 0
  1107. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  1108. ggml_used_mem(ctx0)/1024.0/1024.0,
  1109. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  1110. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  1111. #endif
  1112. ggml_free(ctx0);
  1113. // measure the performance only for the single-token evals
  1114. if (N == 1) {
  1115. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1116. lctx.n_eval++;
  1117. }
  1118. else if (N > 1) {
  1119. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1120. lctx.n_p_eval += N;
  1121. }
  1122. return true;
  1123. }
  1124. //
  1125. // tokenizer
  1126. //
  1127. static size_t utf8_len(char src) {
  1128. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1129. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1130. return lookup[highbits];
  1131. }
  1132. struct llama_sp_symbol {
  1133. using index = int;
  1134. index prev;
  1135. index next;
  1136. const char * text;
  1137. size_t n;
  1138. };
  1139. struct llama_sp_bigram {
  1140. struct comparator {
  1141. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1142. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1143. }
  1144. };
  1145. using queue_storage = std::vector<llama_sp_bigram>;
  1146. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1147. llama_sp_symbol::index left;
  1148. llama_sp_symbol::index right;
  1149. float score;
  1150. size_t size;
  1151. };
  1152. // original implementation:
  1153. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1154. struct llama_tokenizer {
  1155. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1156. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1157. // split string into utf8 chars
  1158. int index = 0;
  1159. size_t offs = 0;
  1160. while (offs < text.size()) {
  1161. llama_sp_symbol sym;
  1162. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  1163. sym.text = text.c_str() + offs;
  1164. sym.n = char_len;
  1165. offs += char_len;
  1166. sym.prev = index - 1;
  1167. sym.next = offs == text.size() ? -1 : index + 1;
  1168. index++;
  1169. symbols_.emplace_back(std::move(sym));
  1170. }
  1171. // seed the work queue with all possible 2-character tokens.
  1172. for (size_t i = 1; i < symbols_.size(); ++i) {
  1173. try_add_bigram(i - 1, i);
  1174. }
  1175. // keep substituting the highest frequency pairs for as long as we can.
  1176. while (!work_queue_.empty()) {
  1177. auto bigram = work_queue_.top();
  1178. work_queue_.pop();
  1179. auto & left_sym = symbols_[bigram.left];
  1180. auto & right_sym = symbols_[bigram.right];
  1181. // if one of the symbols already got merged, skip it.
  1182. if (left_sym.n == 0 || right_sym.n == 0 ||
  1183. left_sym.n + right_sym.n != bigram.size) {
  1184. continue;
  1185. }
  1186. // merge the right sym into the left one
  1187. left_sym.n += right_sym.n;
  1188. right_sym.n = 0;
  1189. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1190. // remove the right sym from the chain
  1191. left_sym.next = right_sym.next;
  1192. if (right_sym.next >= 0) {
  1193. symbols_[right_sym.next].prev = bigram.left;
  1194. }
  1195. // find more substitutions
  1196. try_add_bigram(left_sym.prev, bigram.left);
  1197. try_add_bigram(bigram.left, left_sym.next);
  1198. }
  1199. for (int i = 0; i != -1; i = symbols_[i].next) {
  1200. auto & symbol = symbols_[i];
  1201. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  1202. if (token == vocab_.token_to_id.end()) {
  1203. // output any symbols that did not form tokens as bytes.
  1204. for (int j = 0; j < (int) symbol.n; ++j) {
  1205. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  1206. output.push_back(token_id);
  1207. }
  1208. } else {
  1209. output.push_back((*token).second);
  1210. }
  1211. }
  1212. }
  1213. private:
  1214. void try_add_bigram(int left, int right) {
  1215. if (left == -1 || right == -1) {
  1216. return;
  1217. }
  1218. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1219. auto token = vocab_.token_to_id.find(text);
  1220. if (token == vocab_.token_to_id.end()) {
  1221. return;
  1222. }
  1223. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1224. return;
  1225. }
  1226. const auto &tok_score = vocab_.id_to_token[(*token).second];
  1227. llama_sp_bigram bigram;
  1228. bigram.left = left;
  1229. bigram.right = right;
  1230. bigram.score = tok_score.score;
  1231. bigram.size = text.size();
  1232. work_queue_.push(bigram);
  1233. }
  1234. const llama_vocab & vocab_;
  1235. std::vector<llama_sp_symbol> symbols_;
  1236. llama_sp_bigram::queue work_queue_;
  1237. };
  1238. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  1239. llama_tokenizer tokenizer(vocab);
  1240. std::vector<llama_vocab::id> output;
  1241. if (text.size() == 0) {
  1242. return output;
  1243. }
  1244. if (bos) {
  1245. output.push_back(1);
  1246. }
  1247. tokenizer.tokenize(text, output);
  1248. return output;
  1249. }
  1250. //
  1251. // sampling
  1252. //
  1253. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  1254. assert(candidates->size > 0);
  1255. const int64_t t_start_sample_us = ggml_time_us();
  1256. // Sort the logits in descending order
  1257. if (!candidates->sorted) {
  1258. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  1259. return a.logit > b.logit;
  1260. });
  1261. candidates->sorted = true;
  1262. }
  1263. float max_l = candidates->data[0].logit;
  1264. float cum_sum = 0.0f;
  1265. for (size_t i = 0; i < candidates->size; ++i) {
  1266. float p = expf(candidates->data[i].logit - max_l);
  1267. candidates->data[i].p = p;
  1268. cum_sum += p;
  1269. }
  1270. for (size_t i = 0; i < candidates->size; ++i) {
  1271. candidates->data[i].p /= cum_sum;
  1272. }
  1273. if (ctx) {
  1274. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1275. }
  1276. }
  1277. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  1278. const int64_t t_start_sample_us = ggml_time_us();
  1279. k = std::max(k, (int) min_keep);
  1280. k = std::min(k, (int) candidates->size);
  1281. // Sort scores in descending order
  1282. if (!candidates->sorted) {
  1283. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  1284. return a.logit > b.logit;
  1285. };
  1286. if (k == (int) candidates->size) {
  1287. std::sort(candidates->data, candidates->data + candidates->size, comp);
  1288. } else {
  1289. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  1290. }
  1291. candidates->sorted = true;
  1292. }
  1293. candidates->size = k;
  1294. if (ctx) {
  1295. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1296. }
  1297. }
  1298. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  1299. if (p >= 1.0f) {
  1300. return;
  1301. }
  1302. const int64_t t_start_sample_us = ggml_time_us();
  1303. llama_sample_softmax(ctx, candidates);
  1304. // Compute the cumulative probabilities
  1305. float cum_sum = 0.0f;
  1306. size_t last_idx = candidates->size;
  1307. for (size_t i = 0; i < candidates->size; ++i) {
  1308. cum_sum += candidates->data[i].p;
  1309. // Check if the running sum is greater than p or if we have kept at least min_keep tokens
  1310. if (cum_sum > p && i >= min_keep) {
  1311. last_idx = i;
  1312. break;
  1313. }
  1314. }
  1315. // Resize the output vector to keep only the top-p tokens
  1316. candidates->size = last_idx;
  1317. if (ctx) {
  1318. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1319. }
  1320. }
  1321. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  1322. if (z >= 1.0f || candidates->size <= 2) {
  1323. return;
  1324. }
  1325. const int64_t t_start_sample_us = ggml_time_us();
  1326. llama_sample_softmax(nullptr, candidates);
  1327. // Compute the first and second derivatives
  1328. std::vector<float> first_derivatives(candidates->size - 1);
  1329. std::vector<float> second_derivatives(candidates->size - 2);
  1330. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  1331. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  1332. }
  1333. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1334. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  1335. }
  1336. // Calculate absolute value of second derivatives
  1337. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1338. second_derivatives[i] = abs(second_derivatives[i]);
  1339. }
  1340. // Normalize the second derivatives
  1341. float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  1342. for (float & value : second_derivatives) {
  1343. value /= second_derivatives_sum;
  1344. }
  1345. float cum_sum = 0.0f;
  1346. size_t last_idx = candidates->size;
  1347. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  1348. cum_sum += second_derivatives[i];
  1349. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  1350. if (cum_sum > z && i >= min_keep) {
  1351. last_idx = i;
  1352. break;
  1353. }
  1354. }
  1355. // Resize the output vector to keep only the tokens above the tail location
  1356. candidates->size = last_idx;
  1357. if (ctx) {
  1358. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1359. }
  1360. }
  1361. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  1362. // Reference implementation:
  1363. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  1364. if (p >= 1.0f) {
  1365. return;
  1366. }
  1367. const int64_t t_start_sample_us = ggml_time_us();
  1368. // Compute the softmax of logits and calculate entropy
  1369. llama_sample_softmax(nullptr, candidates);
  1370. float entropy = 0.0f;
  1371. for (size_t i = 0; i < candidates->size; ++i) {
  1372. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  1373. }
  1374. // Compute the absolute difference between negative log probability and entropy for each candidate
  1375. std::vector<float> shifted_scores;
  1376. for (size_t i = 0; i < candidates->size; ++i) {
  1377. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  1378. shifted_scores.push_back(shifted_score);
  1379. }
  1380. // Sort tokens based on the shifted_scores and their corresponding indices
  1381. std::vector<size_t> indices(candidates->size);
  1382. std::iota(indices.begin(), indices.end(), 0);
  1383. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  1384. return shifted_scores[a] < shifted_scores[b];
  1385. });
  1386. // Compute the cumulative probabilities
  1387. float cum_sum = 0.0f;
  1388. size_t last_idx = indices.size();
  1389. for (size_t i = 0; i < indices.size(); ++i) {
  1390. size_t idx = indices[i];
  1391. cum_sum += candidates->data[idx].p;
  1392. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  1393. if (cum_sum > p && i >= min_keep - 1) {
  1394. last_idx = i + 1;
  1395. break;
  1396. }
  1397. }
  1398. // Resize the output vector to keep only the locally typical tokens
  1399. std::vector<llama_token_data> new_candidates;
  1400. for (size_t i = 0; i < last_idx; ++i) {
  1401. size_t idx = indices[i];
  1402. new_candidates.push_back(candidates->data[idx]);
  1403. }
  1404. // Replace the data in candidates with the new_candidates data
  1405. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  1406. candidates->size = new_candidates.size();
  1407. if (ctx) {
  1408. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1409. }
  1410. }
  1411. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  1412. const int64_t t_start_sample_us = ggml_time_us();
  1413. for (size_t i = 0; i < candidates_p->size; ++i) {
  1414. candidates_p->data[i].logit /= temp;
  1415. }
  1416. if (ctx) {
  1417. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1418. }
  1419. }
  1420. 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) {
  1421. if (last_tokens_size == 0 || penalty == 1.0f) {
  1422. return;
  1423. }
  1424. const int64_t t_start_sample_us = ggml_time_us();
  1425. for (size_t i = 0; i < candidates->size; ++i) {
  1426. auto token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  1427. if (token_iter == last_tokens + last_tokens_size) {
  1428. continue;
  1429. }
  1430. // 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.
  1431. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  1432. if (candidates->data[i].logit <= 0) {
  1433. candidates->data[i].logit *= penalty;
  1434. } else {
  1435. candidates->data[i].logit /= penalty;
  1436. }
  1437. }
  1438. candidates->sorted = false;
  1439. if (ctx) {
  1440. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1441. }
  1442. }
  1443. 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) {
  1444. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  1445. return;
  1446. }
  1447. const int64_t t_start_sample_us = ggml_time_us();
  1448. // Create a frequency map to count occurrences of each token in last_tokens
  1449. std::unordered_map<llama_token, int> token_count;
  1450. for (size_t i = 0; i < last_tokens_size; ++i) {
  1451. token_count[last_tokens_p[i]]++;
  1452. }
  1453. // Apply frequency and presence penalties to the candidates
  1454. for (size_t i = 0; i < candidates->size; ++i) {
  1455. auto token_iter = token_count.find(candidates->data[i].id);
  1456. if (token_iter == token_count.end()) {
  1457. continue;
  1458. }
  1459. int count = token_iter->second;
  1460. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  1461. }
  1462. candidates->sorted = false;
  1463. if (ctx) {
  1464. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1465. }
  1466. }
  1467. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  1468. assert(ctx);
  1469. auto N = float(llama_n_vocab(ctx));
  1470. int64_t t_start_sample_us;
  1471. t_start_sample_us = ggml_time_us();
  1472. llama_sample_softmax(nullptr, candidates);
  1473. // Estimate s_hat using the most probable m tokens
  1474. float s_hat = 0.0;
  1475. float sum_ti_bi = 0.0;
  1476. float sum_ti_sq = 0.0;
  1477. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  1478. float t_i = logf(float(i + 2) / float(i + 1));
  1479. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  1480. sum_ti_bi += t_i * b_i;
  1481. sum_ti_sq += t_i * t_i;
  1482. }
  1483. s_hat = sum_ti_bi / sum_ti_sq;
  1484. // Compute k from the estimated s_hat and target surprise value
  1485. float epsilon_hat = s_hat - 1;
  1486. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  1487. // Sample the next word X using top-k sampling
  1488. llama_sample_top_k(nullptr, candidates, int(k), 1);
  1489. if (ctx) {
  1490. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1491. }
  1492. llama_token X = llama_sample_token(ctx, candidates);
  1493. t_start_sample_us = ggml_time_us();
  1494. // Compute error as the difference between observed surprise and target surprise value
  1495. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1496. return candidate.id == X;
  1497. }));
  1498. float observed_surprise = -log2f(candidates->data[X_idx].p);
  1499. float e = observed_surprise - tau;
  1500. // Update mu using the learning rate and error
  1501. *mu = *mu - eta * e;
  1502. if (ctx) {
  1503. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1504. ctx->n_sample++;
  1505. }
  1506. return X;
  1507. }
  1508. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  1509. assert(ctx);
  1510. int64_t t_start_sample_us;
  1511. t_start_sample_us = ggml_time_us();
  1512. llama_sample_softmax(ctx, candidates);
  1513. // Truncate the words with surprise values greater than mu
  1514. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1515. return -log2f(candidate.p) > *mu;
  1516. }));
  1517. // Normalize the probabilities of the remaining words
  1518. llama_sample_softmax(ctx, candidates);
  1519. // Sample the next word X from the remaining words
  1520. if (ctx) {
  1521. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1522. }
  1523. llama_token X = llama_sample_token(ctx, candidates);
  1524. t_start_sample_us = ggml_time_us();
  1525. // Compute error as the difference between observed surprise and target surprise value
  1526. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  1527. return candidate.id == X;
  1528. }));
  1529. float observed_surprise = -log2f(candidates->data[X_idx].p);
  1530. float e = observed_surprise - tau;
  1531. // Update mu using the learning rate and error
  1532. *mu = *mu - eta * e;
  1533. if (ctx) {
  1534. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1535. }
  1536. return X;
  1537. }
  1538. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  1539. const int64_t t_start_sample_us = ggml_time_us();
  1540. // Find max element
  1541. auto max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  1542. return a.logit < b.logit;
  1543. });
  1544. llama_token result = max_iter->id;
  1545. if (ctx) {
  1546. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1547. ctx->n_sample++;
  1548. }
  1549. return result;
  1550. }
  1551. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  1552. assert(ctx);
  1553. const int64_t t_start_sample_us = ggml_time_us();
  1554. llama_sample_softmax(nullptr, candidates);
  1555. std::vector<float> probs;
  1556. probs.reserve(candidates->size);
  1557. for (size_t i = 0; i < candidates->size; ++i) {
  1558. probs.push_back(candidates->data[i].p);
  1559. }
  1560. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1561. auto & rng = ctx->rng;
  1562. int idx = dist(rng);
  1563. llama_token result = candidates->data[idx].id;
  1564. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1565. ctx->n_sample++;
  1566. return result;
  1567. }
  1568. //
  1569. // quantization
  1570. //
  1571. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, enum llama_ftype ftype, int nthread) {
  1572. ggml_type quantized_type;
  1573. switch (ftype) {
  1574. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  1575. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  1576. case LLAMA_FTYPE_MOSTLY_Q4_2: quantized_type = GGML_TYPE_Q4_2; break;
  1577. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  1578. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  1579. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  1580. default: throw format("invalid output file type %d\n", ftype);
  1581. };
  1582. if (nthread <= 0) {
  1583. nthread = std::thread::hardware_concurrency();
  1584. }
  1585. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp.c_str(), /*use_mmap*/ false,
  1586. /*vocab_only*/ false));
  1587. llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loaders.at(0).get(), ftype);
  1588. size_t total_size_org = 0;
  1589. size_t total_size_new = 0;
  1590. std::vector<int64_t> hist_all(1 << 4, 0);
  1591. std::vector<std::thread> workers;
  1592. std::mutex mutex;
  1593. size_t idx = 0;
  1594. for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
  1595. llama_buffer read_data;
  1596. read_data.resize(tensor.size);
  1597. tensor.data = read_data.addr;
  1598. model_loader->load_data_for(tensor);
  1599. printf("[%4zu/%4zu] %36s - %16s, type = %6s, ",
  1600. ++idx, model_loader->tensors_map.tensors.size(),
  1601. tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
  1602. ggml_type_name(tensor.type));
  1603. // This used to be a regex, but <regex> has an extreme cost to compile times.
  1604. bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
  1605. // quantize only 2D tensors
  1606. quantize &= (tensor.ne.size() == 2);
  1607. // uncomment this to keep the output layer in FP16
  1608. //if (tensor.name == "output.weight") {
  1609. // quantize = false;
  1610. //}
  1611. enum ggml_type new_type;
  1612. void * new_data;
  1613. size_t new_size;
  1614. llama_buffer work;
  1615. if (!quantize) {
  1616. new_type = tensor.type;
  1617. new_data = tensor.data;
  1618. new_size = tensor.size;
  1619. printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
  1620. } else {
  1621. new_type = quantized_type;
  1622. float * f32_data;
  1623. size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
  1624. llama_buffer f32_conv_buf;
  1625. if (tensor.type == GGML_TYPE_F32) {
  1626. f32_data = (float *) tensor.data;
  1627. } else if (tensor.type == GGML_TYPE_F16) {
  1628. f32_conv_buf.resize(nelements * sizeof(float));
  1629. f32_data = (float *) f32_conv_buf.addr;
  1630. auto f16_data = (const ggml_fp16_t *) tensor.data;
  1631. for (size_t i = 0; i < nelements; i++) {
  1632. f32_data[i] = ggml_fp16_to_fp32(f16_data[i]);
  1633. }
  1634. } else {
  1635. throw format("type %s unsupported for integer quantization", ggml_type_name(tensor.type));
  1636. }
  1637. printf("quantizing .. ");
  1638. fflush(stdout);
  1639. work.resize(nelements * 4); // upper bound on size
  1640. new_data = work.addr;
  1641. std::vector<int64_t> hist_cur(1 << 4, 0);
  1642. int chunk_size = 32 * 512;
  1643. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  1644. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  1645. if (nthread_use < 2) {
  1646. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  1647. } else {
  1648. size_t counter = 0;
  1649. new_size = 0;
  1650. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements, chunk_size] () {
  1651. std::vector<int64_t> local_hist;
  1652. size_t local_size = 0;
  1653. while (true) {
  1654. std::unique_lock<std::mutex> lock(mutex);
  1655. size_t first = counter; counter += chunk_size;
  1656. if (first >= nelements) {
  1657. if (!local_hist.empty()) {
  1658. for (int j=0; j<int(local_hist.size()); ++j) hist_cur[j] += local_hist[j];
  1659. new_size += local_size;
  1660. }
  1661. break;
  1662. }
  1663. lock.unlock();
  1664. size_t last = std::min(nelements, first + chunk_size);
  1665. if (local_hist.empty()) local_hist.resize(hist_cur.size(), 0);
  1666. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  1667. }
  1668. };
  1669. if (int(workers.size()) < nthread_use - 1) workers.resize(nthread_use - 1);
  1670. for (int it = 0; it < nthread_use - 1; ++it) workers[it] = std::thread(compute);
  1671. compute();
  1672. for (int it = 0; it < nthread_use - 1; ++it) workers[it].join();
  1673. }
  1674. printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
  1675. for (size_t i = 0; i < hist_cur.size(); i++) {
  1676. hist_all[i] += hist_cur[i];
  1677. }
  1678. for (size_t i = 0; i < hist_cur.size(); i++) {
  1679. printf("%5.3f ", hist_cur[i] / float(nelements));
  1680. }
  1681. printf("\n");
  1682. }
  1683. total_size_org += tensor.size;
  1684. total_size_new += new_size;
  1685. file_saver.write_tensor(tensor, new_type, new_data, new_size);
  1686. }
  1687. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1688. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1689. {
  1690. int64_t sum_all = 0;
  1691. for (size_t i = 0; i < hist_all.size(); i++) {
  1692. sum_all += hist_all[i];
  1693. }
  1694. printf("%s: hist: ", __func__);
  1695. for (size_t i = 0; i < hist_all.size(); i++) {
  1696. printf("%5.3f ", hist_all[i] / float(sum_all));
  1697. }
  1698. printf("\n");
  1699. }
  1700. }
  1701. //
  1702. // interface implementation
  1703. //
  1704. struct llama_context * llama_init_from_file(
  1705. const char * path_model,
  1706. struct llama_context_params params) {
  1707. ggml_time_init();
  1708. llama_context * ctx = new llama_context;
  1709. if (params.seed < 0) {
  1710. params.seed = time(NULL);
  1711. }
  1712. unsigned cur_percentage = 0;
  1713. if (params.progress_callback == NULL) {
  1714. params.progress_callback_user_data = &cur_percentage;
  1715. params.progress_callback = [](float progress, void * ctx) {
  1716. unsigned * cur_percentage_p = (unsigned *) ctx;
  1717. unsigned percentage = (unsigned) (100 * progress);
  1718. while (percentage > *cur_percentage_p) {
  1719. ++*cur_percentage_p;
  1720. fprintf(stderr, ".");
  1721. fflush(stderr);
  1722. if (percentage >= 100) {
  1723. fprintf(stderr, "\n");
  1724. }
  1725. }
  1726. };
  1727. }
  1728. ctx->rng = std::mt19937(params.seed);
  1729. ctx->logits_all = params.logits_all;
  1730. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1731. if (!llama_model_load(path_model, *ctx, params.n_ctx, memory_type,
  1732. params.use_mmap, params.use_mlock, params.vocab_only,
  1733. params.progress_callback, params.progress_callback_user_data)) {
  1734. fprintf(stderr, "%s: failed to load model\n", __func__);
  1735. llama_free(ctx);
  1736. return nullptr;
  1737. }
  1738. // reserve memory for context buffers
  1739. if (!params.vocab_only) {
  1740. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1741. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1742. llama_free(ctx);
  1743. return nullptr;
  1744. }
  1745. {
  1746. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1747. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1748. }
  1749. const auto & hparams = ctx->model.hparams;
  1750. // resized during inference
  1751. if (params.logits_all) {
  1752. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1753. } else {
  1754. ctx->logits.reserve(hparams.n_vocab);
  1755. }
  1756. if (params.embedding){
  1757. ctx->embedding.resize(hparams.n_embd);
  1758. }
  1759. ctx->buf_compute.resize(MEM_REQ_EVAL().at(ctx->model.type));
  1760. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0().at(ctx->model.type));
  1761. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1().at(ctx->model.type));
  1762. }
  1763. return ctx;
  1764. }
  1765. void llama_free(struct llama_context * ctx) {
  1766. delete ctx;
  1767. }
  1768. int llama_model_quantize(
  1769. const char * fname_inp,
  1770. const char * fname_out,
  1771. enum llama_ftype ftype,
  1772. int nthread) {
  1773. try {
  1774. llama_model_quantize_internal(fname_inp, fname_out, ftype, nthread);
  1775. return 0;
  1776. } catch (const std::string & err) {
  1777. fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.c_str());
  1778. return 1;
  1779. }
  1780. }
  1781. int llama_apply_lora_from_file_internal(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  1782. fprintf(stderr, "%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  1783. auto & model = ctx->model;
  1784. const int64_t t_start_lora_us = ggml_time_us();
  1785. auto fin = std::ifstream(path_lora, std::ios::binary);
  1786. if (!fin) {
  1787. fprintf(stderr, "%s: failed to open '%s'\n", __func__, path_lora);
  1788. return 1;
  1789. }
  1790. // verify magic and version
  1791. {
  1792. uint32_t magic;
  1793. fin.read((char *) &magic, sizeof(magic));
  1794. if (magic != 'ggla') {
  1795. fprintf(stderr, "%s: bad file magic\n", __func__);
  1796. return 1;
  1797. }
  1798. uint32_t format_version;
  1799. fin.read((char *) &format_version, sizeof(format_version));
  1800. if (format_version != 1) {
  1801. fprintf(stderr, "%s: unsupported file version\n", __func__ );
  1802. return 1;
  1803. }
  1804. }
  1805. int32_t lora_r;
  1806. int32_t lora_alpha;
  1807. fin.read((char *) &lora_r, sizeof(lora_r));
  1808. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  1809. float scaling = (float)lora_alpha / (float)lora_r;
  1810. fprintf(stderr, "%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  1811. // create a temporary ggml context to store the lora tensors
  1812. // todo: calculate size from biggest possible tensor
  1813. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  1814. struct ggml_init_params params;
  1815. params.mem_size = lora_buf.size();
  1816. params.mem_buffer = lora_buf.data();
  1817. params.no_alloc = false;
  1818. ggml_context * lora_ctx = ggml_init(params);
  1819. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  1820. // create a name -> tensor map of the model to accelerate lookups
  1821. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  1822. for (auto & kv: model.tensors_by_name) {
  1823. model_tensors.insert(kv);
  1824. }
  1825. // load base model
  1826. std::unique_ptr<llama_model_loader> model_loader;
  1827. ggml_context * base_ctx = NULL;
  1828. llama_buffer base_buf;
  1829. if (path_base_model) {
  1830. fprintf(stderr, "%s: loading base model from '%s'\n", __func__, path_base_model);
  1831. model_loader.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*vocab_only*/ false));
  1832. size_t ctx_size, mmapped_size;
  1833. model_loader->calc_sizes(&ctx_size, &mmapped_size);
  1834. base_buf.resize(ctx_size);
  1835. ggml_init_params base_params;
  1836. base_params.mem_size = base_buf.size;
  1837. base_params.mem_buffer = base_buf.addr;
  1838. base_params.no_alloc = model_loader->use_mmap;
  1839. base_ctx = ggml_init(base_params);
  1840. model_loader->ggml_ctx = base_ctx;
  1841. // maybe this should in llama_model_loader
  1842. if (model_loader->use_mmap) {
  1843. model_loader->mapping.reset(new llama_mmap(&model_loader->file_loaders.at(0)->file, /* prefetch */ false));
  1844. }
  1845. }
  1846. // read tensors and apply
  1847. bool warned = false;
  1848. int n_tensors = 0;
  1849. while (true) {
  1850. int32_t n_dims;
  1851. int32_t length;
  1852. int32_t ftype;
  1853. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1854. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  1855. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1856. if (fin.eof()) {
  1857. break;
  1858. }
  1859. int32_t ne[2] = { 1, 1 };
  1860. for (int i = 0; i < n_dims; ++i) {
  1861. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1862. }
  1863. std::string name(length, 0);
  1864. fin.read(&name[0], length);
  1865. // check for lora suffix and get the type of tensor
  1866. const std::string lora_suffix = ".lora";
  1867. size_t pos = name.rfind(lora_suffix);
  1868. if (pos == std::string::npos) {
  1869. fprintf(stderr, "%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  1870. return 1;
  1871. }
  1872. std::string lora_type = name.substr(pos + lora_suffix.length());
  1873. std::string base_name = name;
  1874. base_name.erase(pos);
  1875. // fprintf(stderr, "%s: %s => %s (lora type %s) ", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  1876. if (model_tensors.find(base_name.data()) == model_tensors.end()) {
  1877. fprintf(stderr, "%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  1878. return 1;
  1879. }
  1880. // create ggml tensor
  1881. ggml_type wtype;
  1882. switch (ftype) {
  1883. case 0: wtype = GGML_TYPE_F32; break;
  1884. case 1: wtype = GGML_TYPE_F16; break;
  1885. default:
  1886. {
  1887. fprintf(stderr, "%s: invalid tensor data type '%d'\n",
  1888. __func__, ftype);
  1889. return false;
  1890. }
  1891. }
  1892. ggml_tensor* lora_tensor;
  1893. if (n_dims == 2) {
  1894. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  1895. }
  1896. else {
  1897. fprintf(stderr, "%s: unsupported tensor dimension %d\n", __func__, n_dims);
  1898. return 1;
  1899. }
  1900. // load tensor data
  1901. size_t offset = fin.tellg();
  1902. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  1903. offset = (offset + 31) & -32;
  1904. fin.seekg(offset);
  1905. fin.read((char*)lora_tensor->data, tensor_data_size);
  1906. lora_tensors[name] = lora_tensor;
  1907. // check if we have both A and B tensors and apply
  1908. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  1909. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  1910. ggml_tensor * dest_t = model_tensors[base_name];
  1911. ggml_tensor * base_t;
  1912. if (model_loader) {
  1913. // load from base model
  1914. if (model_loader->tensors_map.name_to_idx.find(base_name) == model_loader->tensors_map.name_to_idx.end()) {
  1915. fprintf(stderr, "%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  1916. return 1;
  1917. }
  1918. size_t idx = model_loader->tensors_map.name_to_idx[base_name];
  1919. llama_load_tensor & lt = model_loader->tensors_map.tensors[idx];
  1920. base_t = model_loader->get_tensor(base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] });
  1921. lt.data = (uint8_t *) lt.ggml_tensor->data;
  1922. model_loader->load_data_for(lt);
  1923. lt.ggml_tensor->data = lt.data;
  1924. }
  1925. else {
  1926. base_t = dest_t;
  1927. }
  1928. if (ggml_is_quantized(base_t->type)) {
  1929. if (!warned) {
  1930. fprintf(stderr, "%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  1931. "use a f16 or f32 base model with --lora-base\n", __func__);
  1932. warned = true;
  1933. }
  1934. }
  1935. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  1936. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  1937. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  1938. fprintf(stderr, "%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  1939. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  1940. return 1;
  1941. }
  1942. // w = w + BA*s
  1943. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  1944. if (scaling != 1.0f) {
  1945. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  1946. BA = ggml_scale(lora_ctx, BA, scale_tensor);
  1947. }
  1948. ggml_tensor * r;
  1949. if (base_t == dest_t) {
  1950. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  1951. }
  1952. else {
  1953. r = ggml_add(lora_ctx, base_t, BA);
  1954. r = ggml_cpy(lora_ctx, r, dest_t);
  1955. }
  1956. struct ggml_cgraph gf = ggml_build_forward(r);
  1957. gf.n_threads = n_threads;
  1958. ggml_graph_compute(lora_ctx, &gf);
  1959. // we won't need these tensors again, reset the context to save memory
  1960. ggml_free(lora_ctx);
  1961. lora_ctx = ggml_init(params);
  1962. lora_tensors.clear();
  1963. n_tensors++;
  1964. if (n_tensors % 4 == 0)
  1965. fprintf(stderr, ".");
  1966. }
  1967. }
  1968. // TODO: this should be in a destructor, it will leak on failure
  1969. ggml_free(lora_ctx);
  1970. if (base_ctx) {
  1971. ggml_free(base_ctx);
  1972. }
  1973. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  1974. fprintf(stderr, " done (%.2f ms)\n", t_lora_us / 1000.0);
  1975. return 0;
  1976. }
  1977. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  1978. try {
  1979. return llama_apply_lora_from_file_internal(ctx, path_lora, path_base_model, n_threads);
  1980. } catch (const std::string & err) {
  1981. fprintf(stderr, "%s: failed to apply lora adapter: %s\n", __func__, err.c_str());
  1982. return 1;
  1983. }
  1984. }
  1985. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  1986. return ctx->model.kv_self.n;
  1987. }
  1988. #define LLAMA_MAX_RNG_STATE 64*1024
  1989. void llama_set_rng_seed(struct llama_context * ctx, int seed) {
  1990. if (seed < 0) {
  1991. seed = time(NULL);
  1992. }
  1993. ctx->rng.seed(seed);
  1994. }
  1995. // Returns the *maximum* size of the state
  1996. size_t llama_get_state_size(const struct llama_context * ctx) {
  1997. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  1998. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  1999. const size_t s_rng_size = sizeof(size_t);
  2000. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  2001. const size_t s_logits_capacity = sizeof(size_t);
  2002. const size_t s_logits_size = sizeof(size_t);
  2003. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  2004. const size_t s_embedding_size = sizeof(size_t);
  2005. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  2006. const size_t s_kv_size = sizeof(size_t);
  2007. const size_t s_kv_ntok = sizeof(int);
  2008. const size_t s_kv = ctx->model.kv_self.buf.size;
  2009. const size_t s_total = (
  2010. + s_rng_size
  2011. + s_rng
  2012. + s_logits_capacity
  2013. + s_logits_size
  2014. + s_logits
  2015. + s_embedding_size
  2016. + s_embedding
  2017. + s_kv_size
  2018. + s_kv_ntok
  2019. + s_kv
  2020. );
  2021. return s_total;
  2022. }
  2023. // Copies the state to the specified destination address
  2024. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dest) {
  2025. uint8_t * out = dest;
  2026. // copy rng
  2027. {
  2028. std::stringstream rng_ss;
  2029. rng_ss << ctx->rng;
  2030. const size_t rng_size = rng_ss.str().size();
  2031. char rng_buf[LLAMA_MAX_RNG_STATE];
  2032. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  2033. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  2034. memcpy(out, &rng_size, sizeof(rng_size)); out += sizeof(rng_size);
  2035. memcpy(out, &rng_buf[0], LLAMA_MAX_RNG_STATE); out += LLAMA_MAX_RNG_STATE;
  2036. }
  2037. // copy logits
  2038. {
  2039. const size_t logits_cap = ctx->logits.capacity();
  2040. const size_t logits_size = ctx->logits.size();
  2041. memcpy(out, &logits_cap, sizeof(logits_cap)); out += sizeof(logits_cap);
  2042. memcpy(out, &logits_size, sizeof(logits_size)); out += sizeof(logits_size);
  2043. if (logits_size) {
  2044. memcpy(out, ctx->logits.data(), logits_size * sizeof(float));
  2045. }
  2046. out += logits_cap * sizeof(float);
  2047. }
  2048. // copy embeddings
  2049. {
  2050. const size_t embedding_size = ctx->embedding.size();
  2051. memcpy(out, &embedding_size, sizeof(embedding_size)); out += sizeof(embedding_size);
  2052. if (embedding_size) {
  2053. memcpy(out, ctx->embedding.data(), embedding_size * sizeof(float));
  2054. out += embedding_size * sizeof(float);
  2055. }
  2056. }
  2057. // copy kv cache
  2058. {
  2059. const auto & kv_self = ctx->model.kv_self;
  2060. const auto & hparams = ctx->model.hparams;
  2061. const int n_layer = hparams.n_layer;
  2062. const int n_embd = hparams.n_embd;
  2063. const int n_ctx = hparams.n_ctx;
  2064. const size_t kv_size = kv_self.buf.size;
  2065. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  2066. memcpy(out, &kv_size, sizeof(kv_size)); out += sizeof(kv_size);
  2067. memcpy(out, &kv_ntok, sizeof(kv_ntok)); out += sizeof(kv_ntok);
  2068. if (kv_size) {
  2069. const size_t elt_size = ggml_element_size(kv_self.k);
  2070. char buffer[4096];
  2071. ggml_context * cpy_ctx = ggml_init({ sizeof(buffer), buffer, /* no_alloc */ true });
  2072. ggml_cgraph gf{};
  2073. gf.n_threads = 1;
  2074. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  2075. kout3d->data = out;
  2076. out += ggml_nbytes(kout3d);
  2077. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  2078. vout3d->data = out;
  2079. out += ggml_nbytes(vout3d);
  2080. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  2081. n_embd, kv_ntok, n_layer,
  2082. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  2083. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  2084. kv_ntok, n_embd, n_layer,
  2085. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  2086. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  2087. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  2088. ggml_graph_compute(cpy_ctx, &gf);
  2089. }
  2090. }
  2091. const size_t written = out - dest;
  2092. const size_t max_size = llama_get_state_size(ctx);
  2093. LLAMA_ASSERT(written <= max_size);
  2094. return written;
  2095. }
  2096. // Sets the state reading from the specified source address
  2097. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  2098. const uint8_t * in = src;
  2099. // set rng
  2100. {
  2101. size_t rng_size;
  2102. char rng_buf[LLAMA_MAX_RNG_STATE];
  2103. memcpy(&rng_size, in, sizeof(rng_size)); in += sizeof(rng_size);
  2104. memcpy(&rng_buf[0], in, LLAMA_MAX_RNG_STATE); in += LLAMA_MAX_RNG_STATE;
  2105. std::stringstream rng_ss;
  2106. rng_ss.str(std::string(&rng_buf[0], rng_size));
  2107. rng_ss >> ctx->rng;
  2108. LLAMA_ASSERT(rng_ss.fail() == false);
  2109. }
  2110. // set logits
  2111. {
  2112. size_t logits_cap;
  2113. size_t logits_size;
  2114. memcpy(&logits_cap, in, sizeof(logits_cap)); in += sizeof(logits_cap);
  2115. memcpy(&logits_size, in, sizeof(logits_size)); in += sizeof(logits_size);
  2116. LLAMA_ASSERT(ctx->logits.capacity() == logits_cap);
  2117. if (logits_size) {
  2118. ctx->logits.resize(logits_size);
  2119. memcpy(ctx->logits.data(), in, logits_size * sizeof(float));
  2120. }
  2121. in += logits_cap * sizeof(float);
  2122. }
  2123. // set embeddings
  2124. {
  2125. size_t embedding_size;
  2126. memcpy(&embedding_size, in, sizeof(embedding_size)); in += sizeof(embedding_size);
  2127. LLAMA_ASSERT(ctx->embedding.capacity() == embedding_size);
  2128. if (embedding_size) {
  2129. memcpy(ctx->embedding.data(), in, embedding_size * sizeof(float));
  2130. in += embedding_size * sizeof(float);
  2131. }
  2132. }
  2133. // set kv cache
  2134. {
  2135. const auto & kv_self = ctx->model.kv_self;
  2136. const auto & hparams = ctx->model.hparams;
  2137. const int n_layer = hparams.n_layer;
  2138. const int n_embd = hparams.n_embd;
  2139. const int n_ctx = hparams.n_ctx;
  2140. size_t kv_size;
  2141. int kv_ntok;
  2142. memcpy(&kv_size, in, sizeof(kv_size)); in += sizeof(kv_size);
  2143. memcpy(&kv_ntok, in, sizeof(kv_ntok)); in += sizeof(kv_ntok);
  2144. if (kv_size) {
  2145. LLAMA_ASSERT(kv_self.buf.size == kv_size);
  2146. const size_t elt_size = ggml_element_size(kv_self.k);
  2147. char buffer[4096];
  2148. ggml_context * cpy_ctx = ggml_init({ sizeof(buffer), buffer, /* no_alloc */ true });
  2149. ggml_cgraph gf{};
  2150. gf.n_threads = 1;
  2151. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  2152. kin3d->data = (void *) in;
  2153. in += ggml_nbytes(kin3d);
  2154. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  2155. vin3d->data = (void *) in;
  2156. in += ggml_nbytes(vin3d);
  2157. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  2158. n_embd, kv_ntok, n_layer,
  2159. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  2160. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  2161. kv_ntok, n_embd, n_layer,
  2162. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  2163. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  2164. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  2165. ggml_graph_compute(cpy_ctx, &gf);
  2166. }
  2167. ctx->model.kv_self.n = kv_ntok;
  2168. }
  2169. const size_t nread = in - src;
  2170. const size_t max_size = llama_get_state_size(ctx);
  2171. LLAMA_ASSERT(nread <= max_size);
  2172. return nread;
  2173. }
  2174. 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) {
  2175. llama_file file(path_session, "rb");
  2176. // sanity checks
  2177. {
  2178. const uint32_t magic = file.read_u32();
  2179. const uint32_t version = file.read_u32();
  2180. if (!(magic == LLAMA_SESSION_MAGIC && version == LLAMA_SESSION_VERSION)) {
  2181. fprintf(stderr, "%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  2182. return false;
  2183. }
  2184. llama_hparams session_hparams;
  2185. file.read_raw(&session_hparams, sizeof(llama_hparams));
  2186. if (session_hparams != ctx->model.hparams) {
  2187. fprintf(stderr, "%s : model hparams didn't match from session file!\n", __func__);
  2188. return false;
  2189. }
  2190. }
  2191. // load the prompt
  2192. {
  2193. const uint32_t n_token_count = file.read_u32();
  2194. if (n_token_count > n_token_capacity) {
  2195. fprintf(stderr, "%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  2196. return false;
  2197. }
  2198. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  2199. *n_token_count_out = n_token_count;
  2200. }
  2201. // restore the context state
  2202. {
  2203. const size_t n_state_size_cur = file.size - file.tell();
  2204. const size_t n_state_size_max = llama_get_state_size(ctx);
  2205. if (n_state_size_cur > n_state_size_max) {
  2206. 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);
  2207. return false;
  2208. }
  2209. std::vector<uint8_t> state_data(n_state_size_max);
  2210. file.read_raw(state_data.data(), n_state_size_cur);
  2211. llama_set_state_data(ctx, state_data.data());
  2212. }
  2213. return true;
  2214. }
  2215. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  2216. llama_file file(path_session, "wb");
  2217. file.write_u32(LLAMA_SESSION_MAGIC);
  2218. file.write_u32(LLAMA_SESSION_VERSION);
  2219. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  2220. // save the prompt
  2221. file.write_u32((uint32_t) n_token_count);
  2222. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  2223. // save the context state
  2224. {
  2225. const size_t n_state_size_max = llama_get_state_size(ctx);
  2226. std::vector<uint8_t> state_data(n_state_size_max);
  2227. const size_t n_state_size_cur = llama_copy_state_data(ctx, state_data.data());
  2228. file.write_raw(state_data.data(), n_state_size_cur);
  2229. }
  2230. return true;
  2231. }
  2232. int llama_eval(
  2233. struct llama_context * ctx,
  2234. const llama_token * tokens,
  2235. int n_tokens,
  2236. int n_past,
  2237. int n_threads) {
  2238. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  2239. fprintf(stderr, "%s: failed to eval\n", __func__);
  2240. return 1;
  2241. }
  2242. // get a more accurate load time, upon first eval
  2243. if (!ctx->has_evaluated_once) {
  2244. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  2245. ctx->has_evaluated_once = true;
  2246. }
  2247. return 0;
  2248. }
  2249. int llama_tokenize(
  2250. struct llama_context * ctx,
  2251. const char * text,
  2252. llama_token * tokens,
  2253. int n_max_tokens,
  2254. bool add_bos) {
  2255. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  2256. if (n_max_tokens < (int) res.size()) {
  2257. fprintf(stderr, "%s: too many tokens\n", __func__);
  2258. return -((int) res.size());
  2259. }
  2260. for (size_t i = 0; i < res.size(); i++) {
  2261. tokens[i] = res[i];
  2262. }
  2263. return res.size();
  2264. }
  2265. int llama_n_vocab(const struct llama_context * ctx) {
  2266. return ctx->vocab.id_to_token.size();
  2267. }
  2268. int llama_n_ctx(const struct llama_context * ctx) {
  2269. return ctx->model.hparams.n_ctx;
  2270. }
  2271. int llama_n_embd(const struct llama_context * ctx) {
  2272. return ctx->model.hparams.n_embd;
  2273. }
  2274. float * llama_get_logits(struct llama_context * ctx) {
  2275. return ctx->logits.data();
  2276. }
  2277. float * llama_get_embeddings(struct llama_context * ctx) {
  2278. return ctx->embedding.data();
  2279. }
  2280. const char * llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  2281. if (token >= llama_n_vocab(ctx)) {
  2282. return nullptr;
  2283. }
  2284. return ctx->vocab.id_to_token[token].tok.c_str();
  2285. }
  2286. llama_token llama_token_bos() {
  2287. return 1;
  2288. }
  2289. llama_token llama_token_eos() {
  2290. return 2;
  2291. }
  2292. llama_token llama_token_nl() {
  2293. return 13;
  2294. }
  2295. void llama_print_timings(struct llama_context * ctx) {
  2296. const int64_t t_end_us = ggml_time_us();
  2297. const int32_t n_sample = std::max(1, ctx->n_sample);
  2298. const int32_t n_eval = std::max(1, ctx->n_eval);
  2299. const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
  2300. fprintf(stderr, "\n");
  2301. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0);
  2302. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_sample_us, n_sample, 1e-3 * ctx->t_sample_us / n_sample);
  2303. 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);
  2304. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_eval_us, n_eval, 1e-3 * ctx->t_eval_us / n_eval);
  2305. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0);
  2306. }
  2307. void llama_reset_timings(struct llama_context * ctx) {
  2308. ctx->t_start_us = ggml_time_us();
  2309. ctx->t_sample_us = ctx->n_sample = 0;
  2310. ctx->t_eval_us = ctx->n_eval = 0;
  2311. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  2312. }
  2313. const char * llama_print_system_info(void) {
  2314. static std::string s;
  2315. s = "";
  2316. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  2317. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  2318. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  2319. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  2320. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  2321. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  2322. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  2323. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  2324. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  2325. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  2326. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  2327. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  2328. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  2329. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  2330. return s.c_str();
  2331. }
  2332. // For internal test use
  2333. std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  2334. return ctx->model.tensors_by_name;
  2335. }