llama.cpp 98 KB

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