llama.cpp 75 KB

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