main.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. #include "ggml/ggml.h"
  2. #include "ggml/ggml-alloc.h"
  3. #include "common.h"
  4. #include "common-ggml.h"
  5. #include <cassert>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <fstream>
  10. #include <map>
  11. #include <string>
  12. #include <vector>
  13. #if defined(_MSC_VER)
  14. #pragma warning(disable: 4244 4267) // possible loss of data
  15. #endif
  16. // default hparams (GPT-2 117M)
  17. struct gpt2_hparams {
  18. int32_t n_vocab = 50257;
  19. int32_t n_ctx = 1024;
  20. int32_t n_embd = 768;
  21. int32_t n_head = 12;
  22. int32_t n_layer = 12;
  23. int32_t ftype = 1;
  24. float eps = 1e-5f;
  25. };
  26. struct gpt2_layer {
  27. // normalization
  28. struct ggml_tensor * ln_1_g;
  29. struct ggml_tensor * ln_1_b;
  30. struct ggml_tensor * ln_2_g;
  31. struct ggml_tensor * ln_2_b;
  32. // attention
  33. struct ggml_tensor * c_attn_attn_w;
  34. struct ggml_tensor * c_attn_attn_b;
  35. struct ggml_tensor * c_attn_proj_w;
  36. struct ggml_tensor * c_attn_proj_b;
  37. // mlp
  38. struct ggml_tensor * c_mlp_fc_w;
  39. struct ggml_tensor * c_mlp_fc_b;
  40. struct ggml_tensor * c_mlp_proj_w;
  41. struct ggml_tensor * c_mlp_proj_b;
  42. };
  43. struct gpt2_model {
  44. gpt2_hparams hparams;
  45. // normalization
  46. struct ggml_tensor * ln_f_g;
  47. struct ggml_tensor * ln_f_b;
  48. struct ggml_tensor * wte; // position embedding
  49. struct ggml_tensor * wpe; // token embedding
  50. struct ggml_tensor * lm_head; // language model head
  51. std::vector<gpt2_layer> layers;
  52. // key + value memory
  53. struct ggml_tensor * memory_k;
  54. struct ggml_tensor * memory_v;
  55. //
  56. struct ggml_context * ctx;
  57. std::map<std::string, struct ggml_tensor *> tensors;
  58. };
  59. // load the model's weights from a file
  60. bool gpt2_model_load(const std::string & fname, gpt2_model & model, gpt_vocab & vocab) {
  61. printf("%s: loading model from '%s'\n", __func__, fname.c_str());
  62. auto fin = std::ifstream(fname, std::ios::binary);
  63. if (!fin) {
  64. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  65. return false;
  66. }
  67. // verify magic
  68. {
  69. uint32_t magic;
  70. fin.read((char *) &magic, sizeof(magic));
  71. if (magic != GGML_FILE_MAGIC) {
  72. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  73. return false;
  74. }
  75. }
  76. // load hparams
  77. {
  78. auto & hparams = model.hparams;
  79. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  80. fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  81. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  82. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  83. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  84. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  85. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  86. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  87. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  88. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  89. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  90. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  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_vocab*n_embd*ggml_type_sizef(wtype); // wte
  135. ctx_size += n_ctx*n_embd*ggml_type_sizef(GGML_TYPE_F32); // wpe
  136. ctx_size += n_vocab*n_embd*ggml_type_sizef(wtype); // lm_head
  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*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_g
  140. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_b
  141. ctx_size += n_layer*(3*n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_attn_w
  142. ctx_size += n_layer*( 3*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_attn_b
  143. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_proj_w
  144. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_proj_b
  145. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_fc_w
  146. ctx_size += n_layer*( 4*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_fc_b
  147. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_proj_w
  148. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_proj_b
  149. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_k
  150. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_v
  151. ctx_size += (6 + 12*n_layer)*512; // object overhead
  152. printf("%s: ggml tensor size = %d bytes\n", __func__, (int) sizeof(ggml_tensor));
  153. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  154. }
  155. // create the ggml context
  156. {
  157. struct ggml_init_params params = {
  158. /*.mem_size =*/ ctx_size,
  159. /*.mem_buffer =*/ NULL,
  160. /*.no_alloc =*/ false,
  161. };
  162. model.ctx = ggml_init(params);
  163. if (!model.ctx) {
  164. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  165. return false;
  166. }
  167. }
  168. // prepare memory for the weights
  169. {
  170. const auto & hparams = model.hparams;
  171. const int n_embd = hparams.n_embd;
  172. const int n_layer = hparams.n_layer;
  173. const int n_ctx = hparams.n_ctx;
  174. const int n_vocab = hparams.n_vocab;
  175. model.layers.resize(n_layer);
  176. model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  177. model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  178. model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  179. model.wpe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ctx);
  180. model.lm_head = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  181. // map by name
  182. model.tensors["model/ln_f/g"] = model.ln_f_g;
  183. model.tensors["model/ln_f/b"] = model.ln_f_b;
  184. model.tensors["model/wte"] = model.wte;
  185. model.tensors["model/wpe"] = model.wpe;
  186. model.tensors["model/lm_head"] = model.lm_head;
  187. for (int i = 0; i < n_layer; ++i) {
  188. auto & layer = model.layers[i];
  189. layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  190. layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  191. layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  192. layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  193. layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 3*n_embd);
  194. layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_embd);
  195. layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  196. layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  197. layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd);
  198. layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
  199. layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
  200. layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  201. // map by name
  202. model.tensors["model/h" + std::to_string(i) + "/ln_1/g"] = layer.ln_1_g;
  203. model.tensors["model/h" + std::to_string(i) + "/ln_1/b"] = layer.ln_1_b;
  204. model.tensors["model/h" + std::to_string(i) + "/ln_2/g"] = layer.ln_2_g;
  205. model.tensors["model/h" + std::to_string(i) + "/ln_2/b"] = layer.ln_2_b;
  206. model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/w"] = layer.c_attn_attn_w;
  207. model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/b"] = layer.c_attn_attn_b;
  208. model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/w"] = layer.c_attn_proj_w;
  209. model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/b"] = layer.c_attn_proj_b;
  210. model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/w"] = layer.c_mlp_fc_w;
  211. model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/b"] = layer.c_mlp_fc_b;
  212. model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/w"] = layer.c_mlp_proj_w;
  213. model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/b"] = layer.c_mlp_proj_b;
  214. }
  215. }
  216. // key + value memory
  217. {
  218. const auto & hparams = model.hparams;
  219. const int n_embd = hparams.n_embd;
  220. const int n_layer = hparams.n_layer;
  221. const int n_ctx = hparams.n_ctx;
  222. const int n_mem = n_layer*n_ctx;
  223. const int n_elements = n_embd*n_mem;
  224. model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
  225. model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
  226. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  227. printf("%s: memory size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  228. }
  229. // load weights
  230. {
  231. size_t total_size = 0;
  232. bool has_lm_head = false;
  233. while (true) {
  234. int32_t n_dims;
  235. int32_t length;
  236. int32_t ttype;
  237. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  238. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  239. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  240. if (fin.eof()) {
  241. break;
  242. }
  243. int32_t nelements = 1;
  244. int32_t ne[2] = { 1, 1 };
  245. for (int i = 0; i < n_dims; ++i) {
  246. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  247. nelements *= ne[i];
  248. }
  249. std::string name(length, 0);
  250. fin.read(&name[0], length);
  251. if (model.tensors.find(name) == model.tensors.end()) {
  252. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  253. return false;
  254. }
  255. auto tensor = model.tensors[name];
  256. if (ggml_nelements(tensor) != nelements) {
  257. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  258. return false;
  259. }
  260. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  261. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  262. __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
  263. return false;
  264. }
  265. // for debugging
  266. if (0) {
  267. 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));
  268. }
  269. const size_t bpe = ggml_type_size(ggml_type(ttype));
  270. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  271. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  272. __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe);
  273. return false;
  274. }
  275. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  276. // GPT-2 models share the WTE tensor as the LM head
  277. if (name == "model/wte" && has_lm_head == false) {
  278. memcpy(model.lm_head->data, tensor->data, ggml_nbytes(tensor));
  279. }
  280. if (name == "model/lm_head") {
  281. has_lm_head = true;
  282. }
  283. total_size += ggml_nbytes(tensor);
  284. }
  285. printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0);
  286. }
  287. fin.close();
  288. return true;
  289. }
  290. // build the computation graph
  291. struct ggml_cgraph * gpt2_graph(
  292. const gpt2_model & model,
  293. struct ggml_allocr * allocr,
  294. const int n_past,
  295. const std::vector<gpt_vocab::id> & embd_inp) {
  296. const int N = embd_inp.size();
  297. const auto & hparams = model.hparams;
  298. const int n_embd = hparams.n_embd;
  299. const int n_layer = hparams.n_layer;
  300. const int n_ctx = hparams.n_ctx;
  301. const int n_head = hparams.n_head;
  302. // since we are using ggml-alloc, this buffer only needs enough space to hold the ggml_tensor and ggml_cgraph structs, but not the tensor data
  303. static size_t buf_size = ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead();
  304. static std::vector<uint8_t> buf(buf_size);
  305. struct ggml_init_params params = {
  306. /*.mem_size =*/ buf_size,
  307. /*.mem_buffer =*/ buf.data(),
  308. /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_allocr_alloc_graph()
  309. };
  310. struct ggml_context * ctx0 = ggml_init(params);
  311. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  312. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  313. ggml_allocr_alloc(allocr, embd);
  314. // avoid writing to tensors if we are only measuring the memory usage
  315. if (!ggml_allocr_is_measure(allocr)) {
  316. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  317. }
  318. struct ggml_tensor * position = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  319. ggml_allocr_alloc(allocr, position);
  320. if (!ggml_allocr_is_measure(allocr)) {
  321. for (int i = 0; i < N; ++i) {
  322. ((int32_t *) position->data)[i] = n_past + i;
  323. }
  324. }
  325. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  326. ggml_allocr_alloc(allocr, KQ_scale);
  327. if (!ggml_allocr_is_measure(allocr)) {
  328. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  329. }
  330. // wte + wpe
  331. struct ggml_tensor * inpL =
  332. ggml_add(ctx0,
  333. ggml_get_rows(ctx0, model.wte, embd),
  334. ggml_get_rows(ctx0, model.wpe, position));
  335. for (int il = 0; il < n_layer; ++il) {
  336. struct ggml_tensor * cur;
  337. // norm
  338. {
  339. // [ 768, N]
  340. cur = ggml_norm(ctx0, inpL, hparams.eps);
  341. // cur = ln_1_g*cur + ln_1_b
  342. // [ 768, N]
  343. cur = ggml_add(ctx0,
  344. ggml_mul(ctx0,
  345. ggml_repeat(ctx0, model.layers[il].ln_1_g, cur),
  346. cur),
  347. ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
  348. }
  349. // attn
  350. // [2304, 768] - model.layers[il].c_attn_attn_w
  351. // [2304, 1] - model.layers[il].c_attn_attn_b
  352. // [ 768, N] - cur (in)
  353. // [2304, N] - cur (out)
  354. //
  355. // cur = attn_w*cur + attn_b
  356. // [2304, N]
  357. {
  358. cur = ggml_mul_mat(ctx0,
  359. model.layers[il].c_attn_attn_w,
  360. cur);
  361. cur = ggml_add(ctx0,
  362. ggml_repeat(ctx0, model.layers[il].c_attn_attn_b, cur),
  363. cur);
  364. }
  365. // self-attention
  366. {
  367. struct ggml_tensor * Qcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 0*sizeof(float)*n_embd);
  368. struct ggml_tensor * Kcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 1*sizeof(float)*n_embd);
  369. struct ggml_tensor * Vcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 2*sizeof(float)*n_embd);
  370. // store key and value to memory
  371. if (N >= 1) {
  372. 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));
  373. 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));
  374. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  375. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  376. }
  377. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  378. // [64, N, 12]
  379. struct ggml_tensor * Q =
  380. ggml_permute(ctx0,
  381. ggml_cpy(ctx0,
  382. Qcur,
  383. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  384. 0, 2, 1, 3);
  385. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  386. // [64, n_past + N, 12]
  387. struct ggml_tensor * K =
  388. ggml_permute(ctx0,
  389. ggml_reshape_3d(ctx0,
  390. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  391. n_embd/n_head, n_head, n_past + N),
  392. 0, 2, 1, 3);
  393. // GG: flash attention
  394. //struct ggml_tensor * V =
  395. // ggml_cpy(ctx0,
  396. // ggml_permute(ctx0,
  397. // ggml_reshape_3d(ctx0,
  398. // ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  399. // n_embd/n_head, n_head, n_past + N),
  400. // 1, 2, 0, 3),
  401. // ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_past + N, n_embd/n_head, n_head));
  402. //struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, true);
  403. // K * Q
  404. // [n_past + N, N, 12]
  405. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  406. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  407. // [n_past + N, N, 12]
  408. struct ggml_tensor * KQ_scaled =
  409. ggml_scale(ctx0,
  410. KQ,
  411. KQ_scale);
  412. // KQ_masked = mask_past(KQ_scaled)
  413. // [n_past + N, N, 12]
  414. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  415. // KQ = soft_max(KQ_masked)
  416. // [n_past + N, N, 12]
  417. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  418. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  419. // [n_past + N, 64, 12]
  420. struct ggml_tensor * V_trans =
  421. ggml_cpy(ctx0,
  422. ggml_permute(ctx0,
  423. ggml_reshape_3d(ctx0,
  424. ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  425. n_embd/n_head, n_head, n_past + N),
  426. 1, 2, 0, 3),
  427. ggml_new_tensor_3d(ctx0, model.memory_v->type, n_past + N, n_embd/n_head, n_head));
  428. // KQV = transpose(V) * KQ_soft_max
  429. // [64, N, 12]
  430. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  431. // KQV_merged = KQV.permute(0, 2, 1, 3)
  432. // [64, 12, N]
  433. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  434. // cur = KQV_merged.contiguous().view(n_embd, N)
  435. // [768, N]
  436. cur = ggml_cpy(ctx0,
  437. KQV_merged,
  438. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  439. }
  440. // projection
  441. // [ 768, 768] - model.layers[il].c_attn_proj_w
  442. // [ 768, 1] - model.layers[il].c_attn_proj_b
  443. // [ 768, N] - cur (in)
  444. // [ 768, N] - cur (out)
  445. //
  446. // cur = proj_w*cur + proj_b
  447. // [768, N]
  448. {
  449. cur = ggml_mul_mat(ctx0,
  450. model.layers[il].c_attn_proj_w,
  451. cur);
  452. cur = ggml_add(ctx0,
  453. ggml_repeat(ctx0, model.layers[il].c_attn_proj_b, cur),
  454. cur);
  455. }
  456. // add the input
  457. cur = ggml_add(ctx0, cur, inpL);
  458. struct ggml_tensor * inpFF = cur;
  459. // feed-forward network
  460. {
  461. // norm
  462. {
  463. cur = ggml_norm(ctx0, inpFF, hparams.eps);
  464. // cur = ln_2_g*cur + ln_2_b
  465. // [ 768, N]
  466. cur = ggml_add(ctx0,
  467. ggml_mul(ctx0,
  468. ggml_repeat(ctx0, model.layers[il].ln_2_g, cur),
  469. cur),
  470. ggml_repeat(ctx0, model.layers[il].ln_2_b, cur));
  471. }
  472. // fully connected
  473. // [3072, 768] - model.layers[il].c_mlp_fc_w
  474. // [3072, 1] - model.layers[il].c_mlp_fc_b
  475. // [ 768, N] - cur (in)
  476. // [3072, N] - cur (out)
  477. //
  478. // cur = fc_w*cur + fc_b
  479. // [3072, N]
  480. cur = ggml_mul_mat(ctx0,
  481. model.layers[il].c_mlp_fc_w,
  482. cur);
  483. cur = ggml_add(ctx0,
  484. ggml_repeat(ctx0, model.layers[il].c_mlp_fc_b, cur),
  485. cur);
  486. // GELU activation
  487. // [3072, N]
  488. cur = ggml_gelu(ctx0, cur);
  489. // projection
  490. // [ 768, 3072] - model.layers[il].c_mlp_proj_w
  491. // [ 768, 1] - model.layers[il].c_mlp_proj_b
  492. // [3072, N] - cur (in)
  493. // [ 768, N] - cur (out)
  494. //
  495. // cur = proj_w*cur + proj_b
  496. // [768, N]
  497. cur = ggml_mul_mat(ctx0,
  498. model.layers[il].c_mlp_proj_w,
  499. cur);
  500. cur = ggml_add(ctx0,
  501. ggml_repeat(ctx0, model.layers[il].c_mlp_proj_b, cur),
  502. cur);
  503. }
  504. // input for next layer
  505. inpL = ggml_add(ctx0, cur, inpFF);
  506. }
  507. // norm
  508. {
  509. // [ 768, N]
  510. inpL = ggml_norm(ctx0, inpL, hparams.eps);
  511. // inpL = ln_f_g*inpL + ln_f_b
  512. // [ 768, N]
  513. inpL = ggml_add(ctx0,
  514. ggml_mul(ctx0,
  515. ggml_repeat(ctx0, model.ln_f_g, inpL),
  516. inpL),
  517. ggml_repeat(ctx0, model.ln_f_b, inpL));
  518. }
  519. // inpL = WTE * inpL
  520. // [ 768, 50257] - model.lm_head
  521. // [ 768, N] - inpL
  522. inpL = ggml_mul_mat(ctx0, model.lm_head, inpL);
  523. // logits -> probs
  524. //inpL = ggml_soft_max(ctx0, inpL);
  525. ggml_build_forward_expand(gf, inpL);
  526. ggml_free(ctx0);
  527. return gf;
  528. }
  529. // evaluate the transformer
  530. //
  531. // - model: the model
  532. // - allocr: ggml_allocr to use to allocate the compute buffer
  533. // - n_threads: number of threads to use
  534. // - n_past: the context size so far
  535. // - embd_inp: the embeddings of the tokens in the context
  536. // - embd_w: the predicted logits for the next token
  537. //
  538. bool gpt2_eval(
  539. const gpt2_model & model,
  540. struct ggml_allocr * allocr,
  541. const int n_threads,
  542. const int n_past,
  543. const std::vector<gpt_vocab::id> & embd_inp,
  544. std::vector<float> & embd_w) {
  545. const int N = embd_inp.size();
  546. const auto & hparams = model.hparams;
  547. const int n_vocab = hparams.n_vocab;
  548. // reset the allocator to free all the memory allocated during the previous inference
  549. ggml_allocr_reset(allocr);
  550. struct ggml_cgraph * gf = gpt2_graph(model, allocr, n_past, embd_inp);
  551. // allocate tensors
  552. ggml_allocr_alloc_graph(allocr, gf);
  553. // run the computation
  554. struct ggml_cplan plan = ggml_graph_plan(gf, n_threads);
  555. static std::vector<uint8_t> work_buffer;
  556. work_buffer.resize(plan.work_size);
  557. plan.work_data = work_buffer.data();
  558. ggml_graph_compute(gf, &plan);
  559. //if (n_past%100 == 0) {
  560. // ggml_graph_print (&gf);
  561. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  562. //}
  563. // in this case, the output tensor is the last one in the graph
  564. struct ggml_tensor * inpL = gf->nodes[gf->n_nodes - 1];
  565. //embd_w.resize(n_vocab*N);
  566. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  567. // return result just for the last token
  568. embd_w.resize(n_vocab);
  569. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  570. return true;
  571. }
  572. int main(int argc, char ** argv) {
  573. ggml_time_init();
  574. const int64_t t_main_start_us = ggml_time_us();
  575. gpt_params params;
  576. params.model = "models/gpt-2-117M/ggml-model.bin";
  577. if (gpt_params_parse(argc, argv, params) == false) {
  578. return 1;
  579. }
  580. if (params.seed < 0) {
  581. params.seed = time(NULL);
  582. }
  583. printf("%s: seed = %d\n", __func__, params.seed);
  584. std::mt19937 rng(params.seed);
  585. if (params.prompt.empty()) {
  586. params.prompt = gpt_random_prompt(rng);
  587. }
  588. int64_t t_load_us = 0;
  589. gpt_vocab vocab;
  590. gpt2_model model;
  591. // load the model
  592. {
  593. const int64_t t_start_us = ggml_time_us();
  594. if (!gpt2_model_load(params.model, model, vocab)) {
  595. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  596. return 1;
  597. }
  598. t_load_us = ggml_time_us() - t_start_us;
  599. test_gpt_tokenizer(vocab, params.token_test);
  600. }
  601. // keep this buffer alive while evaluating the model
  602. std::vector<uint8_t> compute_buffer;
  603. struct ggml_allocr * allocr = NULL;
  604. // allocate the compute buffer
  605. {
  606. allocr = ggml_allocr_new_measure(GGML_MEM_ALIGN);
  607. // create the worst case graph for memory usage estimation
  608. int n_tokens = std::min(model.hparams.n_ctx, params.n_batch);
  609. int n_past = model.hparams.n_ctx - n_tokens;
  610. struct ggml_cgraph * gf = gpt2_graph(model, allocr, n_past, std::vector<gpt_vocab::id>(n_tokens, 0));
  611. // compute the required memory
  612. size_t mem_size = ggml_allocr_alloc_graph(allocr, gf) + GGML_MEM_ALIGN;
  613. // recreate the allocator with the required memory
  614. ggml_allocr_free(allocr);
  615. compute_buffer.resize(mem_size);
  616. allocr = ggml_allocr_new(compute_buffer.data(), mem_size, GGML_MEM_ALIGN);
  617. fprintf(stderr, "%s: compute buffer size: %.2f MB\n", __func__, mem_size/1024.0/1024.0);
  618. }
  619. int n_past = 0;
  620. int64_t t_sample_us = 0;
  621. int64_t t_predict_us = 0;
  622. std::vector<float> logits;
  623. // tokenize the prompt
  624. std::vector<gpt_vocab::id> embd_inp = ::gpt_tokenize(vocab, params.prompt);
  625. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  626. printf("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  627. printf("%s: number of tokens in prompt = %zu, first 8 tokens: ", __func__, embd_inp.size());
  628. for (int i = 0; i < std::min(8, (int) embd_inp.size()); i++) {
  629. printf("%d ", embd_inp[i]);
  630. }
  631. printf("\n\n");
  632. // submit the input prompt token-by-token
  633. // this reduces the memory usage during inference, at the cost of a bit of speed at the beginning
  634. std::vector<gpt_vocab::id> embd;
  635. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  636. // predict
  637. if (embd.size() > 0) {
  638. const int64_t t_start_us = ggml_time_us();
  639. if (!gpt2_eval(model, allocr, params.n_threads, n_past, embd, logits)) {
  640. printf("Failed to predict\n");
  641. return 1;
  642. }
  643. t_predict_us += ggml_time_us() - t_start_us;
  644. }
  645. n_past += embd.size();
  646. embd.clear();
  647. if (i >= embd_inp.size()) {
  648. // sample next token
  649. const int top_k = params.top_k;
  650. const float top_p = params.top_p;
  651. const float temp = params.temp;
  652. const int n_vocab = model.hparams.n_vocab;
  653. gpt_vocab::id id = 0;
  654. {
  655. const int64_t t_start_sample_us = ggml_time_us();
  656. id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
  657. t_sample_us += ggml_time_us() - t_start_sample_us;
  658. }
  659. // add it to the context
  660. embd.push_back(id);
  661. } else {
  662. // if here, it means we are still processing the input prompt
  663. for (size_t k = i; k < embd_inp.size(); k++) {
  664. embd.push_back(embd_inp[k]);
  665. if (int32_t(embd.size()) >= params.n_batch) {
  666. break;
  667. }
  668. }
  669. i += embd.size() - 1;
  670. }
  671. // display text
  672. for (auto id : embd) {
  673. printf("%s", vocab.id_to_token[id].c_str());
  674. }
  675. fflush(stdout);
  676. // end of text token
  677. if (embd.back() == 50256) {
  678. break;
  679. }
  680. }
  681. // report timing
  682. {
  683. const int64_t t_main_end_us = ggml_time_us();
  684. printf("\n\n");
  685. printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  686. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  687. 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);
  688. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  689. }
  690. ggml_free(model.ctx);
  691. return 0;
  692. }