main.cpp 40 KB

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