main.cpp 41 KB

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