llama.cpp 63 KB

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