main.cpp 38 KB

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