llama.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "llama_util.h"
  6. #include "llama.h"
  7. #include "llama_internal.h"
  8. #include "ggml.h"
  9. #include <array>
  10. #include <cinttypes>
  11. #include <fstream>
  12. #include <random>
  13. #include <map>
  14. #include <unordered_map>
  15. #include <queue>
  16. #include <cassert>
  17. #include <cstring>
  18. #include <climits>
  19. #include <memory>
  20. #include <algorithm>
  21. #include <initializer_list>
  22. #define LLAMA_USE_SCRATCH
  23. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  24. // available llama models
  25. enum e_model {
  26. MODEL_UNKNOWN,
  27. MODEL_7B,
  28. MODEL_13B,
  29. MODEL_30B,
  30. MODEL_65B,
  31. };
  32. static const size_t MB = 1024*1024;
  33. // computed for n_ctx == 2048
  34. // TODO: dynamically determine these sizes
  35. // needs modifications in ggml
  36. static const std::map<e_model, size_t> MEM_REQ_SCRATCH0 = {
  37. { MODEL_7B, 512ull*MB },
  38. { MODEL_13B, 512ull*MB },
  39. { MODEL_30B, 512ull*MB },
  40. { MODEL_65B, 512ull*MB },
  41. };
  42. static const std::map<e_model, size_t> MEM_REQ_SCRATCH1 = {
  43. { MODEL_7B, 512ull*MB },
  44. { MODEL_13B, 512ull*MB },
  45. { MODEL_30B, 512ull*MB },
  46. { MODEL_65B, 512ull*MB },
  47. };
  48. // 2*n_embd*n_ctx*n_layer*sizeof(float16)
  49. static const std::map<e_model, size_t> MEM_REQ_KV_SELF = {
  50. { MODEL_7B, 1026ull*MB },
  51. { MODEL_13B, 1608ull*MB },
  52. { MODEL_30B, 3124ull*MB },
  53. { MODEL_65B, 5120ull*MB },
  54. };
  55. // this is mostly needed for temporary mul_mat buffers to dequantize the data
  56. // not actually needed if BLAS is disabled
  57. static const std::map<e_model, size_t> MEM_REQ_EVAL = {
  58. { MODEL_7B, 768ull*MB },
  59. { MODEL_13B, 1024ull*MB },
  60. { MODEL_30B, 1280ull*MB },
  61. { MODEL_65B, 1536ull*MB },
  62. };
  63. // default hparams (LLaMA 7B)
  64. struct llama_hparams {
  65. uint32_t n_vocab = 32000;
  66. uint32_t n_ctx = 512; // this is provided as user input?
  67. uint32_t n_embd = 4096;
  68. uint32_t n_mult = 256;
  69. uint32_t n_head = 32;
  70. uint32_t n_layer = 32;
  71. uint32_t n_rot = 64;
  72. uint32_t f16 = 1;
  73. bool operator!=(const llama_hparams & other) const {
  74. return memcmp(this, &other, sizeof(llama_hparams));
  75. }
  76. };
  77. struct llama_layer {
  78. // normalization
  79. struct ggml_tensor * attention_norm;
  80. // attention
  81. struct ggml_tensor * wq;
  82. struct ggml_tensor * wk;
  83. struct ggml_tensor * wv;
  84. struct ggml_tensor * wo;
  85. // normalization
  86. struct ggml_tensor * ffn_norm;
  87. // ff
  88. struct ggml_tensor * w1;
  89. struct ggml_tensor * w2;
  90. struct ggml_tensor * w3;
  91. };
  92. struct llama_kv_cache {
  93. struct ggml_tensor * k;
  94. struct ggml_tensor * v;
  95. struct ggml_context * ctx = NULL;
  96. llama_buffer buf;
  97. int n; // number of tokens currently in the cache
  98. ~llama_kv_cache() {
  99. if (ctx) {
  100. ggml_free(ctx);
  101. }
  102. }
  103. };
  104. struct llama_model {
  105. e_model type = MODEL_UNKNOWN;
  106. llama_hparams hparams;
  107. struct ggml_tensor * tok_embeddings;
  108. struct ggml_tensor * norm;
  109. struct ggml_tensor * output;
  110. std::vector<llama_layer> layers;
  111. // context
  112. struct ggml_context * ctx = NULL;
  113. // key + value cache for the self attention
  114. // TODO: move to llama_state
  115. struct llama_kv_cache kv_self;
  116. // the model memory buffer
  117. llama_buffer buf;
  118. // model memory mapped file
  119. std::unique_ptr<llama_mmap> mapping;
  120. // objects representing data potentially being locked in memory
  121. llama_mlock mlock_buf;
  122. llama_mlock mlock_mmap;
  123. // for quantize-stats only
  124. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  125. ~llama_model() {
  126. if (ctx) {
  127. ggml_free(ctx);
  128. }
  129. }
  130. };
  131. struct llama_vocab {
  132. using id = int32_t;
  133. using token = std::string;
  134. struct token_score {
  135. token tok;
  136. float score;
  137. };
  138. std::unordered_map<token, id> token_to_id;
  139. std::vector<token_score> id_to_token;
  140. };
  141. struct llama_context {
  142. std::mt19937 rng;
  143. int64_t t_load_us = 0;
  144. int64_t t_start_us = 0;
  145. bool has_evaluated_once = false;
  146. int64_t t_sample_us = 0;
  147. int64_t t_eval_us = 0;
  148. int64_t t_p_eval_us = 0;
  149. int32_t n_sample = 0; // number of tokens sampled
  150. int32_t n_eval = 0; // number of eval calls
  151. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  152. llama_model model;
  153. llama_vocab vocab;
  154. size_t mem_per_token = 0;
  155. // decode output (2-dimensional array: [n_tokens][n_vocab])
  156. std::vector<float> logits;
  157. bool logits_all = false;
  158. // input embedding (1-dimensional array: [n_embd])
  159. std::vector<float> embedding;
  160. // memory buffers used to evaluate the model
  161. // TODO: move in llama_state
  162. llama_buffer buf_compute;
  163. llama_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  164. int buf_last = 0;
  165. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  166. void use_buf(struct ggml_context * ctx, int i) {
  167. #if defined(LLAMA_USE_SCRATCH)
  168. size_t last_size = 0;
  169. if (i == -1) {
  170. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  171. } else {
  172. auto & buf = buf_scratch[i];
  173. last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
  174. }
  175. if (buf_last >= 0) {
  176. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  177. }
  178. buf_last = i;
  179. #else
  180. (void) i;
  181. (void) ctx;
  182. #endif
  183. }
  184. size_t get_buf_max_mem(int i) const {
  185. #if defined(LLAMA_USE_SCRATCH)
  186. return buf_max_size[i];
  187. #else
  188. (void) i;
  189. return 0;
  190. #endif
  191. }
  192. };
  193. template <typename T>
  194. static T checked_mul(T a, T b) {
  195. T ret = a * b;
  196. if (a != 0 && ret / a != b) {
  197. throw format("overflow multiplying %llu * %llu",
  198. (unsigned long long) a, (unsigned long long) b);
  199. }
  200. return ret;
  201. }
  202. static size_t checked_div(size_t a, size_t b) {
  203. if (b == 0 || a % b != 0) {
  204. throw format("error dividing %zu / %zu", a, b);
  205. }
  206. return a / b;
  207. }
  208. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  209. std::string ret = "[" + std::to_string(ne.at(0));
  210. for (size_t i = 1; i < ne.size(); i++) {
  211. ret += " x " + std::to_string(ne.at(i));
  212. }
  213. ret += "]";
  214. return ret;
  215. }
  216. static const char * llama_format_type(enum ggml_type type) {
  217. switch (type) {
  218. case GGML_TYPE_F32: return "f32";
  219. case GGML_TYPE_F16: return "f16";
  220. case GGML_TYPE_Q4_0: return "q4_0";
  221. case GGML_TYPE_Q4_1: return "q4_1";
  222. default: LLAMA_ASSERT(false);
  223. }
  224. }
  225. static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
  226. size_t size = ggml_type_size(type);
  227. for (uint32_t dim : ne) {
  228. size = checked_mul<size_t>(size, dim);
  229. }
  230. return size / ggml_blck_size(type);
  231. }
  232. struct llama_load_tensor_shard {
  233. std::vector<uint32_t> ne;
  234. size_t size;
  235. enum ggml_type type;
  236. size_t file_idx;
  237. size_t file_off;
  238. void calc_size() {
  239. size = llama_calc_tensor_size(ne, type);
  240. }
  241. };
  242. enum llama_split_type {
  243. SPLIT_NONE,
  244. SPLIT_BY_COLUMNS,
  245. SPLIT_BY_ROWS
  246. };
  247. struct llama_load_tensor {
  248. std::vector<llama_load_tensor_shard> shards;
  249. std::string name;
  250. enum ggml_type type = GGML_TYPE_F32;
  251. llama_split_type split_type = SPLIT_NONE;
  252. std::vector<uint32_t> ne;
  253. size_t size;
  254. struct ggml_tensor * ggml_tensor = NULL;
  255. uint8_t * data;
  256. llama_load_tensor(const std::string & name) : name(name) {}
  257. void calc_all() {
  258. calc_type();
  259. calc_split_type();
  260. calc_ne();
  261. calc_size();
  262. }
  263. void calc_type() {
  264. const auto & first_shard = shards.at(0);
  265. for (const auto & shard : shards) {
  266. if (shard.type != first_shard.type) {
  267. throw format("inconsistent tensor shard type in '%s'", name.c_str());
  268. }
  269. }
  270. type = first_shard.type;
  271. }
  272. void calc_split_type() {
  273. if (shards.at(0).ne.size() == 1 || // 1D tensors are just duplicated in every file
  274. shards.size() == 1) { // only one file?
  275. split_type = SPLIT_NONE;
  276. } else if (name.find("tok_embeddings.") == 0 ||
  277. name.find(".attention.wo.weight") != std::string::npos ||
  278. name.find(".feed_forward.w2.weight") != std::string::npos) {
  279. split_type = SPLIT_BY_COLUMNS;
  280. } else {
  281. split_type = SPLIT_BY_ROWS;
  282. }
  283. }
  284. void calc_ne() {
  285. const auto & first_shard = shards.at(0);
  286. for (const auto & shard : shards) {
  287. if (shard.ne != first_shard.ne) {
  288. throw format("inconsistent tensor shard shape in '%s': first was %s, other was %s",
  289. name.c_str(), llama_format_tensor_shape(first_shard.ne).c_str(), llama_format_tensor_shape(shard.ne).c_str());
  290. }
  291. }
  292. ne = first_shard.ne;
  293. LLAMA_ASSERT(shards.size() <= UINT32_MAX);
  294. uint32_t n_shards = (uint32_t) shards.size();
  295. switch (split_type) {
  296. case SPLIT_NONE:
  297. ne = first_shard.ne;
  298. break;
  299. case SPLIT_BY_COLUMNS:
  300. ne = {checked_mul<uint32_t>(first_shard.ne[0], n_shards),
  301. first_shard.ne[1]};
  302. break;
  303. case SPLIT_BY_ROWS:
  304. ne = {first_shard.ne[0],
  305. checked_mul<uint32_t>(first_shard.ne[1], n_shards)};
  306. break;
  307. }
  308. }
  309. void calc_size() {
  310. size = llama_calc_tensor_size(ne, type);
  311. }
  312. };
  313. struct llama_load_tensors_map {
  314. // tensors is kept in a separate vector to preserve file order
  315. std::vector<llama_load_tensor> tensors;
  316. std::unordered_map<std::string, size_t> name_to_idx;
  317. };
  318. enum llama_file_version {
  319. LLAMA_FILE_VERSION_GGML,
  320. LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
  321. LLAMA_FILE_VERSION_GGJT_V1, // added padding
  322. };
  323. struct llama_file_loader {
  324. llama_file file;
  325. llama_file_version file_version;
  326. llama_hparams hparams;
  327. llama_vocab vocab;
  328. llama_file_loader(const char * fname, size_t file_idx, llama_load_tensors_map & tensors_map)
  329. : file(fname, "rb") {
  330. fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
  331. read_magic();
  332. read_hparams();
  333. read_vocab();
  334. read_tensor_metadata(file_idx, tensors_map);
  335. }
  336. void read_magic() {
  337. uint32_t magic = file.read_u32();
  338. uint32_t version = 0;
  339. if (magic != 'ggml') {
  340. version = file.read_u32();
  341. }
  342. if (magic == 'ggml' && version == 0) {
  343. file_version = LLAMA_FILE_VERSION_GGML;
  344. } else if (magic == 'ggmf' && version == 1) {
  345. file_version = LLAMA_FILE_VERSION_GGMF_V1;
  346. } else if (magic == 'ggjt' && version == 1) {
  347. file_version = LLAMA_FILE_VERSION_GGJT_V1;
  348. } else {
  349. throw format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
  350. magic, version);
  351. }
  352. }
  353. void read_hparams() {
  354. hparams.n_vocab = file.read_u32();
  355. hparams.n_embd = file.read_u32();
  356. hparams.n_mult = file.read_u32();
  357. hparams.n_head = file.read_u32();
  358. hparams.n_layer = file.read_u32();
  359. hparams.n_rot = file.read_u32();
  360. hparams.f16 = file.read_u32();
  361. }
  362. void read_vocab() {
  363. vocab.id_to_token.resize(hparams.n_vocab);
  364. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  365. uint32_t len = file.read_u32();
  366. std::string word = file.read_string(len);
  367. float score = 0.0f;
  368. if (file_version >= LLAMA_FILE_VERSION_GGMF_V1) {
  369. file.read_raw(&score, sizeof(score));
  370. }
  371. vocab.token_to_id[word] = i;
  372. auto & tok_score = vocab.id_to_token[i];
  373. tok_score.tok = std::move(word);
  374. tok_score.score = score;
  375. }
  376. }
  377. void read_tensor_metadata(size_t file_idx, llama_load_tensors_map & tensors_map) {
  378. while (file.tell() < file.size) {
  379. llama_load_tensor_shard shard;
  380. uint32_t n_dims = file.read_u32();
  381. uint32_t name_len = file.read_u32();
  382. uint32_t ftype = file.read_u32();
  383. shard.ne.resize(n_dims);
  384. file.read_raw(shard.ne.data(), sizeof(shard.ne[0]) * n_dims);
  385. std::string name = file.read_string(name_len);
  386. if (n_dims < 1 || n_dims > 2) {
  387. throw format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims);
  388. }
  389. switch (ftype) {
  390. case 0: shard.type = GGML_TYPE_F32; break;
  391. case 1: shard.type = GGML_TYPE_F16; break;
  392. case 2: shard.type = GGML_TYPE_Q4_0; break;
  393. case 3: shard.type = GGML_TYPE_Q4_1; break;
  394. default: {
  395. throw format("unrecognized ftype %u\n", ftype);
  396. }
  397. }
  398. if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
  399. // skip to the next multiple of 32 bytes
  400. file.seek(-file.tell() & 31, SEEK_CUR);
  401. }
  402. shard.file_idx = file_idx;
  403. shard.file_off = file.tell();
  404. shard.calc_size();
  405. file.seek(shard.size, SEEK_CUR);
  406. auto it = tensors_map.name_to_idx.find(name);
  407. size_t idx;
  408. if (it != tensors_map.name_to_idx.end()) {
  409. idx = it->second;
  410. } else {
  411. tensors_map.tensors.emplace_back(name);
  412. idx = tensors_map.tensors.size() - 1;
  413. tensors_map.name_to_idx.emplace(name, idx);
  414. }
  415. tensors_map.tensors.at(idx).shards.push_back(shard);
  416. }
  417. }
  418. };
  419. struct llama_file_saver {
  420. llama_file file;
  421. llama_file_loader * any_file_loader;
  422. llama_file_saver(const char * fname, llama_file_loader * any_file_loader, uint32_t new_f16)
  423. : file(fname, "wb"), any_file_loader(any_file_loader) {
  424. fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
  425. write_magic();
  426. write_hparams(new_f16);
  427. write_vocab();
  428. }
  429. void write_magic() {
  430. file.write_u32('ggjt'); // magic
  431. file.write_u32(1); // version
  432. }
  433. void write_hparams(uint32_t new_f16) {
  434. const llama_hparams & hparams = any_file_loader->hparams;
  435. file.write_u32(hparams.n_vocab);
  436. file.write_u32(hparams.n_embd);
  437. file.write_u32(hparams.n_mult);
  438. file.write_u32(hparams.n_head);
  439. file.write_u32(hparams.n_layer);
  440. file.write_u32(hparams.n_rot);
  441. file.write_u32(new_f16);
  442. }
  443. void write_vocab() {
  444. if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
  445. fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
  446. }
  447. uint32_t n_vocab = any_file_loader->hparams.n_vocab;
  448. for (uint32_t i = 0; i < n_vocab; i++) {
  449. const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
  450. file.write_u32((uint32_t) token_score.tok.size());
  451. file.write_raw(token_score.tok.data(), token_score.tok.size());
  452. file.write_raw(&token_score.score, sizeof(token_score.score));
  453. }
  454. }
  455. void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
  456. uint32_t ftype;
  457. switch (new_type) {
  458. case GGML_TYPE_F32: ftype = 0; break;
  459. case GGML_TYPE_F16: ftype = 1; break;
  460. case GGML_TYPE_Q4_0: ftype = 2; break;
  461. case GGML_TYPE_Q4_1: ftype = 3; break;
  462. default: LLAMA_ASSERT(false);
  463. }
  464. file.write_u32((uint32_t) tensor.ne.size());
  465. file.write_u32((uint32_t) tensor.name.size());
  466. file.write_u32(ftype);
  467. file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
  468. file.write_raw(tensor.name.data(), tensor.name.size());
  469. file.seek(-file.tell() & 31, SEEK_CUR);
  470. LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
  471. file.write_raw(new_data, new_size);
  472. }
  473. };
  474. struct llama_model_loader {
  475. std::vector<std::unique_ptr<llama_file_loader>> file_loaders;
  476. llama_load_tensors_map tensors_map;
  477. bool use_mmap;
  478. size_t num_ggml_tensors_created = 0;
  479. struct ggml_context * ggml_ctx = NULL;
  480. std::unique_ptr<llama_mmap> mapping;
  481. llama_model_loader(const std::string & fname_base, bool use_mmap, bool vocab_only) {
  482. auto first_file = new llama_file_loader(fname_base.c_str(), 0, tensors_map);
  483. file_loaders.emplace_back(first_file);
  484. uint32_t n_parts = vocab_only ? 1 : guess_n_parts();
  485. for (uint32_t i = 1; i < n_parts; i++) {
  486. std::string fname = fname_base + "." + std::to_string(i);
  487. auto ith_file = new llama_file_loader(fname.c_str(), i, tensors_map);
  488. file_loaders.emplace_back(ith_file);
  489. if (ith_file->hparams != first_file->hparams) {
  490. throw format("llama.cpp: hparams inconsistent between files");
  491. }
  492. }
  493. if (!llama_mmap::SUPPORTED) {
  494. use_mmap = false;
  495. }
  496. if (use_mmap && alignment_prevents_mmap()) {
  497. fprintf(stderr, "llama.cpp: can't use mmap because tensors are not aligned; convert to new format to avoid this\n");
  498. use_mmap = false;
  499. }
  500. this->use_mmap = use_mmap;
  501. for (llama_load_tensor & lt : tensors_map.tensors) {
  502. lt.calc_all();
  503. }
  504. }
  505. bool alignment_prevents_mmap() {
  506. for (const llama_load_tensor & lt : tensors_map.tensors) {
  507. for (const llama_load_tensor_shard & shard : lt.shards) {
  508. if (shard.file_off & 3) {
  509. return true;
  510. }
  511. }
  512. }
  513. return false;
  514. }
  515. uint32_t guess_n_parts() const {
  516. auto it = tensors_map.name_to_idx.find("tok_embeddings.weight");
  517. if (it == tensors_map.name_to_idx.end()) {
  518. throw std::string("missing tok_embeddings.weight");
  519. }
  520. const llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  521. return file_loaders.at(0)->hparams.n_embd / lt.shards.at(0).ne.at(0);
  522. }
  523. void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
  524. *ctx_size_p = *mmapped_size_p = 0;
  525. for (const llama_load_tensor & lt : tensors_map.tensors) {
  526. *ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  527. *(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size;
  528. }
  529. }
  530. struct ggml_tensor * get_tensor(const std::string & name, std::vector<uint32_t> ne) {
  531. auto it = tensors_map.name_to_idx.find(name);
  532. if (it == tensors_map.name_to_idx.end()) {
  533. throw format("llama.cpp: tensor '%s' is missing from model", name.c_str());
  534. }
  535. llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  536. if (lt.ne != ne) {
  537. throw format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
  538. name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str());
  539. }
  540. return get_tensor_for(lt);
  541. }
  542. struct ggml_tensor * get_tensor_for(llama_load_tensor & lt) {
  543. struct ggml_tensor * tensor;
  544. if (lt.ne.size() == 2) {
  545. tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
  546. } else {
  547. LLAMA_ASSERT(lt.ne.size() == 1);
  548. tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
  549. }
  550. LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
  551. lt.ggml_tensor = tensor;
  552. num_ggml_tensors_created++;
  553. return tensor;
  554. }
  555. void done_getting_tensors() {
  556. if (num_ggml_tensors_created != tensors_map.tensors.size()) {
  557. throw std::string("llama.cpp: file contained more tensors than expected");
  558. }
  559. }
  560. void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  561. size_t data_size = 0;
  562. for (const llama_load_tensor & lt : tensors_map.tensors) {
  563. data_size += lt.size;
  564. }
  565. if (use_mmap) {
  566. mapping.reset(new llama_mmap(&file_loaders.at(0)->file));
  567. if (!lmlock) {
  568. // Don't call the callback since the actual loading will be lazy
  569. // and we can't measure it.
  570. progress_callback = NULL;
  571. }
  572. if (lmlock) {
  573. lmlock->init(mapping->addr);
  574. }
  575. }
  576. size_t done_size = 0;
  577. for (llama_load_tensor & lt : tensors_map.tensors) {
  578. if (progress_callback) {
  579. progress_callback((float) done_size / data_size, progress_callback_user_data);
  580. }
  581. LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
  582. lt.data = (uint8_t *) lt.ggml_tensor->data;
  583. load_data_for(lt);
  584. lt.ggml_tensor->data = lt.data;
  585. done_size += lt.size;
  586. if (use_mmap && lmlock) {
  587. lmlock->grow_to(done_size);
  588. }
  589. }
  590. if (progress_callback) {
  591. progress_callback(1.0f, progress_callback_user_data);
  592. }
  593. }
  594. void load_data_for(llama_load_tensor & lt) {
  595. if (use_mmap) {
  596. LLAMA_ASSERT(lt.shards.size() == 1);
  597. lt.data = (uint8_t *) mapping->addr + lt.shards.at(0).file_off;
  598. } else if (lt.split_type == SPLIT_NONE) {
  599. llama_file & file = file_loaders.at(lt.shards.at(0).file_idx)->file;
  600. file.seek(lt.shards.at(0).file_off, SEEK_SET);
  601. file.read_raw(lt.data, lt.size);
  602. } else if (lt.split_type == SPLIT_BY_ROWS) {
  603. size_t offset = 0;
  604. for (llama_load_tensor_shard & shard : lt.shards) {
  605. llama_file & file = file_loaders.at(shard.file_idx)->file;
  606. file.seek(shard.file_off, SEEK_SET);
  607. file.read_raw(lt.data + offset, shard.size);
  608. offset += shard.size;
  609. }
  610. LLAMA_ASSERT(offset == lt.size);
  611. } else if (lt.split_type == SPLIT_BY_COLUMNS) {
  612. // Let's load the data into temporary buffers to ensure the OS performs large loads.
  613. std::vector<llama_buffer> tmp_bufs;
  614. tmp_bufs.resize(lt.shards.size());
  615. for (size_t i = 0; i < lt.shards.size(); i++) {
  616. llama_load_tensor_shard & shard = lt.shards.at(i);
  617. llama_file & file = file_loaders.at(shard.file_idx)->file;
  618. file.seek(shard.file_off, SEEK_SET);
  619. tmp_bufs.at(i).resize(shard.size);
  620. file.read_raw(tmp_bufs.at(i).addr, shard.size);
  621. }
  622. // Then reshape.
  623. size_t num_rows = lt.ne.at(1);
  624. size_t per_shard_row_size = lt.shards.at(0).size / num_rows;
  625. size_t out_offset = 0;
  626. for (size_t row = 0; row < num_rows; row++) {
  627. for (llama_buffer & tmp_buf : tmp_bufs) {
  628. memcpy(lt.data + out_offset,
  629. tmp_buf.addr + row * per_shard_row_size,
  630. per_shard_row_size);
  631. out_offset += per_shard_row_size;
  632. }
  633. }
  634. LLAMA_ASSERT(out_offset == lt.size);
  635. }
  636. if (0) {
  637. print_checksum(lt);
  638. }
  639. }
  640. static void print_checksum(llama_load_tensor & lt) {
  641. uint32_t sum = 0;
  642. for (size_t i = 0; i < lt.size; i++) {
  643. uint8_t byte = lt.data[i];
  644. sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
  645. }
  646. fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
  647. llama_format_tensor_shape(lt.ne).c_str(), lt.size);
  648. }
  649. };
  650. //
  651. // kv cache
  652. //
  653. static bool kv_cache_init(
  654. const struct llama_hparams & hparams,
  655. struct llama_kv_cache & cache,
  656. ggml_type wtype,
  657. int n_ctx) {
  658. const int n_embd = hparams.n_embd;
  659. const int n_layer = hparams.n_layer;
  660. const int64_t n_mem = (int64_t)n_layer*n_ctx;
  661. const int64_t n_elements = n_embd*n_mem;
  662. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  663. struct ggml_init_params params;
  664. params.mem_size = cache.buf.size;
  665. params.mem_buffer = cache.buf.addr;
  666. params.no_alloc = false;
  667. cache.ctx = ggml_init(params);
  668. if (!cache.ctx) {
  669. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  670. return false;
  671. }
  672. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  673. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  674. return true;
  675. }
  676. struct llama_context_params llama_context_default_params() {
  677. struct llama_context_params result = {
  678. /*.n_ctx =*/ 512,
  679. /*.n_parts =*/ -1,
  680. /*.seed =*/ 0,
  681. /*.f16_kv =*/ false,
  682. /*.logits_all =*/ false,
  683. /*.vocab_only =*/ false,
  684. /*.use_mmap =*/ true,
  685. /*.use_mlock =*/ false,
  686. /*.embedding =*/ false,
  687. /*.progress_callback =*/ nullptr,
  688. /*.progress_callback_user_data =*/ nullptr,
  689. };
  690. return result;
  691. }
  692. bool llama_mmap_supported() {
  693. return llama_mmap::SUPPORTED;
  694. }
  695. bool llama_mlock_supported() {
  696. return llama_mlock::SUPPORTED;
  697. }
  698. //
  699. // model loading
  700. //
  701. static const char *llama_file_version_name(llama_file_version version) {
  702. switch (version) {
  703. case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
  704. case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
  705. case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (latest)";
  706. default: LLAMA_ASSERT(false);
  707. }
  708. }
  709. static const char *llama_model_type_name(e_model type) {
  710. switch (type) {
  711. case MODEL_7B: return "7B";
  712. case MODEL_13B: return "13B";
  713. case MODEL_30B: return "30B";
  714. case MODEL_65B: return "65B";
  715. default: LLAMA_ASSERT(false);
  716. }
  717. }
  718. static void llama_model_load_internal(
  719. const std::string & fname,
  720. llama_context & lctx,
  721. int n_ctx,
  722. ggml_type memory_type,
  723. bool use_mmap,
  724. bool use_mlock,
  725. bool vocab_only,
  726. llama_progress_callback progress_callback,
  727. void * progress_callback_user_data) {
  728. lctx.t_start_us = ggml_time_us();
  729. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap, vocab_only));
  730. lctx.vocab = std::move(ml->file_loaders.at(0)->vocab);
  731. auto & model = lctx.model;
  732. model.hparams = ml->file_loaders.at(0)->hparams;
  733. llama_file_version file_version = ml->file_loaders.at(0)->file_version;
  734. auto & hparams = model.hparams;
  735. uint32_t n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  736. {
  737. switch (hparams.n_layer) {
  738. case 32: model.type = e_model::MODEL_7B; break;
  739. case 40: model.type = e_model::MODEL_13B; break;
  740. case 60: model.type = e_model::MODEL_30B; break;
  741. case 80: model.type = e_model::MODEL_65B; break;
  742. }
  743. hparams.n_ctx = n_ctx;
  744. }
  745. {
  746. fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
  747. fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  748. fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  749. fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
  750. fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
  751. fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
  752. fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
  753. fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot);
  754. fprintf(stderr, "%s: f16 = %u\n", __func__, hparams.f16);
  755. fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
  756. fprintf(stderr, "%s: n_parts = %zu\n", __func__, ml->file_loaders.size());
  757. fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
  758. }
  759. if (vocab_only) {
  760. return;
  761. }
  762. auto & ctx = model.ctx;
  763. size_t ctx_size, mmapped_size;
  764. ml->calc_sizes(&ctx_size, &mmapped_size);
  765. fprintf(stderr, "%s: ggml ctx size = %6.2f KB\n", __func__, ctx_size/1024.0);
  766. // print memory requirements
  767. {
  768. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  769. // this is the total memory required to run the inference
  770. const size_t mem_required =
  771. ctx_size +
  772. mmapped_size +
  773. MEM_REQ_SCRATCH0.at(model.type) +
  774. MEM_REQ_SCRATCH1.at(model.type) +
  775. MEM_REQ_EVAL.at (model.type);
  776. // this is the memory required by one llama_state
  777. const size_t mem_required_state =
  778. scale*MEM_REQ_KV_SELF.at(model.type);
  779. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  780. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  781. }
  782. // create the ggml context
  783. {
  784. lctx.model.buf.resize(ctx_size);
  785. if (use_mlock) {
  786. lctx.model.mlock_buf.init(lctx.model.buf.addr);
  787. lctx.model.mlock_buf.grow_to(lctx.model.buf.size);
  788. }
  789. struct ggml_init_params params = {
  790. /*.mem_size =*/ lctx.model.buf.size,
  791. /*.mem_buffer =*/ lctx.model.buf.addr,
  792. /*.no_alloc =*/ ml->use_mmap,
  793. };
  794. model.ctx = ggml_init(params);
  795. if (!model.ctx) {
  796. throw format("ggml_init() failed");
  797. }
  798. }
  799. // prepare memory for the weights
  800. {
  801. const auto & hparams = model.hparams;
  802. const uint32_t n_embd = hparams.n_embd;
  803. const uint32_t n_layer = hparams.n_layer;
  804. const uint32_t n_vocab = hparams.n_vocab;
  805. ml->ggml_ctx = ctx;
  806. model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab});
  807. model.norm = ml->get_tensor("norm.weight", {n_embd});
  808. model.output = ml->get_tensor("output.weight", {n_embd, n_vocab});
  809. model.layers.resize(n_layer);
  810. for (uint32_t i = 0; i < n_layer; ++i) {
  811. auto & layer = model.layers[i];
  812. std::string layers_i = "layers." + std::to_string(i);
  813. layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd});
  814. layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd});
  815. layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd});
  816. layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd});
  817. layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd});
  818. layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd});
  819. layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
  820. layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
  821. layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
  822. }
  823. }
  824. ml->done_getting_tensors();
  825. // populate `tensors_by_name`
  826. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  827. model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
  828. }
  829. ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &lctx.model.mlock_mmap : NULL);
  830. model.mapping = std::move(ml->mapping);
  831. // loading time will be recalculate after the first eval, so
  832. // we take page faults deferred by mmap() into consideration
  833. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  834. }
  835. static bool llama_model_load(
  836. const std::string & fname,
  837. llama_context & lctx,
  838. int n_ctx,
  839. ggml_type memory_type,
  840. bool use_mmap,
  841. bool use_mlock,
  842. bool vocab_only,
  843. llama_progress_callback progress_callback,
  844. void *progress_callback_user_data) {
  845. try {
  846. llama_model_load_internal(fname, lctx, n_ctx, memory_type, use_mmap, use_mlock,
  847. vocab_only, progress_callback, progress_callback_user_data);
  848. return true;
  849. } catch (const std::string & err) {
  850. fprintf(stderr, "error loading model: %s\n", err.c_str());
  851. return false;
  852. }
  853. }
  854. // evaluate the transformer
  855. //
  856. // - lctx: llama context
  857. // - tokens: new batch of tokens to process
  858. // - n_past: the context size so far
  859. // - n_threads: number of threads to use
  860. //
  861. static bool llama_eval_internal(
  862. llama_context & lctx,
  863. const llama_token * tokens,
  864. const int n_tokens,
  865. const int n_past,
  866. const int n_threads) {
  867. const int64_t t_start_us = ggml_time_us();
  868. const int N = n_tokens;
  869. const auto & model = lctx.model;
  870. const auto & hparams = model.hparams;
  871. auto & kv_self = model.kv_self;
  872. LLAMA_ASSERT(!!kv_self.ctx);
  873. const int n_embd = hparams.n_embd;
  874. const int n_layer = hparams.n_layer;
  875. const int n_ctx = hparams.n_ctx;
  876. const int n_head = hparams.n_head;
  877. const int n_vocab = hparams.n_vocab;
  878. const int n_rot = hparams.n_embd/hparams.n_head;
  879. auto & mem_per_token = lctx.mem_per_token;
  880. auto & buf_compute = lctx.buf_compute;
  881. struct ggml_init_params params = {
  882. /*.mem_size =*/ buf_compute.size,
  883. /*.mem_buffer =*/ buf_compute.addr,
  884. /*.no_alloc =*/ false,
  885. };
  886. struct ggml_context * ctx0 = ggml_init(params);
  887. // for big prompts, if BLAS is enabled, it is better to use only one thread
  888. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  889. ggml_cgraph gf = {};
  890. gf.n_threads = N >= 32 && ggml_cpu_has_blas() ? 1 : n_threads;
  891. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  892. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  893. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  894. for (int il = 0; il < n_layer; ++il) {
  895. struct ggml_tensor * inpSA = inpL;
  896. struct ggml_tensor * cur;
  897. lctx.use_buf(ctx0, 0);
  898. // norm
  899. {
  900. cur = ggml_rms_norm(ctx0, inpL);
  901. // cur = attention_norm*cur
  902. cur = ggml_mul(ctx0,
  903. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  904. cur);
  905. }
  906. // self-attention
  907. {
  908. // compute Q and K and RoPE them
  909. struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  910. struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
  911. // store key and value to memory
  912. {
  913. // compute the transposed [N, n_embd] V matrix
  914. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), n_embd, N));
  915. 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));
  916. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
  917. ( n_ctx)*ggml_element_size(kv_self.v),
  918. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
  919. // important: storing RoPE-ed version of K in the KV cache!
  920. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  921. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  922. }
  923. struct ggml_tensor * Q =
  924. ggml_permute(ctx0,
  925. Qcur,
  926. 0, 2, 1, 3);
  927. struct ggml_tensor * K =
  928. ggml_permute(ctx0,
  929. ggml_reshape_3d(ctx0,
  930. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  931. n_embd/n_head, n_head, n_past + N),
  932. 0, 2, 1, 3);
  933. // K * Q
  934. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  935. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  936. struct ggml_tensor * KQ_scaled =
  937. ggml_scale(ctx0,
  938. KQ,
  939. ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
  940. // KQ_masked = mask_past(KQ_scaled)
  941. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  942. // KQ = soft_max(KQ_masked)
  943. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  944. // split cached V into n_head heads
  945. struct ggml_tensor * V =
  946. ggml_view_3d(ctx0, kv_self.v,
  947. n_past + N, n_embd/n_head, n_head,
  948. n_ctx*ggml_element_size(kv_self.v),
  949. n_ctx*ggml_element_size(kv_self.v)*n_embd/n_head,
  950. il*n_ctx*ggml_element_size(kv_self.v)*n_embd);
  951. #if 1
  952. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  953. #else
  954. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  955. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  956. // is there a better way?
  957. 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));
  958. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  959. #endif
  960. // KQV_merged = KQV.permute(0, 2, 1, 3)
  961. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  962. // cur = KQV_merged.contiguous().view(n_embd, N)
  963. cur = ggml_cpy(ctx0,
  964. KQV_merged,
  965. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  966. // projection (no bias)
  967. cur = ggml_mul_mat(ctx0,
  968. model.layers[il].wo,
  969. cur);
  970. }
  971. lctx.use_buf(ctx0, 1);
  972. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  973. // feed-forward network
  974. {
  975. // norm
  976. {
  977. cur = ggml_rms_norm(ctx0, inpFF);
  978. // cur = ffn_norm*cur
  979. cur = ggml_mul(ctx0,
  980. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  981. cur);
  982. }
  983. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  984. model.layers[il].w3,
  985. cur);
  986. cur = ggml_mul_mat(ctx0,
  987. model.layers[il].w1,
  988. cur);
  989. // SILU activation
  990. cur = ggml_silu(ctx0, cur);
  991. cur = ggml_mul(ctx0, cur, tmp);
  992. cur = ggml_mul_mat(ctx0,
  993. model.layers[il].w2,
  994. cur);
  995. }
  996. cur = ggml_add(ctx0, cur, inpFF);
  997. // input for next layer
  998. inpL = cur;
  999. }
  1000. lctx.use_buf(ctx0, 0);
  1001. // used at the end to optionally extract the embeddings
  1002. struct ggml_tensor * embeddings = NULL;
  1003. // norm
  1004. {
  1005. inpL = ggml_rms_norm(ctx0, inpL);
  1006. // inpL = norm*inpL
  1007. inpL = ggml_mul(ctx0,
  1008. ggml_repeat(ctx0, model.norm, inpL),
  1009. inpL);
  1010. embeddings = inpL;
  1011. }
  1012. // lm_head
  1013. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  1014. lctx.use_buf(ctx0, -1);
  1015. // logits -> probs
  1016. //inpL = ggml_soft_max(ctx0, inpL);
  1017. // run the computation
  1018. ggml_build_forward_expand(&gf, inpL);
  1019. ggml_graph_compute (ctx0, &gf);
  1020. // print timing information per ggml operation (for debugging purposes)
  1021. // requires GGML_PERF to be defined
  1022. //ggml_graph_print(&gf);
  1023. // plot the computation graph in dot format (for debugging purposes)
  1024. //if (n_past%100 == 0) {
  1025. // ggml_graph_dump_dot(&gf, NULL, "llama.dot");
  1026. //}
  1027. //embd_w.resize(n_vocab*N);
  1028. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1029. // extract logits
  1030. {
  1031. auto & logits_out = lctx.logits;
  1032. if (lctx.logits_all) {
  1033. logits_out.resize(n_vocab * N);
  1034. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  1035. } else {
  1036. // return result for just the last token
  1037. logits_out.resize(n_vocab);
  1038. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1039. }
  1040. }
  1041. // extract embeddings
  1042. if (lctx.embedding.size()) {
  1043. auto & embedding_out = lctx.embedding;
  1044. embedding_out.resize(n_embd);
  1045. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1046. }
  1047. if (mem_per_token == 0) {
  1048. mem_per_token = ggml_used_mem(ctx0)/N;
  1049. }
  1050. #if 0
  1051. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  1052. ggml_used_mem(ctx0)/1024.0/1024.0,
  1053. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  1054. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  1055. #endif
  1056. ggml_free(ctx0);
  1057. // measure the performance only for the single-token evals
  1058. if (N == 1) {
  1059. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1060. lctx.n_eval++;
  1061. }
  1062. else if (N > 1) {
  1063. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1064. lctx.n_p_eval += N;
  1065. }
  1066. return true;
  1067. }
  1068. //
  1069. // tokenizer
  1070. //
  1071. static size_t utf8_len(char src) {
  1072. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1073. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1074. return lookup[highbits];
  1075. }
  1076. struct llama_sp_symbol {
  1077. using index = int;
  1078. index prev;
  1079. index next;
  1080. const char * text;
  1081. size_t n;
  1082. };
  1083. struct llama_sp_bigram {
  1084. struct comparator {
  1085. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1086. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1087. }
  1088. };
  1089. using queue_storage = std::vector<llama_sp_bigram>;
  1090. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1091. llama_sp_symbol::index left;
  1092. llama_sp_symbol::index right;
  1093. float score;
  1094. size_t size;
  1095. };
  1096. // original implementation:
  1097. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1098. struct llama_tokenizer {
  1099. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1100. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1101. // split string into utf8 chars
  1102. int index = 0;
  1103. size_t offs = 0;
  1104. while (offs < text.size()) {
  1105. llama_sp_symbol sym;
  1106. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  1107. sym.text = text.c_str() + offs;
  1108. sym.n = char_len;
  1109. offs += char_len;
  1110. sym.prev = index - 1;
  1111. sym.next = offs == text.size() ? -1 : index + 1;
  1112. index++;
  1113. symbols_.emplace_back(std::move(sym));
  1114. }
  1115. // seed the work queue with all possible 2-character tokens.
  1116. for (size_t i = 1; i < symbols_.size(); ++i) {
  1117. try_add_bigram(i - 1, i);
  1118. }
  1119. // keep substituting the highest frequency pairs for as long as we can.
  1120. while (!work_queue_.empty()) {
  1121. auto bigram = work_queue_.top();
  1122. work_queue_.pop();
  1123. auto & left_sym = symbols_[bigram.left];
  1124. auto & right_sym = symbols_[bigram.right];
  1125. // if one of the symbols already got merged, skip it.
  1126. if (left_sym.n == 0 || right_sym.n == 0 ||
  1127. left_sym.n + right_sym.n != bigram.size) {
  1128. continue;
  1129. }
  1130. // merge the right sym into the left one
  1131. left_sym.n += right_sym.n;
  1132. right_sym.n = 0;
  1133. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1134. // remove the right sym from the chain
  1135. left_sym.next = right_sym.next;
  1136. if (right_sym.next >= 0) {
  1137. symbols_[right_sym.next].prev = bigram.left;
  1138. }
  1139. // find more substitutions
  1140. try_add_bigram(left_sym.prev, bigram.left);
  1141. try_add_bigram(bigram.left, left_sym.next);
  1142. }
  1143. for (int i = 0; i != -1; i = symbols_[i].next) {
  1144. auto & symbol = symbols_[i];
  1145. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  1146. if (token == vocab_.token_to_id.end()) {
  1147. // output any symbols that did not form tokens as bytes.
  1148. for (int j = 0; j < (int) symbol.n; ++j) {
  1149. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  1150. output.push_back(token_id);
  1151. }
  1152. } else {
  1153. output.push_back((*token).second);
  1154. }
  1155. }
  1156. }
  1157. private:
  1158. void try_add_bigram(int left, int right) {
  1159. if (left == -1 || right == -1) {
  1160. return;
  1161. }
  1162. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1163. auto token = vocab_.token_to_id.find(text);
  1164. if (token == vocab_.token_to_id.end()) {
  1165. return;
  1166. }
  1167. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1168. return;
  1169. }
  1170. const auto &tok_score = vocab_.id_to_token[(*token).second];
  1171. llama_sp_bigram bigram;
  1172. bigram.left = left;
  1173. bigram.right = right;
  1174. bigram.score = tok_score.score;
  1175. bigram.size = text.size();
  1176. work_queue_.push(bigram);
  1177. }
  1178. const llama_vocab & vocab_;
  1179. std::vector<llama_sp_symbol> symbols_;
  1180. llama_sp_bigram::queue work_queue_;
  1181. };
  1182. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  1183. llama_tokenizer tokenizer(vocab);
  1184. std::vector<llama_vocab::id> output;
  1185. if (text.size() == 0) {
  1186. return output;
  1187. }
  1188. if (bos) {
  1189. output.push_back(1);
  1190. }
  1191. tokenizer.tokenize(text, output);
  1192. return output;
  1193. }
  1194. //
  1195. // sampling
  1196. //
  1197. static void sample_top_k(std::vector<std::pair<float, llama_vocab::id>> & logits_id, int top_k) {
  1198. // find the top k tokens
  1199. std::partial_sort(
  1200. logits_id.begin(),
  1201. logits_id.begin() + top_k, logits_id.end(),
  1202. [](const std::pair<float, llama_vocab::id> & a, const std::pair<float, llama_vocab::id> & b) {
  1203. return a.first > b.first;
  1204. });
  1205. logits_id.resize(top_k);
  1206. }
  1207. static llama_vocab::id llama_sample_top_p_top_k(
  1208. llama_context & lctx,
  1209. const std::vector<llama_vocab::id> & last_n_tokens,
  1210. int top_k,
  1211. float top_p,
  1212. float temp,
  1213. float repeat_penalty) {
  1214. auto & rng = lctx.rng;
  1215. const int n_logits = lctx.model.hparams.n_vocab;
  1216. const auto & logits = lctx.logits;
  1217. const auto * plogits = logits.data() + logits.size() - n_logits;
  1218. if (temp <= 0) {
  1219. // select the token with the highest logit directly
  1220. float max_logit = plogits[0];
  1221. llama_vocab::id max_id = 0;
  1222. for (int i = 1; i < n_logits; ++i) {
  1223. if (plogits[i] > max_logit) {
  1224. max_logit = plogits[i];
  1225. max_id = i;
  1226. }
  1227. }
  1228. return max_id;
  1229. }
  1230. std::vector<std::pair<float, llama_vocab::id>> logits_id;
  1231. logits_id.reserve(n_logits);
  1232. {
  1233. const float scale = 1.0f/temp;
  1234. for (int i = 0; i < n_logits; ++i) {
  1235. // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
  1236. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  1237. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  1238. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  1239. if (plogits[i] < 0.0f) {
  1240. logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
  1241. } else {
  1242. logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
  1243. }
  1244. } else {
  1245. logits_id.push_back(std::make_pair(plogits[i]*scale, i));
  1246. }
  1247. }
  1248. }
  1249. sample_top_k(logits_id, top_k > 0 ? std::min(top_k, n_logits) : n_logits);
  1250. // compute probs for the top k tokens
  1251. std::vector<float> probs;
  1252. probs.reserve(logits_id.size());
  1253. float maxl = logits_id[0].first;
  1254. double sum = 0.0;
  1255. for (const auto & kv : logits_id) {
  1256. const float p = expf(kv.first - maxl);
  1257. probs.push_back(p);
  1258. sum += p;
  1259. }
  1260. // normalize the probs
  1261. for (auto & p : probs) {
  1262. p /= sum;
  1263. }
  1264. if (top_p < 1.0) {
  1265. double cumsum = 0.0;
  1266. for (int i = 0; i < (int) probs.size(); i++) {
  1267. cumsum += probs[i];
  1268. if (cumsum >= top_p) {
  1269. probs.resize(i + 1);
  1270. logits_id.resize(i + 1);
  1271. break;
  1272. }
  1273. }
  1274. }
  1275. //printf("\n");
  1276. //for (int i = 0; i < (int) 10; i++) {
  1277. // printf("%d: '%s' %f\n", i, lctx.vocab.id_to_token.at(logits_id[i].second).tok.c_str(), probs[i]);
  1278. //}
  1279. //printf("\n\n");
  1280. //exit(0);
  1281. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1282. int idx = dist(rng);
  1283. return logits_id[idx].second;
  1284. }
  1285. //
  1286. // quantization
  1287. //
  1288. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, int itype) {
  1289. ggml_type quantized_type;
  1290. switch (itype) {
  1291. case 2: quantized_type = GGML_TYPE_Q4_0; break;
  1292. case 3: quantized_type = GGML_TYPE_Q4_1; break;
  1293. default: throw format("invalid quantization type %d\n", itype);
  1294. };
  1295. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp.c_str(), /*use_mmap*/ false,
  1296. /*vocab_only*/ false));
  1297. llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loaders.at(0).get(), (uint32_t) itype);
  1298. size_t total_size_org = 0;
  1299. size_t total_size_new = 0;
  1300. std::vector<int64_t> hist_all(1 << 4, 0);
  1301. size_t idx = 0;
  1302. for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
  1303. llama_buffer read_data;
  1304. read_data.resize(tensor.size);
  1305. tensor.data = read_data.addr;
  1306. model_loader->load_data_for(tensor);
  1307. printf("[%zu/%zu] %36s - %s, type = %6s, ",
  1308. ++idx, model_loader->tensors_map.tensors.size(),
  1309. tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
  1310. llama_format_type(tensor.type));
  1311. // This used to be a regex, but <regex> has an extreme cost to compile times.
  1312. bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
  1313. // quantize only 2D tensors
  1314. quantize &= (tensor.ne.size() == 2);
  1315. enum ggml_type new_type;
  1316. void * new_data;
  1317. size_t new_size;
  1318. llama_buffer work;
  1319. if (!quantize) {
  1320. new_type = tensor.type;
  1321. new_data = tensor.data;
  1322. new_size = tensor.size;
  1323. printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
  1324. } else {
  1325. new_type = quantized_type;
  1326. float * f32_data;
  1327. size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
  1328. llama_buffer f32_conv_buf;
  1329. if (tensor.type == GGML_TYPE_F32) {
  1330. f32_data = (float *) tensor.data;
  1331. } else if (tensor.type == GGML_TYPE_F16) {
  1332. f32_conv_buf.resize(nelements * sizeof(float));
  1333. f32_data = (float *) f32_conv_buf.addr;
  1334. auto f16_data = (const ggml_fp16_t *) tensor.data;
  1335. for (size_t i = 0; i < nelements; i++) {
  1336. f32_data[i] = ggml_fp16_to_fp32(f16_data[i]);
  1337. }
  1338. } else {
  1339. throw format("type %s unsupported for integer quantization", llama_format_type(tensor.type));
  1340. }
  1341. printf("quantizing .. ");
  1342. fflush(stdout);
  1343. work.resize(nelements * 4); // upper bound on size
  1344. new_data = work.addr;
  1345. std::vector<int64_t> hist_cur(1 << 4, 0);
  1346. switch (new_type) {
  1347. case GGML_TYPE_Q4_0:
  1348. {
  1349. new_size = ggml_quantize_q4_0(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
  1350. } break;
  1351. case GGML_TYPE_Q4_1:
  1352. {
  1353. new_size = ggml_quantize_q4_1(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
  1354. } break;
  1355. default:
  1356. LLAMA_ASSERT(false);
  1357. }
  1358. printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
  1359. for (size_t i = 0; i < hist_cur.size(); i++) {
  1360. hist_all[i] += hist_cur[i];
  1361. }
  1362. for (size_t i = 0; i < hist_cur.size(); i++) {
  1363. printf("%5.3f ", hist_cur[i] / float(nelements));
  1364. }
  1365. printf("\n");
  1366. }
  1367. total_size_org += tensor.size;
  1368. total_size_new += new_size;
  1369. file_saver.write_tensor(tensor, new_type, new_data, new_size);
  1370. }
  1371. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1372. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1373. {
  1374. int64_t sum_all = 0;
  1375. for (size_t i = 0; i < hist_all.size(); i++) {
  1376. sum_all += hist_all[i];
  1377. }
  1378. printf("%s: hist: ", __func__);
  1379. for (size_t i = 0; i < hist_all.size(); i++) {
  1380. printf("%5.3f ", hist_all[i] / float(sum_all));
  1381. }
  1382. printf("\n");
  1383. }
  1384. }
  1385. //
  1386. // interface implementation
  1387. //
  1388. struct llama_context * llama_init_from_file(
  1389. const char * path_model,
  1390. struct llama_context_params params) {
  1391. ggml_time_init();
  1392. llama_context * ctx = new llama_context;
  1393. if (params.seed <= 0) {
  1394. params.seed = time(NULL);
  1395. }
  1396. unsigned cur_percentage = 0;
  1397. if (params.progress_callback == NULL) {
  1398. params.progress_callback_user_data = &cur_percentage;
  1399. params.progress_callback = [](float progress, void * ctx) {
  1400. unsigned * cur_percentage_p = (unsigned *) ctx;
  1401. unsigned percentage = (unsigned) (100 * progress);
  1402. while (percentage > *cur_percentage_p) {
  1403. ++*cur_percentage_p;
  1404. fprintf(stderr, ".");
  1405. fflush(stderr);
  1406. if (percentage >= 100) {
  1407. fprintf(stderr, "\n");
  1408. }
  1409. }
  1410. };
  1411. }
  1412. ctx->rng = std::mt19937(params.seed);
  1413. ctx->logits_all = params.logits_all;
  1414. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1415. if (!llama_model_load(path_model, *ctx, params.n_ctx, memory_type,
  1416. params.use_mmap, params.use_mlock, params.vocab_only,
  1417. params.progress_callback, params.progress_callback_user_data)) {
  1418. fprintf(stderr, "%s: failed to load model\n", __func__);
  1419. llama_free(ctx);
  1420. return nullptr;
  1421. }
  1422. // reserve memory for context buffers
  1423. if (!params.vocab_only) {
  1424. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1425. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1426. llama_free(ctx);
  1427. return nullptr;
  1428. }
  1429. {
  1430. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1431. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1432. }
  1433. const auto & hparams = ctx->model.hparams;
  1434. // resized during inference
  1435. if (params.logits_all) {
  1436. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1437. } else {
  1438. ctx->logits.reserve(hparams.n_ctx);
  1439. }
  1440. if (params.embedding){
  1441. ctx->embedding.resize(hparams.n_embd);
  1442. }
  1443. ctx->buf_compute.resize(MEM_REQ_EVAL.at(ctx->model.type));
  1444. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0.at(ctx->model.type));
  1445. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1.at(ctx->model.type));
  1446. }
  1447. return ctx;
  1448. }
  1449. void llama_free(struct llama_context * ctx) {
  1450. delete ctx;
  1451. }
  1452. int llama_model_quantize(
  1453. const char * fname_inp,
  1454. const char * fname_out,
  1455. int itype) {
  1456. try {
  1457. llama_model_quantize_internal(fname_inp, fname_out, itype);
  1458. return 0;
  1459. } catch (const std::string & err) {
  1460. fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.c_str());
  1461. return 1;
  1462. }
  1463. }
  1464. // Returns the KV cache that will contain the context for the
  1465. // ongoing prediction with the model.
  1466. const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
  1467. return ctx->model.kv_self.buf.addr;
  1468. }
  1469. // Returns the size of the KV cache
  1470. size_t llama_get_kv_cache_size(struct llama_context * ctx) {
  1471. return ctx->model.kv_self.buf.size;
  1472. }
  1473. int llama_get_kv_cache_token_count(struct llama_context * ctx) {
  1474. return ctx->model.kv_self.n;
  1475. }
  1476. // Sets the KV cache containing the current context for the model
  1477. void llama_set_kv_cache(
  1478. struct llama_context * ctx,
  1479. const uint8_t * kv_cache,
  1480. size_t n_size,
  1481. int n_token_count) {
  1482. // Make sure we have the same kv cache setup
  1483. LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
  1484. memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
  1485. ctx->model.kv_self.n = n_token_count;
  1486. }
  1487. int llama_eval(
  1488. struct llama_context * ctx,
  1489. const llama_token * tokens,
  1490. int n_tokens,
  1491. int n_past,
  1492. int n_threads) {
  1493. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  1494. fprintf(stderr, "%s: failed to eval\n", __func__);
  1495. return 1;
  1496. }
  1497. // get a more accurate load time, upon first eval
  1498. if (!ctx->has_evaluated_once) {
  1499. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  1500. ctx->has_evaluated_once = true;
  1501. }
  1502. return 0;
  1503. }
  1504. int llama_tokenize(
  1505. struct llama_context * ctx,
  1506. const char * text,
  1507. llama_token * tokens,
  1508. int n_max_tokens,
  1509. bool add_bos) {
  1510. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  1511. if (n_max_tokens < (int) res.size()) {
  1512. fprintf(stderr, "%s: too many tokens\n", __func__);
  1513. return -((int) res.size());
  1514. }
  1515. for (size_t i = 0; i < res.size(); i++) {
  1516. tokens[i] = res[i];
  1517. }
  1518. return res.size();
  1519. }
  1520. int llama_n_vocab(struct llama_context * ctx) {
  1521. return ctx->vocab.id_to_token.size();
  1522. }
  1523. int llama_n_ctx(struct llama_context * ctx) {
  1524. return ctx->model.hparams.n_ctx;
  1525. }
  1526. int llama_n_embd(struct llama_context * ctx) {
  1527. return ctx->model.hparams.n_embd;
  1528. }
  1529. float * llama_get_logits(struct llama_context * ctx) {
  1530. return ctx->logits.data();
  1531. }
  1532. float * llama_get_embeddings(struct llama_context * ctx) {
  1533. return ctx->embedding.data();
  1534. }
  1535. const char * llama_token_to_str(struct llama_context * ctx, llama_token token) {
  1536. if (token >= llama_n_vocab(ctx)) {
  1537. return nullptr;
  1538. }
  1539. return ctx->vocab.id_to_token[token].tok.c_str();
  1540. }
  1541. llama_token llama_token_bos() {
  1542. return 1;
  1543. }
  1544. llama_token llama_token_eos() {
  1545. return 2;
  1546. }
  1547. llama_token llama_sample_top_p_top_k(
  1548. llama_context * ctx,
  1549. const llama_token * last_n_tokens_data,
  1550. int last_n_tokens_size,
  1551. int top_k,
  1552. float top_p,
  1553. float temp,
  1554. float repeat_penalty) {
  1555. const int64_t t_start_sample_us = ggml_time_us();
  1556. llama_token result = 0;
  1557. // TODO: avoid this ...
  1558. const auto last_n_tokens = std::vector<llama_token>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_size);
  1559. result = llama_sample_top_p_top_k(
  1560. *ctx,
  1561. last_n_tokens,
  1562. top_k,
  1563. top_p,
  1564. temp,
  1565. repeat_penalty);
  1566. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1567. ctx->n_sample++;
  1568. return result;
  1569. }
  1570. void llama_print_timings(struct llama_context * ctx) {
  1571. const int64_t t_end_us = ggml_time_us();
  1572. const int32_t n_sample = std::max(1, ctx->n_sample);
  1573. const int32_t n_eval = std::max(1, ctx->n_eval);
  1574. const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
  1575. fprintf(stderr, "\n");
  1576. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0);
  1577. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_sample_us, n_sample, 1e-3 * ctx->t_sample_us / n_sample);
  1578. 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);
  1579. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_eval_us, n_eval, 1e-3 * ctx->t_eval_us / n_eval);
  1580. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0);
  1581. }
  1582. void llama_reset_timings(struct llama_context * ctx) {
  1583. ctx->t_start_us = ggml_time_us();
  1584. ctx->t_sample_us = ctx->n_sample = 0;
  1585. ctx->t_eval_us = ctx->n_eval = 0;
  1586. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  1587. }
  1588. const char * llama_print_system_info(void) {
  1589. static std::string s;
  1590. s = "";
  1591. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  1592. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  1593. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  1594. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  1595. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  1596. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  1597. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  1598. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  1599. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  1600. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  1601. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  1602. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  1603. return s.c_str();
  1604. }
  1605. // For internal test use
  1606. std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  1607. return ctx->model.tensors_by_name;
  1608. }