main.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. #include "ggml/ggml.h"
  2. #include "common-ggml.h"
  3. #include "common.h"
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cinttypes>
  7. #include <cstddef>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <map>
  13. #include <stdint.h>
  14. #include <string>
  15. #include <unordered_map>
  16. #include <utility>
  17. #include <vector>
  18. #if defined(_WIN32)
  19. #define NOMINMAX
  20. #include <Windows.h>
  21. bool is_stdin_terminal() {
  22. auto in = GetStdHandle(STD_INPUT_HANDLE);
  23. return GetFileType(in) == FILE_TYPE_CHAR;
  24. }
  25. #else
  26. #include <unistd.h>
  27. bool is_stdin_terminal() {
  28. return isatty(STDIN_FILENO);
  29. }
  30. #endif
  31. #if defined(_MSC_VER)
  32. #pragma warning(disable: 4244 4267) // possible loss of data
  33. #endif
  34. using piece_t = std::pair<std::size_t, float>;
  35. using piece_map_t = std::unordered_map<std::string, piece_t>;
  36. struct replit_tokenizer {
  37. gpt_vocab raw_vocab;
  38. piece_map_t piece_map;
  39. std::vector<std::string> vocab;
  40. };
  41. std::pair<std::vector<std::size_t>, float> encode_word(const std::string & word, const piece_map_t & model) {
  42. std::vector<int> best_segmentations_starts(word.length() + 1, -1);
  43. best_segmentations_starts[0] = 0;
  44. std::vector<float> best_segmentations_scores(word.length() + 1, -std::numeric_limits<float>::infinity());
  45. best_segmentations_scores[0] = 1.0;
  46. for (size_t start_idx = 0; start_idx < word.length(); ++start_idx) {
  47. float best_score_at_start = best_segmentations_scores[start_idx];
  48. for (size_t end_idx = start_idx + 1; end_idx <= word.length(); ++end_idx) {
  49. std::string token = word.substr(start_idx, end_idx - start_idx);
  50. if (model.count(token) && best_score_at_start != -std::numeric_limits<float>::infinity()) {
  51. float token_score = model.at(token).second;
  52. float score = token_score + best_score_at_start;
  53. if (best_segmentations_scores[end_idx] == -std::numeric_limits<float>::infinity() ||
  54. best_segmentations_scores[end_idx] > score) {
  55. best_segmentations_starts[end_idx] = start_idx;
  56. best_segmentations_scores[end_idx] = score;
  57. }
  58. }
  59. }
  60. }
  61. if (best_segmentations_scores.back() == -std::numeric_limits<float>::infinity()) {
  62. return std::make_pair(std::vector<std::size_t>{0}, 0.0f);
  63. }
  64. float score = best_segmentations_scores.back();
  65. int start = best_segmentations_starts.back();
  66. int end = word.length();
  67. std::vector<std::size_t> tokens;
  68. while (start != 0) {
  69. const auto token_id = model.at(word.substr(start, end - start)).first;
  70. tokens.insert(tokens.begin(), token_id);
  71. int next_start = best_segmentations_starts[start];
  72. end = start;
  73. start = next_start;
  74. }
  75. const auto token_id = model.at(word.substr(start, end - start)).first;
  76. tokens.insert(tokens.begin(), token_id);
  77. return std::make_pair(tokens, score);
  78. }
  79. bool replit_tokenizer_load(replit_tokenizer & tokenizer, std::istream & fin, int max_vocab_size) {
  80. std::string word;
  81. std::vector<char> buf(128);
  82. for (int i = 0; i < max_vocab_size; i++) {
  83. uint32_t len;
  84. fin.read((char *)&len, sizeof(len));
  85. buf.resize(len);
  86. fin.read((char *)buf.data(), len);
  87. word.assign(buf.data(), len);
  88. float score;
  89. fin.read((char *)&score, sizeof(score));
  90. tokenizer.piece_map[word] = std::make_pair(i, -score);
  91. tokenizer.raw_vocab.id_to_token[i] = word;
  92. }
  93. return true;
  94. }
  95. std::string replace_all(const std::string & str, // where to work
  96. const std::string & find, // substitute 'find'
  97. const std::string & replace // by 'replace'
  98. ) {
  99. using namespace std;
  100. string result;
  101. size_t find_len = find.size();
  102. size_t pos, from = 0;
  103. while (string::npos != (pos = str.find(find, from))) {
  104. result.append(str, from, pos - from);
  105. result.append(replace);
  106. from = pos + find_len;
  107. }
  108. result.append(str, from, string::npos);
  109. return result;
  110. }
  111. std::string ws_symbol = "\342\226\201";
  112. std::vector<std::size_t> replit_tokenizer_tokenize(replit_tokenizer & tokenizer, const std::string & text) {
  113. std::vector<std::size_t> tokens;
  114. auto normalized_text = replace_all(text, " ", ws_symbol);
  115. auto tokenized = encode_word(normalized_text, tokenizer.piece_map);
  116. return tokenized.first;
  117. }
  118. std::string replit_tokenizer_detokenize(replit_tokenizer & tokenizer, const std::vector<std::size_t> & tokens) {
  119. std::string text;
  120. for (auto token : tokens) {
  121. text += tokenizer.raw_vocab.id_to_token[token];
  122. }
  123. auto denormalized_text = replace_all(text, ws_symbol, " ");
  124. return denormalized_text;
  125. }
  126. // no defaults for now
  127. struct replit_hparams {
  128. int32_t d_model = 0;
  129. int32_t max_seq_len = 0;
  130. int32_t n_heads = 0;
  131. int32_t n_layers = 0;
  132. int32_t n_vocab = 0;
  133. int32_t ftype = 0;
  134. };
  135. struct replit_layer {
  136. // pre normalization
  137. struct ggml_tensor * norm_1_weight;
  138. // attention
  139. struct ggml_tensor * c_attn_wqkv_weight;
  140. struct ggml_tensor * c_attn_out_proj_weight;
  141. // post normalization
  142. struct ggml_tensor * norm_2_weight;
  143. // ff
  144. struct ggml_tensor * ffn_up_proj;
  145. struct ggml_tensor * ffn_down_proj;
  146. };
  147. struct replit_model {
  148. replit_hparams hparams;
  149. struct ggml_tensor * wte_weight; // position embedding
  150. struct ggml_tensor * norm_f_weight; // language model head
  151. std::vector<replit_layer> layers;
  152. // key + value memory
  153. struct ggml_tensor * memory_k;
  154. struct ggml_tensor * memory_v;
  155. struct ggml_context * ctx;
  156. std::map<std::string, struct ggml_tensor *> tensors;
  157. };
  158. // load the model's weights from a file
  159. bool replit_model_load(const std::string & fname, replit_model & model, replit_tokenizer & vocab) {
  160. printf("%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  161. auto fin = std::ifstream(fname, std::ios::binary);
  162. if (!fin) {
  163. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  164. return false;
  165. }
  166. // verify magic
  167. {
  168. uint32_t magic;
  169. fin.read((char *)&magic, sizeof(magic));
  170. if (magic != GGML_FILE_MAGIC) {
  171. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  172. return false;
  173. }
  174. }
  175. // load hparams
  176. {
  177. auto & hparams = model.hparams;
  178. fin.read((char *)&hparams.d_model, sizeof(hparams.d_model));
  179. fin.read((char *)&hparams.max_seq_len, sizeof(hparams.max_seq_len));
  180. fin.read((char *)&hparams.n_heads, sizeof(hparams.n_heads));
  181. fin.read((char *)&hparams.n_layers, sizeof(hparams.n_layers));
  182. fin.read((char *)&hparams.n_vocab, sizeof(hparams.n_vocab));
  183. fin.read((char *)&hparams.ftype, sizeof(hparams.ftype));
  184. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  185. printf("%s: d_model = %d\n", __func__, hparams.d_model);
  186. printf("%s: max_seq_len = %d\n", __func__, hparams.max_seq_len);
  187. printf("%s: n_heads = %d\n", __func__, hparams.n_heads);
  188. printf("%s: n_layers = %d\n", __func__, hparams.n_layers);
  189. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  190. printf("%s: ftype = %d\n", __func__, hparams.ftype);
  191. printf("%s: qntvr = %d\n", __func__, qntvr);
  192. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  193. }
  194. // load vocab
  195. replit_tokenizer_load(vocab, fin, model.hparams.n_vocab);
  196. // for the big tensors, we have the option to store the data in 16-bit
  197. // floats or quantized in order to save memory and also to speed up the
  198. // computation
  199. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype)(model.hparams.ftype));
  200. if (wtype == GGML_TYPE_COUNT) {
  201. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n", __func__, fname.c_str(),
  202. model.hparams.ftype);
  203. return false;
  204. }
  205. auto & ctx = model.ctx;
  206. size_t ctx_size = 0;
  207. {
  208. const auto & hparams = model.hparams;
  209. const int n_embd = hparams.d_model;
  210. const int n_layer = hparams.n_layers;
  211. const int n_ctx = hparams.max_seq_len;
  212. const int n_vocab = hparams.n_vocab;
  213. ctx_size += n_embd * n_vocab * ggml_type_sizef(wtype); // wte_weight
  214. ctx_size += n_embd * ggml_type_sizef(GGML_TYPE_F32); // ln_f_weight
  215. ctx_size += n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ln_1_weight
  216. ctx_size += n_layer * (3 * n_embd * n_embd * ggml_type_sizef(wtype)); // attn_Wqkv_weight
  217. ctx_size += n_layer * (n_embd * n_embd * ggml_type_sizef(wtype)); // attn_out_proj_weight
  218. ctx_size += n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ln_2_weight
  219. ctx_size += n_layer * (4 * n_embd * n_embd * ggml_type_sizef(wtype)); // mlp_mlp_up_weight
  220. ctx_size += n_layer * (n_embd * n_embd * 4 * ggml_type_sizef(wtype)); // mlp_mlp_down_weight
  221. ctx_size += n_ctx * n_layer * n_embd * ggml_type_sizef(GGML_TYPE_F16); // memory_k
  222. ctx_size += n_ctx * n_layer * n_embd * ggml_type_sizef(GGML_TYPE_F16); // memory_v
  223. ctx_size += (1 + 6 * n_layer) * 512; // object overhead
  224. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size / (1024.0 * 1024.0));
  225. }
  226. // create the ggml context
  227. {
  228. struct ggml_init_params params = {
  229. /*.mem_size =*/ ctx_size,
  230. /*.mem_buffer =*/ NULL,
  231. /*.no_alloc =*/ false,
  232. };
  233. model.ctx = ggml_init(params);
  234. if (!model.ctx) {
  235. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  236. return false;
  237. }
  238. }
  239. // prepare memory for the weights
  240. {
  241. const auto & hparams = model.hparams;
  242. const size_t n_embd = hparams.d_model;
  243. const size_t n_layer = hparams.n_layers;
  244. const size_t n_vocab = hparams.n_vocab;
  245. model.layers.resize(n_layer);
  246. model.wte_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  247. model.norm_f_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  248. // map by name
  249. model.tensors["transformer.wte.weight"] = model.wte_weight;
  250. model.tensors["transformer.norm_f.weight"] = model.norm_f_weight;
  251. for (int i = 0; i < (int)n_layer; ++i) {
  252. auto & layer = model.layers[i];
  253. layer.norm_1_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  254. layer.c_attn_wqkv_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, 3 * n_embd);
  255. layer.c_attn_out_proj_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  256. layer.norm_2_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  257. layer.ffn_up_proj = ggml_new_tensor_2d(ctx, wtype, n_embd, 4 * n_embd);
  258. layer.ffn_down_proj = ggml_new_tensor_2d(ctx, wtype, 4 * n_embd, n_embd);
  259. // map by name
  260. model.tensors["transformer.blocks." + std::to_string(i) + ".norm_1.weight"] = layer.norm_1_weight;
  261. model.tensors["transformer.blocks." + std::to_string(i) + ".attn.Wqkv.weight"] = layer.c_attn_wqkv_weight;
  262. model.tensors["transformer.blocks." + std::to_string(i) + ".attn.out_proj.weight"] =
  263. layer.c_attn_out_proj_weight;
  264. model.tensors["transformer.blocks." + std::to_string(i) + ".norm_2.weight"] = layer.norm_2_weight;
  265. model.tensors["transformer.blocks." + std::to_string(i) + ".ffn.up_proj.weight"] = layer.ffn_up_proj;
  266. model.tensors["transformer.blocks." + std::to_string(i) + ".ffn.down_proj.weight"] = layer.ffn_down_proj;
  267. }
  268. }
  269. // key + value memory
  270. {
  271. const auto & hparams = model.hparams;
  272. const int n_embd = hparams.d_model;
  273. const int n_layer = hparams.n_layers;
  274. const int n_ctx = hparams.max_seq_len;
  275. const int64_t n_mem = n_layer * n_ctx;
  276. const int64_t n_elements = n_embd * n_mem;
  277. model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  278. model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  279. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  280. printf("%s: memory_size = %8.2f MB, n_mem = %" PRIu64 "\n", __func__, memory_size / 1024.0 / 1024.0, n_mem);
  281. }
  282. // load weights
  283. {
  284. int n_tensors = 0;
  285. size_t total_size = 0;
  286. printf("%s: ", __func__);
  287. while (true) {
  288. int32_t n_dims;
  289. int32_t length;
  290. int32_t ttype;
  291. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  292. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  293. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  294. if (fin.eof()) {
  295. break;
  296. }
  297. int32_t nelements = 1;
  298. int32_t ne[2] = {1, 1};
  299. for (int i = 0; i < n_dims; ++i) {
  300. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  301. nelements *= ne[i];
  302. }
  303. std::string name(length, 0);
  304. fin.read(&name[0], length);
  305. if (model.tensors.find(name) == model.tensors.end()) {
  306. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  307. return false;
  308. }
  309. auto tensor = model.tensors[name];
  310. if (ggml_nelements(tensor) != nelements) {
  311. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  312. return false;
  313. }
  314. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  315. fprintf(stderr,
  316. "%s: tensor '%s' has wrong shape in model file: got [%5d, "
  317. "%5d], expected [%5d, %5d]\n",
  318. __func__, name.c_str(), (int)tensor->ne[0], (int)tensor->ne[1], ne[0], ne[1]);
  319. return false;
  320. }
  321. // for debugging
  322. if (0) {
  323. printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), ne[0], ne[1],
  324. ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor) / 1024.0 / 1024.0, ggml_nbytes(tensor));
  325. }
  326. const size_t bpe = ggml_type_size(ggml_type(ttype));
  327. if ((nelements * bpe) / ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  328. fprintf(stderr,
  329. "%s: tensor '%s' has wrong size in model file: got %zu, "
  330. "expected %zu\n",
  331. __func__, name.c_str(), ggml_nbytes(tensor), nelements * bpe);
  332. return false;
  333. }
  334. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  335. total_size += ggml_nbytes(tensor);
  336. if (++n_tensors % 8 == 0) {
  337. printf(".");
  338. fflush(stdout);
  339. }
  340. }
  341. printf(" done\n");
  342. printf("%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size / 1024.0 / 1024.0, n_tensors);
  343. }
  344. fin.close();
  345. return true;
  346. }
  347. // evaluate the transformer
  348. //
  349. // - model: the model
  350. // - n_threads: number of threads to use
  351. // - n_past: the context size so far
  352. // - embd_inp: the embeddings of the tokens in the context
  353. // - embd_w: the predicted logits for the next token
  354. //
  355. bool replit_eval(const replit_model & model, const int n_threads, const int n_past,
  356. const std::vector<gpt_vocab::id> & embd_inp, std::vector<float> & embd_w, bool logits_all,
  357. size_t & mem_per_token) {
  358. const int N = embd_inp.size();
  359. const auto & hparams = model.hparams;
  360. const int n_embd = hparams.d_model;
  361. const int n_layer = hparams.n_layers;
  362. const int n_head = hparams.n_heads;
  363. const int n_vocab = hparams.n_vocab;
  364. const int n_ctx = hparams.max_seq_len;
  365. const float eps = 1e-5f;
  366. static size_t buf_size = 256u * 1024 * 1024;
  367. static void * buf = malloc(buf_size);
  368. if (mem_per_token > 0 && mem_per_token * N > buf_size) {
  369. const size_t buf_size_new = 1.1 * (mem_per_token * N); // add 10% to account for ggml object overhead
  370. // printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__,
  371. // buf_size, buf_size_new);
  372. // reallocate
  373. buf_size = buf_size_new;
  374. buf = realloc(buf, buf_size);
  375. if (buf == nullptr) {
  376. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  377. return false;
  378. }
  379. }
  380. struct ggml_init_params params = {
  381. /*.mem_size =*/ buf_size,
  382. /*.mem_buffer =*/ buf,
  383. /*.no_alloc =*/ false,
  384. };
  385. struct ggml_context * ctx0 = ggml_init(params);
  386. struct ggml_cgraph gf = {};
  387. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  388. memcpy(embd->data, embd_inp.data(), N * ggml_element_size(embd));
  389. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.wte_weight, embd);
  390. for (int il = 0; il < n_layer; ++il) {
  391. struct ggml_tensor * cur;
  392. // a = self.ln_1(x)
  393. {
  394. cur = ggml_norm(ctx0, inpL, eps);
  395. cur = ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].norm_1_weight, cur), cur);
  396. }
  397. // self-attention
  398. // b, _, past_key_value = self.attn(a, past_key_value=past_key_value,
  399. // attn_bias=attn_bias, attention_mask=attention_mask,
  400. // is_causal=is_causal)
  401. {
  402. // compute QKV
  403. cur = ggml_mul_mat(ctx0, model.layers[il].c_attn_wqkv_weight, cur);
  404. struct ggml_tensor * Qcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 0 * sizeof(float) * n_embd);
  405. struct ggml_tensor * Kcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 1 * sizeof(float) * n_embd);
  406. struct ggml_tensor * Vcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 2 * sizeof(float) * n_embd);
  407. // store key and value to memory
  408. {
  409. struct ggml_tensor * k =
  410. ggml_view_1d(ctx0, model.memory_k, N * n_embd,
  411. (ggml_element_size(model.memory_k) * n_embd) * (il * n_ctx + n_past));
  412. struct ggml_tensor * v =
  413. ggml_view_1d(ctx0, model.memory_v, N * n_embd,
  414. (ggml_element_size(model.memory_v) * n_embd) * (il * n_ctx + n_past));
  415. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  416. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  417. }
  418. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0,
  419. // 2, 1, 3) [64, N, 12]
  420. struct ggml_tensor * Q = ggml_permute(
  421. ctx0, ggml_cpy(ctx0, Qcur, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd / n_head, n_head, N)), 0, 2,
  422. 1, 3);
  423. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1,
  424. // 3) [64, n_past + N, 12]
  425. struct ggml_tensor * K =
  426. ggml_permute(ctx0,
  427. ggml_reshape_3d(ctx0,
  428. ggml_view_1d(ctx0, model.memory_k, (n_past + N) * n_embd,
  429. il * n_ctx * ggml_element_size(model.memory_k) * n_embd),
  430. n_embd / n_head, n_head, n_past + N),
  431. 0, 2, 1, 3);
  432. // K * Q
  433. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  434. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  435. struct ggml_tensor * KQ_scaled =
  436. ggml_scale(ctx0, KQ, ggml_new_f32(ctx0, 1.0f / sqrt(float(n_embd) / n_head)));
  437. struct ggml_tensor * KQ_scaled_alibi = ggml_alibi(ctx0, KQ_scaled, n_past, n_head, 8.0f);
  438. // KQ_masked = mask_past(KQ_scaled)
  439. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled_alibi, n_past);
  440. // KQ = soft_max(KQ_masked)
  441. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  442. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1,
  443. // 2, 0, 3).contiguous() [n_past + N, 64, 12]
  444. struct ggml_tensor * V_trans = ggml_cpy(
  445. ctx0,
  446. ggml_permute(ctx0,
  447. ggml_reshape_3d(ctx0,
  448. ggml_view_1d(ctx0, model.memory_v, (n_past + N) * n_embd,
  449. il * n_ctx * ggml_element_size(model.memory_v) * n_embd),
  450. n_embd / n_head, n_head, n_past + N),
  451. 1, 2, 0, 3),
  452. ggml_new_tensor_3d(ctx0, model.memory_v->type, n_past + N, n_embd / n_head, n_head));
  453. // KQV = transpose(V) * KQ_soft_max
  454. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  455. // KQV_merged = KQV.permute(0, 2, 1, 3)
  456. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  457. // cur = KQV_merged.contiguous().view(n_embd, N)
  458. cur = ggml_cpy(ctx0, KQV_merged, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  459. // projection
  460. { cur = ggml_mul_mat(ctx0, model.layers[il].c_attn_out_proj_weight, cur); }
  461. }
  462. inpL = ggml_add(ctx0, inpL, cur);
  463. // m = self.ln_2(x)
  464. {
  465. cur = ggml_norm(ctx0, inpL, eps);
  466. cur = ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].norm_2_weight, cur), cur);
  467. }
  468. // n = self.mlp(m)
  469. {
  470. cur = ggml_mul_mat(ctx0, model.layers[il].ffn_up_proj, cur);
  471. // GELU activation
  472. cur = ggml_gelu(ctx0, cur);
  473. // projection
  474. // cur = proj_w*cur + proj_b
  475. cur = ggml_mul_mat(ctx0, model.layers[il].ffn_down_proj, cur);
  476. }
  477. // x = x + n
  478. inpL = ggml_add(ctx0, inpL, cur);
  479. }
  480. // norm
  481. {
  482. inpL = ggml_norm(ctx0, inpL, eps);
  483. // inpL = ln_f_g*inpL
  484. inpL = ggml_mul(ctx0, ggml_repeat(ctx0, model.norm_f_weight, inpL), inpL);
  485. }
  486. // output embedding weight tied to input embedding
  487. inpL = ggml_mul_mat(ctx0, model.wte_weight, inpL);
  488. // logits -> probs
  489. // inpL = ggml_soft_max(ctx0, inpL);
  490. // run the computation
  491. ggml_build_forward_expand(&gf, inpL);
  492. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  493. // std::cout << "Qcur" << std::endl;
  494. // print_tensor(Qcur);
  495. // if (n_past%100 == 0) {
  496. // ggml_graph_print(&gf);
  497. // ggml_graph_dump_dot(&gf, NULL, "mpt-model.dot");
  498. // }
  499. if (logits_all) {
  500. // return result for all tokens
  501. embd_w.resize(n_vocab * N);
  502. memcpy(embd_w.data(), (float *)ggml_get_data(inpL), sizeof(float) * n_vocab * N);
  503. } else {
  504. // return result for just the last token
  505. embd_w.resize(n_vocab);
  506. memcpy(embd_w.data(), (float *)ggml_get_data(inpL) + (n_vocab * (N - 1)), sizeof(float) * n_vocab);
  507. }
  508. if (mem_per_token == 0) {
  509. mem_per_token = ggml_used_mem(ctx0) / N;
  510. }
  511. // printf("used_mem = %zu\n", ggml_used_mem(ctx0));
  512. ggml_free(ctx0);
  513. return true;
  514. }
  515. int main(int argc, char ** argv) {
  516. const int64_t t_main_start_us = ggml_time_us();
  517. gpt_params params;
  518. params.model = "";
  519. if (gpt_params_parse(argc, argv, params) == false) {
  520. return 1;
  521. }
  522. if (params.seed < 0) {
  523. params.seed = time(NULL);
  524. }
  525. printf("%s: seed = %d\n", __func__, params.seed);
  526. std::mt19937 rng(params.seed);
  527. if (params.prompt.empty()) {
  528. if (!is_stdin_terminal()) {
  529. std::string line;
  530. while (std::getline(std::cin, line)) {
  531. params.prompt = params.prompt + "\n" + line;
  532. }
  533. } else {
  534. params.prompt = gpt_random_prompt(rng);
  535. }
  536. }
  537. int64_t t_load_us = 0;
  538. replit_tokenizer vocab;
  539. replit_model model;
  540. // load the model
  541. {
  542. const int64_t t_start_us = ggml_time_us();
  543. if (!replit_model_load(params.model, model, vocab)) {
  544. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  545. return 1;
  546. }
  547. t_load_us = ggml_time_us() - t_start_us;
  548. }
  549. int n_past = 0;
  550. int64_t t_sample_us = 0;
  551. int64_t t_predict_us = 0;
  552. std::vector<float> logits;
  553. // tokenize the prompt
  554. std::vector<std::size_t> embd_inp = replit_tokenizer_tokenize(vocab, params.prompt);
  555. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  556. for (size_t i = 0; i < embd_inp.size(); i++) {
  557. printf("%s: token[%zu] = %6zu\n", __func__, i, embd_inp[i]);
  558. // vocab.id_to_token.at(embd_inp[i]).c_str()
  559. }
  560. printf("\n");
  561. params.n_predict = std::min(params.n_predict, model.hparams.max_seq_len - (int)embd_inp.size());
  562. std::vector<gpt_vocab::id> embd;
  563. // determine the required inference memory per token:
  564. size_t mem_per_token = 0;
  565. replit_eval(model, params.n_threads, 0, {0, 1, 2, 3}, logits, false, mem_per_token);
  566. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  567. // predict
  568. if (embd.size() > 0) {
  569. const int64_t t_start_us = ggml_time_us();
  570. if (!replit_eval(model, params.n_threads, n_past, embd, logits, false, mem_per_token)) {
  571. printf("Failed to predict\n");
  572. return 1;
  573. }
  574. t_predict_us += ggml_time_us() - t_start_us;
  575. }
  576. n_past += embd.size();
  577. embd.clear();
  578. if (i >= embd_inp.size()) {
  579. // sample next token
  580. const int top_k = params.top_k;
  581. const float top_p = params.top_p;
  582. const float temp = params.temp;
  583. const int n_vocab = model.hparams.n_vocab;
  584. gpt_vocab::id id = 0;
  585. {
  586. const int64_t t_start_sample_us = ggml_time_us();
  587. id = gpt_sample_top_k_top_p(vocab.raw_vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p,
  588. temp, rng);
  589. t_sample_us += ggml_time_us() - t_start_sample_us;
  590. }
  591. // add it to the context
  592. embd.push_back(id);
  593. } else {
  594. // if here, it means we are still processing the input prompt
  595. for (size_t k = i; k < embd_inp.size(); k++) {
  596. embd.push_back(embd_inp[k]);
  597. if (int32_t(embd.size()) > params.n_batch) {
  598. break;
  599. }
  600. }
  601. i += embd.size() - 1;
  602. }
  603. // display text
  604. for (auto id : embd) {
  605. printf("%s", replit_tokenizer_detokenize(vocab, {static_cast<std::size_t>(id)}).c_str());
  606. }
  607. fflush(stdout);
  608. // end of text token
  609. if (embd.back() == 0) {
  610. break;
  611. }
  612. }
  613. // report timing
  614. {
  615. const int64_t t_main_end_us = ggml_time_us();
  616. printf("\n\n");
  617. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  618. printf("%s: load time = %8.2f ms\n", __func__, t_load_us / 1000.0f);
  619. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us / 1000.0f);
  620. printf("%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us / 1000.0f,
  621. t_predict_us / 1000.0f / n_past);
  622. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us) / 1000.0f);
  623. }
  624. ggml_free(model.ctx);
  625. return 0;
  626. }