main.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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 <cinttypes>
  9. #include <fstream>
  10. #include <iostream>
  11. #include <map>
  12. #include <string>
  13. #include <vector>
  14. #if !defined(_WIN32)
  15. #define DOLLY_INTERACTIVE_PORT
  16. #endif
  17. #if defined(DOLLY_INTERACTIVE_PORT)
  18. #include <arpa/inet.h>
  19. #include <netinet/in.h>
  20. #include <sys/socket.h>
  21. #include <unistd.h>
  22. #endif
  23. #if defined(_MSC_VER)
  24. #pragma warning(disable: 4244 4267) // possible loss of data
  25. #endif
  26. // default hparams (Dolly-V2 3B)
  27. struct dollyv2_hparams {
  28. int32_t n_vocab = 50254; // tokenizer.vocab_size
  29. int32_t n_ctx = 2048; // model.config.max_position_embeddings
  30. int32_t n_embd = 2560; // model.config.hidden_size
  31. int32_t n_head = 32; // model.config.num_attention_heads
  32. int32_t n_layer = 32; // model.config.num_hidden_layers
  33. int32_t n_rot = 20; // rotary_pct[25%] * (n_embd / n_head)
  34. int32_t par_res = 1; // 1 = true, 0 = false
  35. int32_t ftype = GGML_FTYPE_MOSTLY_F16;
  36. float eps = 1e-5f;
  37. };
  38. const std::string INSTRUCTION_KEY = "### Instruction:";
  39. const std::string RESPONSE_KEY = "### Response:";
  40. const std::string END_KEY = "### End";
  41. const std::string INTRO_BLURB = "Below is an instruction that describes a task. Write a response that appropriately completes the request.";
  42. // dollyv2 prompt format
  43. std::string prompt_for_generation(const std::string& instruction) {
  44. return INTRO_BLURB + "\n\n" + INSTRUCTION_KEY + "\n" + instruction + "\n\n" + RESPONSE_KEY + "\n";
  45. }
  46. struct dollyv2_layer {
  47. // pre normalization
  48. struct ggml_tensor * ln_1_g;
  49. struct ggml_tensor * ln_1_b;
  50. // attention
  51. struct ggml_tensor * c_attn_attn_w;
  52. struct ggml_tensor * c_attn_attn_b;
  53. struct ggml_tensor * c_attn_proj_w;
  54. struct ggml_tensor * c_attn_proj_b;
  55. // post normalization
  56. struct ggml_tensor * ln_2_g;
  57. struct ggml_tensor * ln_2_b;
  58. // ff
  59. struct ggml_tensor * c_mlp_fc_w;
  60. struct ggml_tensor * c_mlp_fc_b;
  61. struct ggml_tensor * c_mlp_proj_w;
  62. struct ggml_tensor * c_mlp_proj_b;
  63. };
  64. struct dollyv2_model {
  65. dollyv2_hparams hparams;
  66. // normalization
  67. struct ggml_tensor * ln_f_g;
  68. struct ggml_tensor * ln_f_b;
  69. struct ggml_tensor * wte; // position embedding
  70. struct ggml_tensor * lmh_g; // language model head
  71. //struct ggml_tensor * lmh_b; // language model bias
  72. std::vector<dollyv2_layer> layers;
  73. // key + value memory
  74. struct ggml_tensor * memory_k;
  75. struct ggml_tensor * memory_v;
  76. //
  77. struct ggml_context * ctx;
  78. std::map<std::string, struct ggml_tensor *> tensors;
  79. };
  80. // load the model's weights from a file
  81. bool dollyv2_model_load(const std::string & fname, dollyv2_model & model, gpt_vocab & vocab) {
  82. printf("%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  83. auto fin = std::ifstream(fname, std::ios::binary);
  84. if (!fin) {
  85. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  86. return false;
  87. }
  88. // verify magic
  89. {
  90. uint32_t magic;
  91. fin.read((char *) &magic, sizeof(magic));
  92. if (magic != GGML_FILE_MAGIC) {
  93. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  94. return false;
  95. }
  96. }
  97. // load hparams
  98. {
  99. auto & hparams = model.hparams;
  100. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  101. fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  102. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  103. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  104. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  105. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  106. fin.read((char *) &hparams.par_res, sizeof(hparams.par_res));
  107. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  108. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  109. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  110. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  111. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  112. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  113. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  114. printf("%s: n_rot = %d\n", __func__, hparams.n_rot);
  115. printf("%s: par_res = %d\n", __func__, hparams.par_res);
  116. printf("%s: ftype = %d\n", __func__, hparams.ftype);
  117. printf("%s: qntvr = %d\n", __func__, qntvr);
  118. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  119. }
  120. // load vocab
  121. {
  122. const int32_t n_vocab = model.hparams.n_vocab;
  123. std::string word;
  124. std::vector<char> buf(128);
  125. for (int i = 0; i < n_vocab; i++) {
  126. uint32_t len;
  127. fin.read((char *) &len, sizeof(len));
  128. buf.resize(len);
  129. fin.read((char *) buf.data(), len);
  130. word.assign(buf.data(), len);
  131. vocab.token_to_id[word] = i;
  132. vocab.id_to_token[i] = word;
  133. }
  134. vocab.add_special_token("### End");
  135. vocab.add_special_token("### Instruction:");
  136. vocab.add_special_token("### Response:");
  137. }
  138. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  139. // in order to save memory and also to speed up the computation
  140. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
  141. if (wtype == GGML_TYPE_COUNT) {
  142. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
  143. __func__, fname.c_str(), model.hparams.ftype);
  144. return false;
  145. }
  146. auto & ctx = model.ctx;
  147. size_t ctx_size = 0;
  148. {
  149. const auto & hparams = model.hparams;
  150. const int n_embd = hparams.n_embd;
  151. const int n_layer = hparams.n_layer;
  152. const int n_ctx = hparams.n_ctx;
  153. const int n_vocab = hparams.n_vocab;
  154. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_g
  155. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_b
  156. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // wte
  157. ctx_size += n_embd*n_vocab*ggml_type_sizef(wtype); // lmh_g
  158. //ctx_size += n_vocab*ggml_type_sizef(GGML_TYPE_F32); // lmh_b
  159. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_g
  160. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_b
  161. ctx_size += n_layer*(3*n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_attn_w
  162. ctx_size += n_layer*( 3*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_attn_b
  163. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_proj_w
  164. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_proj_b
  165. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_g
  166. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_b
  167. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_fc_w
  168. ctx_size += n_layer*( 4*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_fc_b
  169. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_proj_w
  170. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_proj_b
  171. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_k
  172. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_v
  173. ctx_size += (6 + 16*n_layer)*512; // object overhead
  174. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  175. }
  176. // create the ggml context
  177. {
  178. struct ggml_init_params params = {
  179. /*.mem_size =*/ ctx_size,
  180. /*.mem_buffer =*/ NULL,
  181. /*.no_alloc =*/ false,
  182. };
  183. model.ctx = ggml_init(params);
  184. if (!model.ctx) {
  185. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  186. return false;
  187. }
  188. }
  189. // prepare memory for the weights
  190. {
  191. const auto & hparams = model.hparams;
  192. const int n_embd = hparams.n_embd;
  193. const int n_layer = hparams.n_layer;
  194. const int n_vocab = hparams.n_vocab;
  195. model.layers.resize(n_layer);
  196. model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  197. model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  198. model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  199. model.lmh_g = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  200. //model.lmh_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_vocab);
  201. // map by name
  202. model.tensors["gpt_neox.embed_in.weight"] = model.wte;
  203. model.tensors["gpt_neox.final_layer_norm.weight"] = model.ln_f_g;
  204. model.tensors["gpt_neox.final_layer_norm.bias"] = model.ln_f_b;
  205. model.tensors["embed_out.weight"] = model.lmh_g;
  206. //model.tensors["lm_head.bias"] = model.lmh_b;
  207. for (int i = 0; i < n_layer; ++i) {
  208. auto & layer = model.layers[i];
  209. layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  210. layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  211. layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 3*n_embd);
  212. layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_embd);
  213. layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  214. layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  215. layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  216. layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  217. layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd);
  218. layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
  219. layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
  220. layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  221. // map by name
  222. // unmapped: attention.rotary_emb, mlp.act
  223. model.tensors["gpt_neox.layers." + std::to_string(i) + ".input_layernorm.weight"] = layer.ln_1_g;
  224. model.tensors["gpt_neox.layers." + std::to_string(i) + ".input_layernorm.bias"] = layer.ln_1_b;
  225. model.tensors["gpt_neox.layers." + std::to_string(i) + ".attention.query_key_value.weight"] = layer.c_attn_attn_w;
  226. model.tensors["gpt_neox.layers." + std::to_string(i) + ".attention.query_key_value.bias"] = layer.c_attn_attn_b;
  227. model.tensors["gpt_neox.layers." + std::to_string(i) + ".attention.dense.weight"] = layer.c_attn_proj_w;
  228. model.tensors["gpt_neox.layers." + std::to_string(i) + ".attention.dense.bias"] = layer.c_attn_proj_b;
  229. model.tensors["gpt_neox.layers." + std::to_string(i) + ".post_attention_layernorm.weight"] = layer.ln_2_g;
  230. model.tensors["gpt_neox.layers." + std::to_string(i) + ".post_attention_layernorm.bias"] = layer.ln_2_b;
  231. model.tensors["gpt_neox.layers." + std::to_string(i) + ".mlp.dense_h_to_4h.weight"] = layer.c_mlp_fc_w;
  232. model.tensors["gpt_neox.layers." + std::to_string(i) + ".mlp.dense_h_to_4h.bias"] = layer.c_mlp_fc_b;
  233. model.tensors["gpt_neox.layers." + std::to_string(i) + ".mlp.dense_4h_to_h.weight"] = layer.c_mlp_proj_w;
  234. model.tensors["gpt_neox.layers." + std::to_string(i) + ".mlp.dense_4h_to_h.bias"] = layer.c_mlp_proj_b;
  235. }
  236. }
  237. // key + value memory
  238. {
  239. const auto & hparams = model.hparams;
  240. const int n_embd = hparams.n_embd;
  241. const int n_layer = hparams.n_layer;
  242. const int n_ctx = hparams.n_ctx;
  243. const int64_t n_mem = n_layer*n_ctx;
  244. const int64_t n_elements = n_embd*n_mem;
  245. model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  246. model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  247. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  248. printf("%s: memory_size = %8.2f MB, n_mem = %" PRId64 "\n", __func__, memory_size/1024.0/1024.0, n_mem);
  249. }
  250. // load weights
  251. {
  252. int n_tensors = 0;
  253. size_t total_size = 0;
  254. printf("%s: ", __func__);
  255. while (true) {
  256. int32_t n_dims;
  257. int32_t length;
  258. int32_t ttype;
  259. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  260. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  261. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  262. if (fin.eof()) {
  263. break;
  264. }
  265. int32_t nelements = 1;
  266. int32_t ne[2] = { 1, 1 };
  267. for (int i = 0; i < n_dims; ++i) {
  268. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  269. nelements *= ne[i];
  270. }
  271. std::string name(length, 0);
  272. fin.read(&name[0], length);
  273. if (model.tensors.find(name) == model.tensors.end()) {
  274. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  275. return false;
  276. }
  277. auto tensor = model.tensors[name];
  278. if (ggml_nelements(tensor) != nelements) {
  279. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  280. return false;
  281. }
  282. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  283. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%5d, %5d], expected [%5d, %5d]\n",
  284. __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
  285. return false;
  286. }
  287. // for debugging
  288. if (0) {
  289. 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));
  290. }
  291. const size_t bpe = ggml_type_size(ggml_type(ttype));
  292. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  293. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  294. __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe);
  295. return false;
  296. }
  297. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  298. total_size += ggml_nbytes(tensor);
  299. if (++n_tensors % 8 == 0) {
  300. printf(".");
  301. fflush(stdout);
  302. }
  303. }
  304. printf(" done\n");
  305. printf("%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
  306. }
  307. fin.close();
  308. return true;
  309. }
  310. // feed-forward network
  311. ggml_tensor * gpt_neox_ff(
  312. const dollyv2_layer & layer,
  313. ggml_context * ctx0,
  314. ggml_tensor * inp,
  315. float eps) {
  316. ggml_tensor * cur = ggml_norm(ctx0, inp, eps);
  317. cur = ggml_add(ctx0,
  318. ggml_mul(ctx0,
  319. ggml_repeat(ctx0, layer.ln_2_g, cur),
  320. cur),
  321. ggml_repeat(ctx0, layer.ln_2_b, cur));
  322. cur = ggml_mul_mat(ctx0,
  323. layer.c_mlp_fc_w,
  324. cur);
  325. cur = ggml_add(ctx0,
  326. ggml_repeat(ctx0, layer.c_mlp_fc_b, cur),
  327. cur);
  328. // GELU activation
  329. cur = ggml_gelu(ctx0, cur);
  330. // projection
  331. // cur = proj_w*cur + proj_b
  332. cur = ggml_mul_mat(ctx0,
  333. layer.c_mlp_proj_w,
  334. cur);
  335. cur = ggml_add(ctx0,
  336. ggml_repeat(ctx0, layer.c_mlp_proj_b, cur),
  337. cur);
  338. return cur;
  339. }
  340. // evaluate the transformer
  341. //
  342. // - model: the model
  343. // - n_threads: number of threads to use
  344. // - n_past: the context size so far
  345. // - embd_inp: the embeddings of the tokens in the context
  346. // - embd_w: the predicted logits for the next token
  347. //
  348. bool dollyv2_eval(
  349. const dollyv2_model & model,
  350. const int n_threads,
  351. const int n_past,
  352. const std::vector<gpt_vocab::id> & embd_inp,
  353. std::vector<float> & embd_w,
  354. size_t & mem_per_token) {
  355. const int N = embd_inp.size();
  356. const auto & hparams = model.hparams;
  357. const int n_embd = hparams.n_embd;
  358. const int n_layer = hparams.n_layer;
  359. const int n_ctx = hparams.n_ctx;
  360. const int n_head = hparams.n_head;
  361. const int n_vocab = hparams.n_vocab;
  362. const int n_rot = hparams.n_rot;
  363. static size_t buf_size = 256u*1024*1024;
  364. static void * buf = malloc(buf_size);
  365. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  366. const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
  367. //printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  368. // reallocate
  369. buf_size = buf_size_new;
  370. buf = realloc(buf, buf_size);
  371. if (buf == nullptr) {
  372. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  373. return false;
  374. }
  375. }
  376. struct ggml_init_params params = {
  377. /*.mem_size =*/ buf_size,
  378. /*.mem_buffer =*/ buf,
  379. /*.no_alloc =*/ false,
  380. };
  381. struct ggml_context * ctx0 = ggml_init(params);
  382. struct ggml_cgraph gf = { };
  383. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  384. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  385. // wte
  386. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.wte, embd);
  387. for (int il = 0; il < n_layer; ++il) {
  388. struct ggml_tensor * cur;
  389. // self-attention
  390. {
  391. {
  392. cur = ggml_norm(ctx0, inpL, hparams.eps);
  393. cur = ggml_add(ctx0,
  394. ggml_mul(ctx0,
  395. ggml_repeat(ctx0, model.layers[il].ln_1_g, cur),
  396. cur),
  397. ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
  398. }
  399. // compute QKV
  400. {
  401. cur = ggml_mul_mat(ctx0,
  402. model.layers[il].c_attn_attn_w,
  403. cur);
  404. cur = ggml_add(ctx0,
  405. ggml_repeat(ctx0, model.layers[il].c_attn_attn_b, cur),
  406. cur);
  407. }
  408. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd/n_head, n_head, N, cur->nb[1]/n_head, cur->nb[1], 0*sizeof(float)*n_embd/n_head));
  409. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd/n_head, n_head, N, cur->nb[1]/n_head, cur->nb[1], 1*sizeof(float)*n_embd/n_head));
  410. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_3d(ctx0, cur, n_embd/n_head, n_head, N, cur->nb[1]/n_head, cur->nb[1], 2*sizeof(float)*n_embd/n_head));
  411. // using mode = 2 for GPT-NeoX mode
  412. Qcur = ggml_rope_inplace(ctx0, Qcur, n_past, n_rot, 2, 0);
  413. Kcur = ggml_rope_inplace(ctx0, Kcur, n_past, n_rot, 2, 0);
  414. // store key and value to memory
  415. {
  416. Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd, N));
  417. 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));
  418. struct ggml_tensor * v = ggml_view_2d(ctx0, model.memory_v, N, n_embd,
  419. ( n_ctx)*ggml_element_size(model.memory_v),
  420. (il*n_ctx)*ggml_element_size(model.memory_v)*n_embd + n_past*ggml_element_size(model.memory_v));
  421. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  422. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  423. }
  424. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  425. struct ggml_tensor * Q =
  426. ggml_permute(ctx0,
  427. Qcur,
  428. 0, 2, 1, 3);
  429. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  430. struct ggml_tensor * K =
  431. ggml_permute(ctx0,
  432. ggml_reshape_3d(ctx0,
  433. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  434. n_embd/n_head, n_head, n_past + N),
  435. 0, 2, 1, 3);
  436. // K * Q
  437. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  438. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  439. struct ggml_tensor * KQ_scaled =
  440. ggml_scale_inplace(ctx0,
  441. KQ,
  442. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  443. );
  444. // KQ_masked = mask_past(KQ_scaled)
  445. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  446. // KQ = soft_max(KQ_masked)
  447. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  448. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  449. struct ggml_tensor * V =
  450. ggml_view_3d(ctx0, model.memory_v,
  451. n_past + N, n_embd/n_head, n_head,
  452. n_ctx*ggml_element_size(model.memory_v),
  453. n_ctx*ggml_element_size(model.memory_v)*n_embd/n_head,
  454. il*n_ctx*ggml_element_size(model.memory_v)*n_embd);
  455. // KQV = transpose(V) * KQ_soft_max
  456. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  457. // KQV_merged = KQV.permute(0, 2, 1, 3)
  458. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  459. // cur = KQV_merged.contiguous().view(n_embd, N)
  460. cur = ggml_cpy(ctx0,
  461. KQV_merged,
  462. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  463. // projection
  464. {
  465. cur = ggml_mul_mat(ctx0,
  466. model.layers[il].c_attn_proj_w,
  467. cur);
  468. cur = ggml_add(ctx0, ggml_repeat(ctx0, model.layers[il].c_attn_proj_b, cur), cur);
  469. }
  470. }
  471. if (hparams.par_res == 0) {
  472. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpL);
  473. cur = gpt_neox_ff(model.layers[il], ctx0, inpFF, hparams.eps);
  474. // input for next layer
  475. inpL = ggml_add(ctx0, cur, inpFF);
  476. } else {
  477. struct ggml_tensor * inpFF = cur;
  478. // this is independent of the self-attention result, so it could be done in parallel to the self-attention
  479. // note here we pass inpL instead of cur
  480. cur = gpt_neox_ff(model.layers[il], ctx0, inpL, hparams.eps);
  481. // layer input + FF
  482. cur = ggml_add(ctx0, cur, inpFF);
  483. // input for next layer
  484. inpL = ggml_add(ctx0, cur, inpL);
  485. }
  486. }
  487. // norm
  488. {
  489. inpL = ggml_norm(ctx0, inpL, hparams.eps);
  490. // inpL = ln_f_g*inpL + ln_f_b
  491. inpL = ggml_add(ctx0,
  492. ggml_mul(ctx0,
  493. ggml_repeat(ctx0, model.ln_f_g, inpL),
  494. inpL),
  495. ggml_repeat(ctx0, model.ln_f_b, inpL));
  496. }
  497. // lm_head
  498. {
  499. inpL = ggml_mul_mat(ctx0, model.lmh_g, inpL);
  500. //inpL = ggml_add(ctx0,
  501. // ggml_repeat(ctx0, model.lmh_b, inpL),
  502. // inpL);
  503. }
  504. // logits -> probs
  505. //inpL = ggml_soft_max_inplace(ctx0, inpL);
  506. // run the computation
  507. ggml_build_forward_expand(&gf, inpL);
  508. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  509. //if (n_past%100 == 0) {
  510. // ggml_graph_print (&gf);
  511. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  512. //}
  513. //embd_w.resize(n_vocab*N);
  514. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  515. // return result for just the last token
  516. embd_w.resize(n_vocab);
  517. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  518. if (mem_per_token == 0) {
  519. mem_per_token = ggml_used_mem(ctx0)/N;
  520. }
  521. //printf("used_mem = %zu\n", ggml_used_mem(ctx0));
  522. ggml_free(ctx0);
  523. return true;
  524. }
  525. std::string execute_prompt(
  526. const dollyv2_model &model,
  527. gpt_vocab &vocab,
  528. const std::string &prompt,
  529. gpt_params &params,
  530. std::mt19937 &rng,
  531. int64_t t_load_us,
  532. int64_t t_sample_us,
  533. int64_t t_predict_us,
  534. size_t mem_per_token,
  535. int n_past,
  536. bool stream_response_to_cout = false) {
  537. std::string output = "";
  538. std::vector<float> logits;
  539. // tokenize the prompt
  540. std::vector<gpt_vocab::id> embd_inp = ::gpt_tokenize(vocab, prompt);
  541. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int)embd_inp.size());
  542. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  543. for (size_t i = 0; i < embd_inp.size(); i++) {
  544. printf("%s: token[%zu] = %6d, %s\n", __func__, i, embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
  545. }
  546. printf("\n");
  547. std::vector<gpt_vocab::id> embd;
  548. dollyv2_eval(model, params.n_threads, 0, {0, 1, 2, 3}, logits, mem_per_token);
  549. const int32_t end_token = vocab.token_to_id["### End"];
  550. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  551. // predict
  552. if (embd.size() > 0) {
  553. const int64_t t_start_us = ggml_time_us();
  554. if (!dollyv2_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  555. printf("Failed to predict\n");
  556. return output;
  557. }
  558. t_predict_us += ggml_time_us() - t_start_us;
  559. }
  560. n_past += embd.size();
  561. embd.clear();
  562. if (i >= embd_inp.size()) {
  563. // sample next token
  564. const int top_k = params.top_k;
  565. const float top_p = params.top_p;
  566. const float temp = params.temp;
  567. const int n_vocab = model.hparams.n_vocab;
  568. gpt_vocab::id id = 0;
  569. {
  570. const int64_t t_start_sample_us = ggml_time_us();
  571. id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
  572. t_sample_us += ggml_time_us() - t_start_sample_us;
  573. }
  574. // add it to the context
  575. embd.push_back(id);
  576. } else {
  577. // if here, it means we are still processing the input prompt
  578. for (size_t k = i; k < embd_inp.size(); k++) {
  579. embd.push_back(embd_inp[k]);
  580. if (int32_t(embd.size()) > params.n_batch) {
  581. break;
  582. }
  583. }
  584. i += embd.size() - 1;
  585. }
  586. // display text
  587. for (auto id : embd) {
  588. output += vocab.id_to_token[id];
  589. if (stream_response_to_cout) {
  590. printf("%s", vocab.id_to_token[id].c_str());
  591. }
  592. }
  593. if (stream_response_to_cout) {
  594. fflush(stdout);
  595. }
  596. // end of text token
  597. if (embd.back() == 0 || (end_token > 0 && embd.back() == end_token)) {
  598. return output;
  599. }
  600. }
  601. return output;
  602. }
  603. #if defined(DOLLY_INTERACTIVE_PORT)
  604. int setup_port(const int port) {
  605. int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  606. if (sockfd < 0) {
  607. fprintf(stderr, "%s: Failed to create new socket\n", __func__);
  608. return -1;
  609. }
  610. sockaddr_in servaddr;
  611. std::memset(&servaddr, 0, sizeof(servaddr));
  612. servaddr.sin_family = AF_INET;
  613. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  614. servaddr.sin_port = htons(port);
  615. if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
  616. fprintf(stderr, "%s: Failed to bind to port %i\n", __func__, port);
  617. return -1;
  618. }
  619. if (listen(sockfd, 10) < 0) {
  620. fprintf(stderr, "%s: Failed to listen to socket on port %i\n", __func__, port);
  621. return -1;
  622. }
  623. return sockfd;
  624. }
  625. std::string read_from_port(int sockfd, int clientfd) {
  626. if (clientfd < 0) {
  627. fprintf(stderr, "%s: Failed to accept new connection\n", __func__);
  628. return "";
  629. }
  630. char buffer[4096];
  631. std::memset(buffer, 0, sizeof(buffer));
  632. if (read(clientfd, buffer, sizeof(buffer)) < 0) {
  633. fprintf(stderr, "%s: Failed to read from client\n", __func__);
  634. } else {
  635. std::cout << "Received: " << buffer;
  636. return std::string(buffer);
  637. }
  638. return std::string("");
  639. }
  640. #endif
  641. int main(int argc, char ** argv) {
  642. ggml_time_init();
  643. const int64_t t_main_start_us = ggml_time_us();
  644. gpt_params params;
  645. params.model = "models/dolly-v2-3b/ggml-model-f16.bin";
  646. if (gpt_params_parse(argc, argv, params) == false) {
  647. return 1;
  648. }
  649. if (params.seed < 0) {
  650. params.seed = time(NULL);
  651. }
  652. printf("%s: seed = %d\n", __func__, params.seed);
  653. std::mt19937 rng(params.seed);
  654. int64_t t_load_us = 0;
  655. int64_t t_sample_us = 0;
  656. int64_t t_predict_us = 0;
  657. // determine the required inference memory per token:
  658. size_t mem_per_token = 0;
  659. int n_past = 0;
  660. gpt_vocab vocab;
  661. dollyv2_model model;
  662. // load the model
  663. {
  664. const int64_t t_start_us = ggml_time_us();
  665. if (!dollyv2_model_load(params.model, model, vocab)) {
  666. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  667. return 1;
  668. }
  669. t_load_us = ggml_time_us() - t_start_us;
  670. test_gpt_tokenizer(vocab, params.token_test);
  671. }
  672. #if defined(DOLLY_INTERACTIVE_PORT)
  673. int sockfd = -1;
  674. if (params.interactive_port != -1) {
  675. sockfd = setup_port(params.interactive_port);
  676. if (sockfd == -1) {
  677. return 1;
  678. }
  679. fprintf(stdout, "Model is ready on port %i\n", params.interactive_port);
  680. fflush(stdout);
  681. }
  682. #endif
  683. if (params.interactive || params.interactive_port != -1) {
  684. while (true) {
  685. std::string prompt_input;
  686. #if defined(DOLLY_INTERACTIVE_PORT)
  687. int clientfd = -1;
  688. if (params.interactive_port != -1) {
  689. sockaddr_in clientaddr;
  690. socklen_t clientaddrlen = sizeof(clientaddr);
  691. clientfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientaddrlen);
  692. prompt_input = read_from_port(sockfd, clientfd);
  693. } else
  694. #endif
  695. {
  696. printf("Please enter your quesiton:\n>");
  697. fflush(stdout);
  698. std::getline(std::cin, prompt_input);
  699. }
  700. if (strcmp(prompt_input.c_str(), "exit") == 0) {
  701. break;
  702. }
  703. const std::string prompt = prompt_for_generation(prompt_input);
  704. // call the model
  705. const std::string response = execute_prompt(model, vocab, prompt, params, rng, t_load_us, t_sample_us, t_predict_us, mem_per_token, n_past, true);
  706. #if defined(DOLLY_INTERACTIVE_PORT)
  707. if (params.interactive_port != -1) {
  708. if (write(clientfd, response.c_str(), response.size()) < 0) {
  709. fprintf(stderr, "%s: Failed to write answer '%s' to client\n", __func__, response.c_str());
  710. }
  711. if (close(clientfd) < 0) {
  712. fprintf(stderr, "%s: Failed to close client socket\n", __func__);
  713. }
  714. } else
  715. #endif
  716. {
  717. printf("%s\n\n", response.c_str());
  718. }
  719. fflush(stdout);
  720. }
  721. } else {
  722. if (params.prompt.empty()) {
  723. params.prompt = gpt_random_prompt(rng);
  724. }
  725. const std::string prompt = prompt_for_generation(params.prompt);
  726. execute_prompt(model, vocab, prompt, params, rng, t_load_us, t_sample_us, t_predict_us, mem_per_token, n_past, true);
  727. }
  728. // report timing
  729. {
  730. const int64_t t_main_end_us = ggml_time_us();
  731. printf("\n\n");
  732. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  733. printf("%s: load time = %8.2f ms\n", __func__, t_load_us / 1000.0f);
  734. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us / 1000.0f);
  735. 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);
  736. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us) / 1000.0f);
  737. }
  738. ggml_free(model.ctx);
  739. #if defined(DOLLY_INTERACTIVE_PORT)
  740. if (params.interactive_port != -1 && close(sockfd) < 0) {
  741. fprintf(stderr, "%s: Failed to close server socket\n", __func__);
  742. }
  743. #endif
  744. return 0;
  745. }