main.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. #include "ggml/ggml.h"
  2. #include "common.h"
  3. #include "common-ggml.h"
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <map>
  10. #include <string>
  11. #include <vector>
  12. #if defined(_MSC_VER)
  13. #pragma warning(disable: 4244 4267) // possible loss of data
  14. #endif
  15. // default hparams (GPT-J 6B)
  16. struct gptj_hparams {
  17. int32_t n_vocab = 50400;
  18. int32_t n_ctx = 2048;
  19. int32_t n_embd = 4096;
  20. int32_t n_head = 16;
  21. int32_t n_layer = 28;
  22. int32_t n_rot = 64;
  23. int32_t ftype = 1;
  24. float eps = 1e-5f;
  25. };
  26. struct gptj_layer {
  27. // normalization
  28. struct ggml_tensor * ln_1_g;
  29. struct ggml_tensor * ln_1_b;
  30. // attention
  31. struct ggml_tensor * c_attn_q_proj_w;
  32. struct ggml_tensor * c_attn_k_proj_w;
  33. struct ggml_tensor * c_attn_v_proj_w;
  34. struct ggml_tensor * c_attn_proj_w;
  35. // ff
  36. struct ggml_tensor * c_mlp_fc_w;
  37. struct ggml_tensor * c_mlp_fc_b;
  38. struct ggml_tensor * c_mlp_proj_w;
  39. struct ggml_tensor * c_mlp_proj_b;
  40. };
  41. struct gptj_model {
  42. gptj_hparams hparams;
  43. // normalization
  44. struct ggml_tensor * ln_f_g;
  45. struct ggml_tensor * ln_f_b;
  46. struct ggml_tensor * wte; // position embedding
  47. struct ggml_tensor * lmh_g; // language model head
  48. struct ggml_tensor * lmh_b; // language model bias
  49. std::vector<gptj_layer> layers;
  50. // key + value memory
  51. struct ggml_tensor * memory_k;
  52. struct ggml_tensor * memory_v;
  53. //
  54. struct ggml_context * ctx;
  55. std::map<std::string, struct ggml_tensor *> tensors;
  56. };
  57. // load the model's weights from a file
  58. bool gptj_model_load(const std::string & fname, gptj_model & model, gpt_vocab & vocab) {
  59. printf("%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  60. auto fin = std::ifstream(fname, std::ios::binary);
  61. if (!fin) {
  62. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  63. return false;
  64. }
  65. // verify magic
  66. {
  67. uint32_t magic;
  68. fin.read((char *) &magic, sizeof(magic));
  69. if (magic != GGML_FILE_MAGIC) {
  70. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  71. return false;
  72. }
  73. }
  74. // load hparams
  75. {
  76. auto & hparams = model.hparams;
  77. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  78. fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  79. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  80. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  81. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  82. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  83. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  84. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  85. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  86. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  87. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  88. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  89. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  90. printf("%s: n_rot = %d\n", __func__, hparams.n_rot);
  91. printf("%s: ftype = %d\n", __func__, hparams.ftype);
  92. printf("%s: qntvr = %d\n", __func__, qntvr);
  93. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  94. }
  95. // load vocab
  96. {
  97. int32_t n_vocab = 0;
  98. fin.read((char *) &n_vocab, sizeof(n_vocab));
  99. if (n_vocab != model.hparams.n_vocab) {
  100. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  101. __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
  102. return false;
  103. }
  104. std::string word;
  105. std::vector<char> buf(128);
  106. for (int i = 0; i < n_vocab; i++) {
  107. uint32_t len;
  108. fin.read((char *) &len, sizeof(len));
  109. buf.resize(len);
  110. fin.read((char *) buf.data(), len);
  111. word.assign(buf.data(), len);
  112. vocab.token_to_id[word] = i;
  113. vocab.id_to_token[i] = word;
  114. }
  115. }
  116. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  117. // in order to save memory and also to speed up the computation
  118. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
  119. if (wtype == GGML_TYPE_COUNT) {
  120. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
  121. __func__, fname.c_str(), model.hparams.ftype);
  122. return false;
  123. }
  124. auto & ctx = model.ctx;
  125. size_t ctx_size = 0;
  126. {
  127. const auto & hparams = model.hparams;
  128. const int n_embd = hparams.n_embd;
  129. const int n_layer = hparams.n_layer;
  130. const int n_ctx = hparams.n_ctx;
  131. const int n_vocab = hparams.n_vocab;
  132. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_g
  133. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_b
  134. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // wte
  135. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // lmh_g
  136. ctx_size += n_vocab*ggml_type_sizef(GGML_TYPE_F32); // lmh_b
  137. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_g
  138. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_b
  139. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_q_proj_w
  140. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_k_proj_w
  141. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_v_proj_w
  142. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_proj_w
  143. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_fc_w
  144. ctx_size += n_layer*( 4*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_fc_b
  145. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_proj_w
  146. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_proj_b
  147. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F16); // memory_k
  148. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F16); // memory_v
  149. ctx_size += (5 + 10*n_layer)*512; // object overhead
  150. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  151. }
  152. // create the ggml context
  153. {
  154. struct ggml_init_params params = {
  155. /*.mem_size =*/ ctx_size,
  156. /*.mem_buffer =*/ NULL,
  157. /*.no_alloc =*/ false,
  158. };
  159. model.ctx = ggml_init(params);
  160. if (!model.ctx) {
  161. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  162. return false;
  163. }
  164. }
  165. // prepare memory for the weights
  166. {
  167. const auto & hparams = model.hparams;
  168. const int n_embd = hparams.n_embd;
  169. const int n_layer = hparams.n_layer;
  170. const int n_vocab = hparams.n_vocab;
  171. model.layers.resize(n_layer);
  172. model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  173. model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  174. model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  175. model.lmh_g = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  176. model.lmh_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_vocab);
  177. // map by name
  178. model.tensors["transformer.wte.weight"] = model.wte;
  179. model.tensors["transformer.ln_f.weight"] = model.ln_f_g;
  180. model.tensors["transformer.ln_f.bias"] = model.ln_f_b;
  181. model.tensors["lm_head.weight"] = model.lmh_g;
  182. model.tensors["lm_head.bias"] = model.lmh_b;
  183. for (int i = 0; i < n_layer; ++i) {
  184. auto & layer = model.layers[i];
  185. layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  186. layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  187. layer.c_attn_q_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  188. layer.c_attn_k_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  189. layer.c_attn_v_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  190. layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  191. layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd);
  192. layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
  193. layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
  194. layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  195. // map by name
  196. model.tensors["transformer.h." + std::to_string(i) + ".ln_1.weight"] = layer.ln_1_g;
  197. model.tensors["transformer.h." + std::to_string(i) + ".ln_1.bias"] = layer.ln_1_b;
  198. model.tensors["transformer.h." + std::to_string(i) + ".attn.q_proj.weight"] = layer.c_attn_q_proj_w;
  199. model.tensors["transformer.h." + std::to_string(i) + ".attn.k_proj.weight"] = layer.c_attn_k_proj_w;
  200. model.tensors["transformer.h." + std::to_string(i) + ".attn.v_proj.weight"] = layer.c_attn_v_proj_w;
  201. model.tensors["transformer.h." + std::to_string(i) + ".attn.out_proj.weight"] = layer.c_attn_proj_w;
  202. model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_in.weight"] = layer.c_mlp_fc_w;
  203. model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_in.bias"] = layer.c_mlp_fc_b;
  204. model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_out.weight"] = layer.c_mlp_proj_w;
  205. model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_out.bias"] = layer.c_mlp_proj_b;
  206. }
  207. }
  208. // key + value memory
  209. {
  210. const auto & hparams = model.hparams;
  211. const int n_embd = hparams.n_embd;
  212. const int n_layer = hparams.n_layer;
  213. const int n_ctx = hparams.n_ctx;
  214. const int n_mem = n_layer*n_ctx;
  215. const int n_elements = n_embd*n_mem;
  216. model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  217. model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  218. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  219. printf("%s: memory_size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  220. }
  221. // load weights
  222. {
  223. int n_tensors = 0;
  224. size_t total_size = 0;
  225. printf("%s: ", __func__);
  226. while (true) {
  227. int32_t n_dims;
  228. int32_t length;
  229. int32_t ttype;
  230. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  231. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  232. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  233. if (fin.eof()) {
  234. break;
  235. }
  236. int32_t nelements = 1;
  237. int32_t ne[2] = { 1, 1 };
  238. for (int i = 0; i < n_dims; ++i) {
  239. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  240. nelements *= ne[i];
  241. }
  242. std::string name(length, 0);
  243. fin.read(&name[0], length);
  244. if (model.tensors.find(name) == model.tensors.end()) {
  245. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  246. return false;
  247. }
  248. auto tensor = model.tensors[name];
  249. if (ggml_nelements(tensor) != nelements) {
  250. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  251. return false;
  252. }
  253. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  254. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  255. __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
  256. return false;
  257. }
  258. // for debugging
  259. if (0) {
  260. printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), ne[0], ne[1], ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor)/1024.0/1024.0, ggml_nbytes(tensor));
  261. }
  262. const size_t bpe = ggml_type_size(ggml_type(ttype));
  263. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  264. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  265. __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe);
  266. return false;
  267. }
  268. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  269. //printf("%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.c_str(), ne[0], ne[1], ttype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
  270. total_size += ggml_nbytes(tensor);
  271. if (++n_tensors % 8 == 0) {
  272. printf(".");
  273. fflush(stdout);
  274. }
  275. }
  276. printf(" done\n");
  277. printf("%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
  278. }
  279. fin.close();
  280. return true;
  281. }
  282. // evaluate the transformer
  283. //
  284. // - model: the model
  285. // - n_threads: number of threads to use
  286. // - n_past: the context size so far
  287. // - embd_inp: the embeddings of the tokens in the context
  288. // - embd_w: the predicted logits for the next token
  289. //
  290. // The GPT-J model requires about 16MB of memory per input token.
  291. //
  292. bool gptj_eval(
  293. const gptj_model & model,
  294. const int n_threads,
  295. const int n_past,
  296. const std::vector<gpt_vocab::id> & embd_inp,
  297. std::vector<float> & embd_w,
  298. size_t & mem_per_token) {
  299. const int N = embd_inp.size();
  300. const auto & hparams = model.hparams;
  301. const int n_embd = hparams.n_embd;
  302. const int n_layer = hparams.n_layer;
  303. const int n_ctx = hparams.n_ctx;
  304. const int n_head = hparams.n_head;
  305. const int n_vocab = hparams.n_vocab;
  306. const int n_rot = hparams.n_rot;
  307. static size_t buf_size = 256u*1024*1024;
  308. static void * buf = malloc(buf_size);
  309. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  310. const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
  311. //printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  312. // reallocate
  313. buf_size = buf_size_new;
  314. buf = realloc(buf, buf_size);
  315. if (buf == nullptr) {
  316. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  317. return false;
  318. }
  319. }
  320. struct ggml_init_params params = {
  321. /*.mem_size =*/ buf_size,
  322. /*.mem_buffer =*/ buf,
  323. /*.no_alloc =*/ false,
  324. };
  325. struct ggml_context * ctx0 = ggml_init(params);
  326. struct ggml_cgraph gf = {};
  327. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  328. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  329. // wte
  330. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.wte, embd);
  331. for (int il = 0; il < n_layer; ++il) {
  332. struct ggml_tensor * cur;
  333. // norm
  334. {
  335. cur = ggml_norm(ctx0, inpL, hparams.eps);
  336. // cur = ln_1_g*cur + ln_1_b
  337. cur = ggml_add(ctx0,
  338. ggml_mul(ctx0,
  339. ggml_repeat(ctx0, model.layers[il].ln_1_g, cur),
  340. cur),
  341. ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
  342. }
  343. struct ggml_tensor * inpSA = cur;
  344. // self-attention
  345. {
  346. struct ggml_tensor * Qcur = ggml_rope_inplace(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_q_proj_w, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0, 0);
  347. struct ggml_tensor * Kcur = ggml_rope_inplace(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_k_proj_w, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0, 0);
  348. // store key and value to memory
  349. {
  350. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_v_proj_w, cur));
  351. 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));
  352. struct ggml_tensor * v = ggml_view_2d(ctx0, model.memory_v, N, n_embd,
  353. ( n_ctx)*ggml_element_size(model.memory_v),
  354. (il*n_ctx)*ggml_element_size(model.memory_v)*n_embd + n_past*ggml_element_size(model.memory_v));
  355. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  356. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  357. }
  358. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  359. struct ggml_tensor * Q =
  360. ggml_permute(ctx0,
  361. Qcur,
  362. 0, 2, 1, 3);
  363. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  364. struct ggml_tensor * K =
  365. ggml_permute(ctx0,
  366. ggml_reshape_3d(ctx0,
  367. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  368. n_embd/n_head, n_head, n_past + N),
  369. 0, 2, 1, 3);
  370. // K * Q
  371. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  372. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  373. struct ggml_tensor * KQ_scaled =
  374. ggml_scale_inplace(ctx0,
  375. KQ,
  376. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  377. );
  378. // KQ_masked = mask_past(KQ_scaled)
  379. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  380. // KQ = soft_max(KQ_masked)
  381. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  382. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  383. struct ggml_tensor * V =
  384. ggml_view_3d(ctx0, model.memory_v,
  385. n_past + N, n_embd/n_head, n_head,
  386. n_ctx*ggml_element_size(model.memory_v),
  387. n_ctx*ggml_element_size(model.memory_v)*n_embd/n_head,
  388. il*n_ctx*ggml_element_size(model.memory_v)*n_embd);
  389. // KQV = transpose(V) * KQ_soft_max
  390. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  391. // KQV_merged = KQV.permute(0, 2, 1, 3)
  392. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  393. // cur = KQV_merged.contiguous().view(n_embd, N)
  394. cur = ggml_cpy(ctx0,
  395. KQV_merged,
  396. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  397. // projection (no bias)
  398. cur = ggml_mul_mat(ctx0,
  399. model.layers[il].c_attn_proj_w,
  400. cur);
  401. }
  402. struct ggml_tensor * inpFF = cur;
  403. // feed-forward network
  404. // this is independent of the self-attention result, so it could be done in parallel to the self-attention
  405. {
  406. // note here we pass inpSA instead of cur
  407. cur = ggml_mul_mat(ctx0,
  408. model.layers[il].c_mlp_fc_w,
  409. inpSA);
  410. cur = ggml_add(ctx0,
  411. ggml_repeat(ctx0, model.layers[il].c_mlp_fc_b, cur),
  412. cur);
  413. // GELU activation
  414. cur = ggml_gelu(ctx0, cur);
  415. // projection
  416. // cur = proj_w*cur + proj_b
  417. cur = ggml_mul_mat(ctx0,
  418. model.layers[il].c_mlp_proj_w,
  419. cur);
  420. cur = ggml_add(ctx0,
  421. ggml_repeat(ctx0, model.layers[il].c_mlp_proj_b, cur),
  422. cur);
  423. }
  424. // self-attention + FF
  425. cur = ggml_add(ctx0, cur, inpFF);
  426. // input for next layer
  427. inpL = ggml_add(ctx0, cur, inpL);
  428. }
  429. // norm
  430. {
  431. inpL = ggml_norm(ctx0, inpL, hparams.eps);
  432. // inpL = ln_f_g*inpL + ln_f_b
  433. inpL = ggml_add(ctx0,
  434. ggml_mul(ctx0,
  435. ggml_repeat(ctx0, model.ln_f_g, inpL),
  436. inpL),
  437. ggml_repeat(ctx0, model.ln_f_b, inpL));
  438. }
  439. // lm_head
  440. {
  441. inpL = ggml_mul_mat(ctx0, model.lmh_g, inpL);
  442. inpL = ggml_add(ctx0,
  443. ggml_repeat(ctx0, model.lmh_b, inpL),
  444. inpL);
  445. }
  446. // logits -> probs
  447. //inpL = ggml_soft_max_inplace(ctx0, inpL);
  448. // run the computation
  449. ggml_build_forward_expand(&gf, inpL);
  450. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  451. //if (n_past%100 == 0) {
  452. // ggml_graph_print (&gf);
  453. // ggml_graph_dump_dot(&gf, NULL, "gpt-j.dot");
  454. //}
  455. //embd_w.resize(n_vocab*N);
  456. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  457. // return result for just the last token
  458. embd_w.resize(n_vocab);
  459. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  460. if (mem_per_token == 0) {
  461. mem_per_token = ggml_used_mem(ctx0)/N;
  462. }
  463. //printf("used_mem = %zu\n", ggml_used_mem(ctx0));
  464. ggml_free(ctx0);
  465. return true;
  466. }
  467. int main(int argc, char ** argv) {
  468. ggml_time_init();
  469. const int64_t t_main_start_us = ggml_time_us();
  470. gpt_params params;
  471. params.model = "models/gpt-j-6B/ggml-model.bin";
  472. if (gpt_params_parse(argc, argv, params) == false) {
  473. return 1;
  474. }
  475. if (params.seed < 0) {
  476. params.seed = time(NULL);
  477. }
  478. printf("%s: seed = %d\n", __func__, params.seed);
  479. std::mt19937 rng(params.seed);
  480. if (params.prompt.empty()) {
  481. params.prompt = gpt_random_prompt(rng);
  482. }
  483. int64_t t_load_us = 0;
  484. gpt_vocab vocab;
  485. gptj_model model;
  486. // load the model
  487. {
  488. const int64_t t_start_us = ggml_time_us();
  489. if (!gptj_model_load(params.model, model, vocab)) {
  490. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  491. return 1;
  492. }
  493. t_load_us = ggml_time_us() - t_start_us;
  494. test_gpt_tokenizer(vocab, params.token_test);
  495. }
  496. int n_past = 0;
  497. int64_t t_sample_us = 0;
  498. int64_t t_predict_us = 0;
  499. std::vector<float> logits;
  500. // tokenize the prompt
  501. std::vector<gpt_vocab::id> embd_inp = ::gpt_tokenize(vocab, params.prompt);
  502. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  503. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  504. printf("\n");
  505. std::vector<gpt_vocab::id> embd;
  506. // determine the required inference memory per token:
  507. size_t mem_per_token = 0;
  508. gptj_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  509. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  510. // predict
  511. if (embd.size() > 0) {
  512. const int64_t t_start_us = ggml_time_us();
  513. if (!gptj_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  514. printf("Failed to predict\n");
  515. return 1;
  516. }
  517. t_predict_us += ggml_time_us() - t_start_us;
  518. }
  519. n_past += embd.size();
  520. embd.clear();
  521. if (i >= embd_inp.size()) {
  522. // sample next token
  523. const int top_k = params.top_k;
  524. const float top_p = params.top_p;
  525. const float temp = params.temp;
  526. const int n_vocab = model.hparams.n_vocab;
  527. gpt_vocab::id id = 0;
  528. {
  529. const int64_t t_start_sample_us = ggml_time_us();
  530. id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
  531. t_sample_us += ggml_time_us() - t_start_sample_us;
  532. }
  533. // add it to the context
  534. embd.push_back(id);
  535. } else {
  536. // if here, it means we are still processing the input prompt
  537. for (size_t k = i; k < embd_inp.size(); k++) {
  538. embd.push_back(embd_inp[k]);
  539. if (int32_t(embd.size()) > params.n_batch) {
  540. break;
  541. }
  542. }
  543. i += embd.size() - 1;
  544. }
  545. // display text
  546. for (auto id : embd) {
  547. printf("%s", vocab.id_to_token[id].c_str());
  548. }
  549. fflush(stdout);
  550. // end of text token
  551. if (embd.back() == 50256) {
  552. break;
  553. }
  554. }
  555. // report timing
  556. {
  557. const int64_t t_main_end_us = ggml_time_us();
  558. printf("\n\n");
  559. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  560. printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  561. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  562. 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);
  563. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  564. }
  565. ggml_free(model.ctx);
  566. return 0;
  567. }