main.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. #include "ggml.h"
  2. #include "utils.h"
  3. #include <cassert>
  4. #include <cinttypes>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <map>
  11. #include <string>
  12. #include <vector>
  13. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  14. #include <signal.h>
  15. #include <unistd.h>
  16. #elif defined (_WIN32)
  17. #include <signal.h>
  18. #endif
  19. #define ANSI_COLOR_RED "\x1b[31m"
  20. #define ANSI_COLOR_GREEN "\x1b[32m"
  21. #define ANSI_COLOR_YELLOW "\x1b[33m"
  22. #define ANSI_COLOR_BLUE "\x1b[34m"
  23. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  24. #define ANSI_COLOR_CYAN "\x1b[36m"
  25. #define ANSI_COLOR_RESET "\x1b[0m"
  26. #define ANSI_BOLD "\x1b[1m"
  27. static const int EOS_TOKEN_ID = 2;
  28. // determine number of model parts based on the dimension
  29. static const std::map<int, int> LLAMA_N_PARTS = {
  30. { 4096, 1 },
  31. { 5120, 2 },
  32. { 6656, 4 },
  33. { 8192, 8 },
  34. };
  35. // default hparams (LLaMA 7B)
  36. struct llama_hparams {
  37. int32_t n_vocab = 32000;
  38. int32_t n_ctx = 512; // this is provided as user input?
  39. int32_t n_embd = 4096;
  40. int32_t n_mult = 256;
  41. int32_t n_head = 32;
  42. int32_t n_layer = 32;
  43. int32_t n_rot = 64;
  44. int32_t f16 = 1;
  45. };
  46. struct llama_layer {
  47. // normalization
  48. struct ggml_tensor * attention_norm;
  49. // attention
  50. struct ggml_tensor * wq;
  51. struct ggml_tensor * wk;
  52. struct ggml_tensor * wv;
  53. struct ggml_tensor * wo;
  54. // normalization
  55. struct ggml_tensor * ffn_norm;
  56. // ff
  57. struct ggml_tensor * w1;
  58. struct ggml_tensor * w2;
  59. struct ggml_tensor * w3;
  60. };
  61. struct llama_model {
  62. llama_hparams hparams;
  63. struct ggml_tensor * tok_embeddings;
  64. struct ggml_tensor * norm;
  65. struct ggml_tensor * output;
  66. std::vector<llama_layer> layers;
  67. // key + value memory
  68. struct ggml_tensor * memory_k;
  69. struct ggml_tensor * memory_v;
  70. //
  71. struct ggml_context * ctx;
  72. std::map<std::string, struct ggml_tensor *> tensors;
  73. };
  74. // load the model's weights from a file
  75. bool llama_model_load(const std::string & fname, llama_model & model, llama_vocab & vocab, int n_ctx, ggml_type memory_type = GGML_TYPE_F32) {
  76. fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  77. std::vector<char> f_buf(1024*1024);
  78. auto fin = std::ifstream(fname, std::ios::binary);
  79. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  80. if (!fin) {
  81. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  82. return false;
  83. }
  84. // verify magic
  85. {
  86. uint32_t magic;
  87. fin.read((char *) &magic, sizeof(magic));
  88. if (magic == FILE_MAGIC_UNVERSIONED) {
  89. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  90. __func__, fname.c_str());
  91. return false;
  92. }
  93. if (magic != FILE_MAGIC) {
  94. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  95. return false;
  96. }
  97. uint32_t format_version;
  98. fin.read((char *) &format_version, sizeof(format_version));
  99. if (format_version != FILE_VERSION) {
  100. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  101. __func__, fname.c_str(), format_version, FILE_VERSION);
  102. return false;
  103. }
  104. }
  105. int n_ff = 0;
  106. int n_parts = 0;
  107. // load hparams
  108. {
  109. auto & hparams = model.hparams;
  110. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  111. //fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  112. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  113. fin.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  114. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  115. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  116. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  117. fin.read((char *) &hparams.f16, sizeof(hparams.f16));
  118. hparams.n_ctx = n_ctx;
  119. n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  120. n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
  121. fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  122. fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  123. fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
  124. fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
  125. fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
  126. fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
  127. fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
  128. fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
  129. fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
  130. fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
  131. }
  132. // load vocab
  133. {
  134. std::string word;
  135. for (int i = 0; i < model.hparams.n_vocab; i++) {
  136. uint32_t len;
  137. fin.read((char *) &len, sizeof(len));
  138. word.resize(len);
  139. fin.read((char *) word.data(), len);
  140. float score;
  141. fin.read((char *) &score, sizeof(score));
  142. vocab.token_to_id[word] = i;
  143. vocab.id_to_token[i] = word;
  144. vocab.score[i] = score;
  145. //if (i < 30000) {
  146. // fprintf(stderr, "%s: vocab[%d] = '%s'\n", __func__, i, word.c_str());
  147. //}
  148. }
  149. }
  150. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  151. // in order to save memory and also to speed up the computation
  152. ggml_type wtype = GGML_TYPE_COUNT;
  153. switch (model.hparams.f16) {
  154. case 0: wtype = GGML_TYPE_F32; break;
  155. case 1: wtype = GGML_TYPE_F16; break;
  156. case 2: wtype = GGML_TYPE_Q4_0; break;
  157. case 3: wtype = GGML_TYPE_Q4_1; break;
  158. default:
  159. {
  160. fprintf(stderr, "%s: invalid model file '%s' (bad f16 value %d)\n",
  161. __func__, fname.c_str(), model.hparams.f16);
  162. return false;
  163. }
  164. }
  165. auto & ctx = model.ctx;
  166. size_t ctx_size = 0;
  167. {
  168. const auto & hparams = model.hparams;
  169. const int n_embd = hparams.n_embd;
  170. const int n_layer = hparams.n_layer;
  171. const int n_ctx = hparams.n_ctx;
  172. const int n_vocab = hparams.n_vocab;
  173. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // tok_embeddings
  174. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // norm
  175. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // output
  176. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // attention_norm
  177. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wq
  178. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wk
  179. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wv
  180. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wo
  181. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ffn_norm
  182. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w1
  183. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w2
  184. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w3
  185. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_k
  186. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_v
  187. ctx_size += (5 + 10*n_layer)*256; // object overhead
  188. fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  189. }
  190. // create the ggml context
  191. {
  192. struct ggml_init_params params = {
  193. /*.mem_size =*/ ctx_size,
  194. /*.mem_buffer =*/ NULL,
  195. };
  196. model.ctx = ggml_init(params);
  197. if (!model.ctx) {
  198. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  199. return false;
  200. }
  201. }
  202. // prepare memory for the weights
  203. {
  204. const auto & hparams = model.hparams;
  205. const int n_embd = hparams.n_embd;
  206. const int n_layer = hparams.n_layer;
  207. const int n_vocab = hparams.n_vocab;
  208. model.layers.resize(n_layer);
  209. model.tok_embeddings = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  210. model.norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  211. model.output = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  212. // map by name
  213. model.tensors["tok_embeddings.weight"] = model.tok_embeddings;
  214. model.tensors["norm.weight"] = model.norm;
  215. model.tensors["output.weight"] = model.output;
  216. for (int i = 0; i < n_layer; ++i) {
  217. auto & layer = model.layers[i];
  218. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  219. layer.wq = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  220. layer.wk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  221. layer.wv = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  222. layer.wo = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  223. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  224. layer.w1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  225. layer.w2 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd);
  226. layer.w3 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  227. // map by name
  228. model.tensors["layers." + std::to_string(i) + ".attention_norm.weight"] = layer.attention_norm;
  229. model.tensors["layers." + std::to_string(i) + ".attention.wq.weight"] = layer.wq;
  230. model.tensors["layers." + std::to_string(i) + ".attention.wk.weight"] = layer.wk;
  231. model.tensors["layers." + std::to_string(i) + ".attention.wv.weight"] = layer.wv;
  232. model.tensors["layers." + std::to_string(i) + ".attention.wo.weight"] = layer.wo;
  233. model.tensors["layers." + std::to_string(i) + ".ffn_norm.weight"] = layer.ffn_norm;
  234. model.tensors["layers." + std::to_string(i) + ".feed_forward.w1.weight"] = layer.w1;
  235. model.tensors["layers." + std::to_string(i) + ".feed_forward.w2.weight"] = layer.w2;
  236. model.tensors["layers." + std::to_string(i) + ".feed_forward.w3.weight"] = layer.w3;
  237. }
  238. }
  239. // key + value memory
  240. {
  241. const auto & hparams = model.hparams;
  242. const int n_embd = hparams.n_embd;
  243. const int n_layer = hparams.n_layer;
  244. const int n_ctx = hparams.n_ctx;
  245. const int n_mem = n_layer*n_ctx;
  246. const int n_elements = n_embd*n_mem;
  247. model.memory_k = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  248. model.memory_v = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  249. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  250. fprintf(stderr, "%s: memory_size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  251. }
  252. const size_t file_offset = fin.tellg();
  253. fin.close();
  254. std::vector<uint8_t> tmp;
  255. for (int i = 0; i < n_parts; ++i) {
  256. const int part_id = i;
  257. //const int part_id = n_parts - i - 1;
  258. std::string fname_part = fname;
  259. if (i > 0) {
  260. fname_part += "." + std::to_string(i);
  261. }
  262. fprintf(stderr, "%s: loading model part %d/%d from '%s'\n", __func__, i+1, n_parts, fname_part.c_str());
  263. fin = std::ifstream(fname_part, std::ios::binary);
  264. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  265. fin.seekg(file_offset);
  266. // load weights
  267. {
  268. int n_tensors = 0;
  269. size_t total_size = 0;
  270. fprintf(stderr, "%s: ", __func__);
  271. while (true) {
  272. int32_t n_dims;
  273. int32_t length;
  274. int32_t ftype;
  275. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  276. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  277. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  278. if (fin.eof()) {
  279. break;
  280. }
  281. int32_t nelements = 1;
  282. int32_t ne[2] = { 1, 1 };
  283. for (int i = 0; i < n_dims; ++i) {
  284. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  285. nelements *= ne[i];
  286. }
  287. std::string name(length, 0);
  288. fin.read(&name[0], length);
  289. if (model.tensors.find(name.data()) == model.tensors.end()) {
  290. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
  291. return false;
  292. }
  293. // split_type = 0: split by columns
  294. // split_type = 1: split by rows
  295. int split_type = 0;
  296. // split_type = 0:
  297. // regex:
  298. // - tok_embeddings.*
  299. // - layers.*.attention.wo.weight
  300. // - layers.*.feed_forward.w2.weight
  301. // split_type = 1:
  302. // regex:
  303. // - output.*
  304. // - layers.*.attention.wq.weight
  305. // - layers.*.attention.wk.weight
  306. // - layers.*.attention.wv.weight
  307. // - layers.*.feed_forward.w1.weight
  308. // - layers.*.feed_forward.w3.weight
  309. if (name.find("tok_embeddings") != std::string::npos) {
  310. split_type = 0;
  311. } else if (name.find("layers") != std::string::npos) {
  312. if (name.find("attention.wo.weight") != std::string::npos) {
  313. split_type = 0;
  314. } else if (name.find("feed_forward.w2.weight") != std::string::npos) {
  315. split_type = 0;
  316. } else {
  317. split_type = 1;
  318. }
  319. } else if (name.find("output") != std::string::npos) {
  320. split_type = 1;
  321. }
  322. auto tensor = model.tensors[name.data()];
  323. if (n_dims == 1) {
  324. if (ggml_nelements(tensor) != nelements) {
  325. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  326. return false;
  327. }
  328. } else {
  329. if (ggml_nelements(tensor)/n_parts != nelements) {
  330. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  331. return false;
  332. }
  333. }
  334. if (n_dims == 1) {
  335. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  336. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  337. __func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
  338. return false;
  339. }
  340. } else {
  341. if (split_type == 0) {
  342. if (tensor->ne[0]/n_parts != ne[0] || tensor->ne[1] != ne[1]) {
  343. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  344. __func__, name.data(), tensor->ne[0]/n_parts, tensor->ne[1], ne[0], ne[1]);
  345. return false;
  346. }
  347. } else {
  348. if (tensor->ne[0] != ne[0] || tensor->ne[1]/n_parts != ne[1]) {
  349. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  350. __func__, name.data(), tensor->ne[0], tensor->ne[1]/n_parts, ne[0], ne[1]);
  351. return false;
  352. }
  353. }
  354. }
  355. if (0) {
  356. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  357. fprintf(stderr, "%24s - [%5d, %5d], type = %6s, split = %d\n", name.data(), ne[0], ne[1], ftype_str[ftype], split_type);
  358. }
  359. size_t bpe = 0;
  360. switch (ftype) {
  361. case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
  362. case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
  363. case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
  364. case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
  365. default:
  366. {
  367. fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
  368. return false;
  369. }
  370. };
  371. if (n_dims == 1 || n_parts == 1) {
  372. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  373. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  374. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  375. return false;
  376. }
  377. if (part_id == 0) {
  378. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  379. } else {
  380. fin.seekg(ggml_nbytes(tensor), std::ios::cur);
  381. }
  382. total_size += ggml_nbytes(tensor);
  383. } else {
  384. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)/n_parts) {
  385. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  386. __func__, name.data(), ggml_nbytes(tensor)/n_parts, nelements*bpe);
  387. return false;
  388. }
  389. if (split_type == 0) {
  390. const int np0 = ne[0];
  391. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  392. assert(row_size == tensor->nb[1]);
  393. for (int i1 = 0; i1 < ne[1]; ++i1) {
  394. const size_t offset_row = i1*row_size;
  395. const size_t offset = offset_row + ((part_id*np0)/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  396. fin.read(reinterpret_cast<char *>(tensor->data) + offset, row_size/n_parts);
  397. }
  398. } else {
  399. const int np1 = ne[1];
  400. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  401. for (int i1 = 0; i1 < ne[1]; ++i1) {
  402. const size_t offset_row = (i1 + part_id*np1)*row_size;
  403. fin.read(reinterpret_cast<char *>(tensor->data) + offset_row, row_size);
  404. }
  405. }
  406. total_size += ggml_nbytes(tensor)/n_parts;
  407. }
  408. //fprintf(stderr, "%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ftype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
  409. if (++n_tensors % 8 == 0) {
  410. fprintf(stderr, ".");
  411. fflush(stderr);
  412. }
  413. }
  414. fprintf(stderr, " done\n");
  415. fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
  416. }
  417. fin.close();
  418. }
  419. return true;
  420. }
  421. // evaluate the transformer
  422. //
  423. // - model: the model
  424. // - n_threads: number of threads to use
  425. // - n_past: the context size so far
  426. // - embd_inp: the embeddings of the tokens in the context
  427. // - embd_w: the predicted logits for the next token
  428. //
  429. // The GPT-J model requires about 16MB of memory per input token.
  430. //
  431. bool llama_eval(
  432. const llama_model & model,
  433. const int n_threads,
  434. const int n_past,
  435. const std::vector<llama_vocab::id> & embd_inp,
  436. std::vector<float> & embd_w,
  437. size_t & mem_per_token) {
  438. const int N = embd_inp.size();
  439. const auto & hparams = model.hparams;
  440. const int n_embd = hparams.n_embd;
  441. const int n_layer = hparams.n_layer;
  442. const int n_ctx = hparams.n_ctx;
  443. const int n_head = hparams.n_head;
  444. const int n_vocab = hparams.n_vocab;
  445. const int n_rot = hparams.n_embd/hparams.n_head;
  446. // TODO: check if this size scales with n_ctx linearly and remove constant. somehow I feel it wasn't the case
  447. // static size_t buf_size = hparams.n_ctx*1024*1024;
  448. static size_t buf_size = 512u*1024*1024;
  449. static void * buf = malloc(buf_size);
  450. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  451. const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
  452. //fprintf(stderr, "\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  453. // reallocate
  454. buf_size = buf_size_new;
  455. buf = realloc(buf, buf_size);
  456. if (buf == nullptr) {
  457. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  458. return false;
  459. }
  460. }
  461. struct ggml_init_params params = {
  462. /*.mem_size =*/ buf_size,
  463. /*.mem_buffer =*/ buf,
  464. };
  465. struct ggml_context * ctx0 = ggml_init(params);
  466. ggml_cgraph gf = {};
  467. gf.n_threads = n_threads;
  468. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  469. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  470. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  471. for (int il = 0; il < n_layer; ++il) {
  472. struct ggml_tensor * inpSA = inpL;
  473. struct ggml_tensor * cur;
  474. // norm
  475. {
  476. cur = ggml_rms_norm(ctx0, inpL);
  477. // cur = attention_norm*cur
  478. cur = ggml_mul(ctx0,
  479. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  480. cur);
  481. }
  482. // self-attention
  483. {
  484. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  485. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  486. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  487. // store key and value to memory
  488. if (N >= 1) {
  489. struct ggml_tensor * k = ggml_view_1d(ctx0, model.memory_k, N*n_embd, (ggml_element_size(model.memory_k)*n_embd)*(il*n_ctx + n_past));
  490. struct ggml_tensor * v = ggml_view_1d(ctx0, model.memory_v, N*n_embd, (ggml_element_size(model.memory_v)*n_embd)*(il*n_ctx + n_past));
  491. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  492. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  493. }
  494. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  495. struct ggml_tensor * Q =
  496. ggml_permute(ctx0,
  497. ggml_rope(ctx0,
  498. ggml_cpy(ctx0,
  499. Qcur,
  500. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  501. n_past, n_rot, 0),
  502. 0, 2, 1, 3);
  503. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  504. struct ggml_tensor * K =
  505. ggml_permute(ctx0,
  506. ggml_rope(ctx0,
  507. ggml_reshape_3d(ctx0,
  508. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  509. n_embd/n_head, n_head, n_past + N),
  510. n_past, n_rot, 1),
  511. 0, 2, 1, 3);
  512. // K * Q
  513. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  514. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  515. struct ggml_tensor * KQ_scaled =
  516. ggml_scale(ctx0,
  517. KQ,
  518. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  519. );
  520. // KQ_masked = mask_past(KQ_scaled)
  521. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  522. // KQ = soft_max(KQ_masked)
  523. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  524. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  525. struct ggml_tensor * V_trans =
  526. ggml_permute(ctx0,
  527. ggml_reshape_3d(ctx0,
  528. ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  529. n_embd/n_head, n_head, n_past + N),
  530. 1, 2, 0, 3);
  531. // KQV = transpose(V) * KQ_soft_max
  532. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  533. // KQV_merged = KQV.permute(0, 2, 1, 3)
  534. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  535. // cur = KQV_merged.contiguous().view(n_embd, N)
  536. cur = ggml_cpy(ctx0,
  537. KQV_merged,
  538. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  539. // projection (no bias)
  540. cur = ggml_mul_mat(ctx0,
  541. model.layers[il].wo,
  542. cur);
  543. }
  544. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  545. // feed-forward network
  546. {
  547. // norm
  548. {
  549. cur = ggml_rms_norm(ctx0, inpFF);
  550. // cur = ffn_norm*cur
  551. cur = ggml_mul(ctx0,
  552. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  553. cur);
  554. }
  555. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  556. model.layers[il].w3,
  557. cur);
  558. cur = ggml_mul_mat(ctx0,
  559. model.layers[il].w1,
  560. cur);
  561. // SILU activation
  562. cur = ggml_silu(ctx0, cur);
  563. cur = ggml_mul(ctx0, cur, tmp);
  564. cur = ggml_mul_mat(ctx0,
  565. model.layers[il].w2,
  566. cur);
  567. }
  568. cur = ggml_add(ctx0, cur, inpFF);
  569. // input for next layer
  570. inpL = cur;
  571. }
  572. // norm
  573. {
  574. inpL = ggml_rms_norm(ctx0, inpL);
  575. // inpL = norm*inpL
  576. inpL = ggml_mul(ctx0,
  577. ggml_repeat(ctx0, model.norm, inpL),
  578. inpL);
  579. }
  580. // lm_head
  581. {
  582. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  583. }
  584. // logits -> probs
  585. //inpL = ggml_soft_max(ctx0, inpL);
  586. // run the computation
  587. ggml_build_forward_expand(&gf, inpL);
  588. ggml_graph_compute (ctx0, &gf);
  589. //if (n_past%100 == 0) {
  590. // ggml_graph_print (&gf);
  591. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  592. //}
  593. //embd_w.resize(n_vocab*N);
  594. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  595. // return result for just the last token
  596. embd_w.resize(n_vocab);
  597. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  598. if (mem_per_token == 0) {
  599. mem_per_token = ggml_used_mem(ctx0)/N;
  600. }
  601. //fprintf(stderr, "used_mem = %zu\n", ggml_used_mem(ctx0));
  602. ggml_free(ctx0);
  603. return true;
  604. }
  605. static bool is_interacting = false;
  606. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  607. void sigint_handler(int signo) {
  608. printf(ANSI_COLOR_RESET);
  609. printf("\n"); // this also force flush stdout.
  610. if (signo == SIGINT) {
  611. if (!is_interacting) {
  612. is_interacting=true;
  613. } else {
  614. _exit(130);
  615. }
  616. }
  617. }
  618. #endif
  619. const char * llama_print_system_info(void) {
  620. static std::string s;
  621. s = "";
  622. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  623. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  624. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  625. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  626. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  627. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  628. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  629. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  630. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  631. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  632. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  633. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  634. return s.c_str();
  635. }
  636. int main(int argc, char ** argv) {
  637. ggml_time_init();
  638. const int64_t t_main_start_us = ggml_time_us();
  639. gpt_params params;
  640. params.model = "models/llama-7B/ggml-model.bin";
  641. if (gpt_params_parse(argc, argv, params) == false) {
  642. return 1;
  643. }
  644. if (params.n_ctx > 2048) {
  645. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  646. "expect poor results\n", __func__, params.n_ctx);
  647. }
  648. if (params.seed < 0) {
  649. params.seed = time(NULL);
  650. }
  651. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  652. std::mt19937 rng(params.seed);
  653. if (params.random_prompt) {
  654. params.prompt = gpt_random_prompt(rng);
  655. }
  656. // params.prompt = R"(// this function checks if the number n is prime
  657. //bool is_prime(int n) {)";
  658. int64_t t_load_us = 0;
  659. llama_vocab vocab;
  660. llama_model model;
  661. // load the model
  662. {
  663. const ggml_type memory_type = params.memory_f16 ? GGML_TYPE_F16 : GGML_TYPE_F32;
  664. const int64_t t_start_us = ggml_time_us();
  665. if (!llama_model_load(params.model, model, vocab, params.n_ctx, memory_type)) {
  666. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  667. return 1;
  668. }
  669. t_load_us = ggml_time_us() - t_start_us;
  670. }
  671. // print system information
  672. {
  673. fprintf(stderr, "\n");
  674. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  675. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  676. }
  677. int n_past = 0;
  678. int64_t t_sample_us = 0;
  679. int64_t t_predict_us = 0;
  680. std::vector<float> logits;
  681. // Add a space in front of the first character to match OG llama tokenizer behavior
  682. params.prompt.insert(0, 1, ' ');
  683. // tokenize the prompt
  684. std::vector<llama_vocab::id> embd_inp = ::llama_tokenize(vocab, params.prompt, true);
  685. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  686. // prefix & suffix for instruct mode
  687. const std::vector<llama_vocab::id> inp_pfx = ::llama_tokenize(vocab, "\n\n### Instruction:\n\n", true);
  688. const std::vector<llama_vocab::id> inp_sfx = ::llama_tokenize(vocab, "\n\n### Response:\n\n", false);
  689. // in instruct mode, we inject a prefix and a suffix to each input by the user
  690. if (params.instruct) {
  691. params.interactive = true;
  692. params.antiprompt.push_back("### Instruction:\n\n");
  693. }
  694. // tokenize the reverse prompt
  695. std::vector<std::vector<llama_vocab::id>> antipromptv_inp;
  696. for (auto antiprompt : params.antiprompt) {
  697. antipromptv_inp.push_back(::llama_tokenize(vocab, antiprompt, false));
  698. }
  699. // enable interactive mode if reverse prompt is specified
  700. if (antipromptv_inp.size() != 0) {
  701. params.interactive = true;
  702. }
  703. fprintf(stderr, "\n");
  704. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  705. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  706. for (int i = 0; i < (int) embd_inp.size(); i++) {
  707. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
  708. }
  709. fprintf(stderr, "\n");
  710. if (params.interactive) {
  711. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  712. struct sigaction sigint_action;
  713. sigint_action.sa_handler = sigint_handler;
  714. sigemptyset (&sigint_action.sa_mask);
  715. sigint_action.sa_flags = 0;
  716. sigaction(SIGINT, &sigint_action, NULL);
  717. #elif defined (_WIN32)
  718. signal(SIGINT, sigint_handler);
  719. #endif
  720. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  721. if(antipromptv_inp.size()) {
  722. for (size_t apindex = 0; apindex < antipromptv_inp.size(); ++apindex) {
  723. auto antiprompt_inp = antipromptv_inp.at(apindex);
  724. fprintf(stderr, "%s: reverse prompt: '%s'\n", __func__, params.antiprompt.at(apindex).c_str());
  725. fprintf(stderr, "%s: number of tokens in reverse prompt = %zu\n", __func__, antiprompt_inp.size());
  726. for (int i = 0; i < (int) antiprompt_inp.size(); i++) {
  727. fprintf(stderr, "%6d -> '%s'\n", antiprompt_inp[i], vocab.id_to_token.at(antiprompt_inp[i]).c_str());
  728. }
  729. fprintf(stderr, "\n");
  730. }
  731. }
  732. }
  733. fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n", params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  734. fprintf(stderr, "\n\n");
  735. std::vector<llama_vocab::id> embd;
  736. // determine the required inference memory per token:
  737. size_t mem_per_token = 0;
  738. llama_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  739. int last_n_size = params.repeat_last_n;
  740. std::vector<llama_vocab::id> last_n_tokens(last_n_size);
  741. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  742. if (params.interactive) {
  743. fprintf(stderr, "== Running in interactive mode. ==\n"
  744. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  745. " - Press Ctrl+C to interject at any time.\n"
  746. #endif
  747. " - Press Return to return control to LLaMa.\n"
  748. " - If you want to submit another line, end your input in '\\'.\n\n");
  749. is_interacting = true;
  750. }
  751. int input_consumed = 0;
  752. bool input_noecho = false;
  753. int remaining_tokens = params.n_predict;
  754. // set the color for the prompt which will be output initially
  755. if (params.use_color) {
  756. printf(ANSI_COLOR_YELLOW);
  757. }
  758. while (remaining_tokens > 0 || params.interactive) {
  759. // predict
  760. if (embd.size() > 0) {
  761. const int64_t t_start_us = ggml_time_us();
  762. if (!llama_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  763. fprintf(stderr, "Failed to predict\n");
  764. return 1;
  765. }
  766. t_predict_us += ggml_time_us() - t_start_us;
  767. }
  768. n_past += embd.size();
  769. embd.clear();
  770. if (embd_inp.size() <= input_consumed) {
  771. // out of user input, sample next token
  772. const float top_k = params.top_k;
  773. const float top_p = params.top_p;
  774. const float temp = params.temp;
  775. const float repeat_penalty = params.repeat_penalty;
  776. const int n_vocab = model.hparams.n_vocab;
  777. llama_vocab::id id = 0;
  778. {
  779. const int64_t t_start_sample_us = ggml_time_us();
  780. if (params.ignore_eos) {
  781. // set the logit of the eos token to zero to avoid sampling it
  782. logits[logits.size() - n_vocab + EOS_TOKEN_ID] = 0;
  783. }
  784. id = llama_sample_top_p_top_k(vocab, logits.data() + (logits.size() - n_vocab), last_n_tokens, repeat_penalty, top_k, top_p, temp, rng);
  785. last_n_tokens.erase(last_n_tokens.begin());
  786. last_n_tokens.push_back(id);
  787. t_sample_us += ggml_time_us() - t_start_sample_us;
  788. }
  789. // add it to the context
  790. embd.push_back(id);
  791. // echo this to console
  792. input_noecho = false;
  793. // decrement remaining sampling budget
  794. --remaining_tokens;
  795. } else {
  796. // some user input remains from prompt or interaction, forward it to processing
  797. while (embd_inp.size() > input_consumed) {
  798. embd.push_back(embd_inp[input_consumed]);
  799. last_n_tokens.erase(last_n_tokens.begin());
  800. last_n_tokens.push_back(embd_inp[input_consumed]);
  801. ++input_consumed;
  802. if ((int) embd.size() >= params.n_batch) {
  803. break;
  804. }
  805. }
  806. }
  807. // display text
  808. if (!input_noecho) {
  809. for (auto id : embd) {
  810. printf("%s", vocab.id_to_token[id].c_str());
  811. }
  812. fflush(stdout);
  813. }
  814. // reset color to default if we there is no pending user input
  815. if (!input_noecho && params.use_color && (int)embd_inp.size() == input_consumed) {
  816. printf(ANSI_COLOR_RESET);
  817. }
  818. // in interactive mode, and not currently processing queued inputs;
  819. // check if we should prompt the user for more
  820. if (params.interactive && embd_inp.size() <= input_consumed) {
  821. // check for reverse prompt
  822. for (auto antiprompt_inp : antipromptv_inp) {
  823. if (antiprompt_inp.size() && std::equal(antiprompt_inp.rbegin(), antiprompt_inp.rend(), last_n_tokens.rbegin())) {
  824. // reverse prompt found
  825. is_interacting = true;
  826. break;
  827. }
  828. }
  829. if (is_interacting) {
  830. if (params.instruct) {
  831. input_consumed = embd_inp.size();
  832. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  833. printf("\n> ");
  834. }
  835. // currently being interactive
  836. if (params.use_color) printf(ANSI_BOLD ANSI_COLOR_GREEN);
  837. std::string buffer;
  838. std::string line;
  839. bool another_line = true;
  840. do {
  841. std::getline(std::cin, line);
  842. if (line.empty() || line.back() != '\\') {
  843. another_line = false;
  844. } else {
  845. line.pop_back(); // Remove the continue character
  846. }
  847. buffer += line + '\n'; // Append the line to the result
  848. } while (another_line);
  849. if (params.use_color) printf(ANSI_COLOR_RESET);
  850. std::vector<llama_vocab::id> line_inp = ::llama_tokenize(vocab, buffer, false);
  851. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  852. if (params.instruct) {
  853. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  854. }
  855. remaining_tokens -= line_inp.size();
  856. input_noecho = true; // do not echo this again
  857. }
  858. is_interacting = false;
  859. }
  860. // end of text token
  861. if (embd.back() == EOS_TOKEN_ID) {
  862. if (params.interactive) {
  863. is_interacting = true;
  864. } else {
  865. fprintf(stderr, " [end of text]\n");
  866. break;
  867. }
  868. }
  869. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  870. if (params.interactive && remaining_tokens <= 0) {
  871. remaining_tokens = params.n_predict;
  872. is_interacting = true;
  873. }
  874. }
  875. #if defined (_WIN32)
  876. signal(SIGINT, SIG_DFL);
  877. #endif
  878. // report timing
  879. {
  880. const int64_t t_main_end_us = ggml_time_us();
  881. fprintf(stderr, "\n\n");
  882. fprintf(stderr, "%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  883. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  884. fprintf(stderr, "%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  885. fprintf(stderr, "%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
  886. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  887. }
  888. ggml_free(model.ctx);
  889. if (params.use_color) {
  890. printf(ANSI_COLOR_RESET);
  891. }
  892. return 0;
  893. }