main.cpp 35 KB

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