main.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. #include "ggml/ggml.h"
  2. #include "common-ggml.h"
  3. #include "common.h"
  4. #include <cmath>
  5. #include <cstddef>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <cinttypes>
  10. #include <map>
  11. #include <string>
  12. #include <utility>
  13. #include <vector>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. // no defaults for now
  18. struct mpt_hparams {
  19. int32_t d_model = 0;
  20. int32_t max_seq_len = 0;
  21. int32_t n_heads = 0;
  22. int32_t n_layers = 0;
  23. int32_t n_vocab = 0;
  24. float alibi_bias_max = 0;
  25. float clip_qkv = 0;
  26. int32_t ftype = 0;
  27. int32_t n_ctx = 0;
  28. };
  29. struct mpt_layer {
  30. // pre normalization
  31. struct ggml_tensor * norm_1_weight;
  32. // attention
  33. struct ggml_tensor * c_attn_wqkv_weight;
  34. struct ggml_tensor * c_attn_out_proj_weight;
  35. // post normalization
  36. struct ggml_tensor * norm_2_weight;
  37. // ff
  38. struct ggml_tensor * ffn_up_proj;
  39. struct ggml_tensor * ffn_down_proj;
  40. };
  41. struct mpt_model {
  42. mpt_hparams hparams;
  43. struct ggml_tensor * wte_weight; // position embedding
  44. struct ggml_tensor * norm_f_weight; // language model head
  45. std::vector<mpt_layer> layers;
  46. // key + value memory
  47. struct ggml_tensor * memory_k;
  48. struct ggml_tensor * memory_v;
  49. struct ggml_context * ctx;
  50. std::map<std::string, struct ggml_tensor *> tensors;
  51. };
  52. struct mpt_params {
  53. int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
  54. int32_t seed = -1; // RNG seed
  55. int32_t n_predict = 200; // new tokens to predict
  56. int32_t n_batch = 8; // batch size for prompt processing
  57. int32_t n_ctx = 512;
  58. std::string model = ""; // model path
  59. std::string prompt = "";
  60. std::string token_test = "";
  61. bool perplexity = false;
  62. // sampling parameters
  63. int32_t top_k = 0;
  64. float top_p = 1.0f;
  65. float temp = 0.8f;
  66. int32_t repeat_last_n = 64;
  67. float repeat_penalty = 1.02f;
  68. };
  69. void mpt_print_usage(int /*argc*/, char ** argv, const mpt_params & params) {
  70. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  71. fprintf(stderr, "\n");
  72. fprintf(stderr, "options:\n");
  73. fprintf(stderr, " -h, --help show this help message and exit\n");
  74. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
  75. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  76. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  77. fprintf(stderr, " prompt to start generation with (default: random)\n");
  78. fprintf(stderr, " -f FNAME, --file FNAME\n");
  79. fprintf(stderr, " load prompt from a file\n");
  80. fprintf(stderr, " -tt TOKEN_TEST, --token_test TOKEN_TEST\n");
  81. fprintf(stderr, " test tokenization\n");
  82. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
  83. fprintf(stderr, " --top_k N top-k sampling (default: %d, 0 = n_vocab)\n", params.top_k);
  84. fprintf(stderr, " --top_p N top-p sampling (default: %.2f)\n", params.top_p);
  85. fprintf(stderr, " --temp N temperature (default: %.2f)\n", params.temp);
  86. fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  87. fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.2f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  88. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  89. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  90. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  91. fprintf(stderr, " -m FNAME, --model FNAME\n");
  92. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  93. fprintf(stderr, "\n");
  94. }
  95. bool mpt_params_parse(int argc, char ** argv, mpt_params & params) {
  96. for (int i = 1; i < argc; i++) {
  97. std::string arg = argv[i];
  98. if (arg == "-s" || arg == "--seed") {
  99. params.seed = std::stoi(argv[++i]);
  100. } else if (arg == "-t" || arg == "--threads") {
  101. params.n_threads = std::stoi(argv[++i]);
  102. } else if (arg == "-p" || arg == "--prompt") {
  103. params.prompt = argv[++i];
  104. } else if (arg == "-n" || arg == "--n_predict") {
  105. params.n_predict = std::stoi(argv[++i]);
  106. } else if (arg == "--top_k") {
  107. params.top_k = std::max(1, std::stoi(argv[++i]));
  108. } else if (arg == "--top_p") {
  109. params.top_p = std::stof(argv[++i]);
  110. } else if (arg == "--temp") {
  111. params.temp = std::stof(argv[++i]);
  112. } else if (arg == "--repeat-last-n") {
  113. params.repeat_last_n = std::stof(argv[++i]);
  114. } else if (arg == "--repeat-penalty") {
  115. params.repeat_penalty = std::stof(argv[++i]);
  116. } else if (arg == "--perplexity") {
  117. params.perplexity = true;
  118. } else if (arg == "-c" || arg == "--ctx-size") {
  119. params.n_ctx = std::stoi(argv[++i]);
  120. } else if (arg == "-b" || arg == "--batch_size") {
  121. params.n_batch = std::stoi(argv[++i]);
  122. } else if (arg == "-m" || arg == "--model") {
  123. params.model = argv[++i];
  124. } else if (arg == "-h" || arg == "--help") {
  125. mpt_print_usage(argc, argv, params);
  126. exit(0);
  127. } else if (arg == "-f" || arg == "--file") {
  128. if (++i > argc) {
  129. fprintf(stderr, "Invalid file param");
  130. break;
  131. }
  132. std::ifstream file(argv[i]);
  133. if (!file) {
  134. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  135. break;
  136. }
  137. params.prompt.clear();
  138. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  139. if (params.prompt.back() == '\n') {
  140. params.prompt.pop_back();
  141. }
  142. } else if (arg == "-tt" || arg == "--token_test") {
  143. params.token_test = argv[++i];
  144. } else {
  145. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  146. mpt_print_usage(argc, argv, params);
  147. exit(0);
  148. }
  149. }
  150. return true;
  151. }
  152. // load the model's weights from a file
  153. bool mpt_model_load(const std::string & fname, mpt_model & model, gpt_vocab & vocab) {
  154. printf("%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  155. auto fin = std::ifstream(fname, std::ios::binary);
  156. if (!fin) {
  157. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  158. return false;
  159. }
  160. // verify magic
  161. {
  162. uint32_t magic;
  163. fin.read((char *)&magic, sizeof(magic));
  164. if (magic != GGML_FILE_MAGIC) {
  165. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  166. return false;
  167. }
  168. }
  169. // load hparams
  170. {
  171. auto & hparams = model.hparams;
  172. fin.read((char *) &hparams.d_model, sizeof(hparams.d_model));
  173. fin.read((char *) &hparams.max_seq_len, sizeof(hparams.max_seq_len));
  174. fin.read((char *) &hparams.n_heads, sizeof(hparams.n_heads));
  175. fin.read((char *) &hparams.n_layers, sizeof(hparams.n_layers));
  176. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  177. fin.read((char *) &hparams.alibi_bias_max, sizeof(hparams.alibi_bias_max));
  178. fin.read((char *) &hparams.clip_qkv, sizeof(hparams.clip_qkv));
  179. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  180. hparams.n_ctx = std::min(hparams.max_seq_len, hparams.n_ctx);
  181. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  182. printf("%s: d_model = %d\n", __func__, hparams.d_model);
  183. printf("%s: max_seq_len = %d\n", __func__, hparams.max_seq_len);
  184. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  185. printf("%s: n_heads = %d\n", __func__, hparams.n_heads);
  186. printf("%s: n_layers = %d\n", __func__, hparams.n_layers);
  187. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  188. printf("%s: alibi_bias_max = %f\n", __func__, hparams.alibi_bias_max);
  189. printf("%s: clip_qkv = %f\n", __func__, hparams.clip_qkv);
  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. {
  196. const int32_t n_vocab = model.hparams.n_vocab;
  197. std::string word;
  198. std::vector<char> buf(128);
  199. for (int i = 0; i < n_vocab; i++) {
  200. uint32_t len;
  201. fin.read((char *) &len, sizeof(len));
  202. buf.resize(len);
  203. fin.read((char *) buf.data(), len);
  204. word.assign(buf.data(), len);
  205. // Convert token from utf-8
  206. std::wstring word_multibytes = convert_to_wstring(word);
  207. word.resize(word_multibytes.size());
  208. for (size_t w = 0; w < word_multibytes.size(); w++) {
  209. word[w] = uint8_t(word_multibytes[w]);
  210. }
  211. vocab.token_to_id[word] = i;
  212. vocab.id_to_token[i] = word;
  213. }
  214. }
  215. // for the big tensors, we have the option to store the data in 16-bit
  216. // floats or quantized in order to save memory and also to speed up the
  217. // computation
  218. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype)(model.hparams.ftype));
  219. if (wtype == GGML_TYPE_COUNT) {
  220. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n", __func__, fname.c_str(),
  221. model.hparams.ftype);
  222. return false;
  223. }
  224. auto & ctx = model.ctx;
  225. size_t ctx_size = 0;
  226. const auto & hparams = model.hparams;
  227. const size_t n_ctx = hparams.n_ctx;
  228. {
  229. const size_t n_embd = hparams.d_model;
  230. const size_t n_layer = hparams.n_layers;
  231. const size_t n_vocab = hparams.n_vocab;
  232. ctx_size += n_embd * n_vocab * ggml_type_sizef(wtype); // wte_weight
  233. ctx_size += n_embd * ggml_type_sizef(GGML_TYPE_F32); // norm_f_weight
  234. ctx_size += n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ln_1_weight
  235. ctx_size += n_layer * (3 * n_embd * n_embd * ggml_type_sizef(wtype)); // attn_Wqkv_weight
  236. ctx_size += n_layer * (n_embd * n_embd * ggml_type_sizef(wtype)); // attn_out_proj_weight
  237. ctx_size += n_layer * (n_embd * ggml_type_sizef(GGML_TYPE_F32)); // ln_2_weight
  238. ctx_size += n_layer * (4 * n_embd * n_embd * ggml_type_sizef(wtype)); // mlp_mlp_up_weight
  239. ctx_size += n_layer * (n_embd * n_embd * 4 * ggml_type_sizef(wtype)); // mlp_mlp_down_weight
  240. ctx_size += n_ctx * n_layer * n_embd * ggml_type_sizef(GGML_TYPE_F16); // memory_k
  241. ctx_size += n_ctx * n_layer * n_embd * ggml_type_sizef(GGML_TYPE_F16); // memory_v
  242. ctx_size += (1 + 6 * n_layer) * 512; // object overhead
  243. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size / (1024.0 * 1024.0));
  244. }
  245. // create the ggml context
  246. {
  247. struct ggml_init_params params = {
  248. /*.mem_size =*/ ctx_size,
  249. /*.mem_buffer =*/ NULL,
  250. /*.no_alloc =*/ false,
  251. };
  252. model.ctx = ggml_init(params);
  253. if (!model.ctx) {
  254. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  255. return false;
  256. }
  257. }
  258. // prepare memory for the weights
  259. {
  260. const auto & hparams = model.hparams;
  261. const size_t n_embd = hparams.d_model;
  262. const size_t n_layer = hparams.n_layers;
  263. const size_t n_vocab = hparams.n_vocab;
  264. model.layers.resize(n_layer);
  265. model.wte_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  266. model.norm_f_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  267. // map by name
  268. model.tensors["transformer.wte.weight"] = model.wte_weight;
  269. model.tensors["transformer.norm_f.weight"] = model.norm_f_weight;
  270. for (int i = 0; i < (int) n_layer; ++i) {
  271. auto & layer = model.layers[i];
  272. layer.norm_1_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  273. layer.c_attn_wqkv_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, 3 * n_embd);
  274. layer.c_attn_out_proj_weight = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  275. layer.norm_2_weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  276. layer.ffn_up_proj = ggml_new_tensor_2d(ctx, wtype, n_embd, 4 * n_embd);
  277. layer.ffn_down_proj = ggml_new_tensor_2d(ctx, wtype, 4 * n_embd, n_embd);
  278. // map by name
  279. model.tensors["transformer.blocks." + std::to_string(i) + ".norm_1.weight"] = layer.norm_1_weight;
  280. model.tensors["transformer.blocks." + std::to_string(i) + ".attn.Wqkv.weight"] = layer.c_attn_wqkv_weight;
  281. model.tensors["transformer.blocks." + std::to_string(i) + ".attn.out_proj.weight"] = layer.c_attn_out_proj_weight;
  282. model.tensors["transformer.blocks." + std::to_string(i) + ".norm_2.weight"] = layer.norm_2_weight;
  283. model.tensors["transformer.blocks." + std::to_string(i) + ".ffn.up_proj.weight"] = layer.ffn_up_proj;
  284. model.tensors["transformer.blocks." + std::to_string(i) + ".ffn.down_proj.weight"] = layer.ffn_down_proj;
  285. }
  286. }
  287. // key + value memory
  288. {
  289. const auto & hparams = model.hparams;
  290. const size_t n_embd = hparams.d_model;
  291. const size_t n_layer = hparams.n_layers;
  292. const int64_t n_mem = n_layer * n_ctx;
  293. const int64_t n_elements = n_embd * n_mem;
  294. model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  295. model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements);
  296. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  297. printf("%s: memory_size = %8.2f MB, n_mem = %" PRId64 "\n", __func__, memory_size / 1024.0 / 1024.0, n_mem);
  298. }
  299. // load weights
  300. {
  301. int n_tensors = 0;
  302. size_t total_size = 0;
  303. printf("%s: ", __func__);
  304. while (true) {
  305. int32_t n_dims;
  306. int32_t length;
  307. int32_t ttype;
  308. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  309. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  310. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  311. if (fin.eof()) {
  312. break;
  313. }
  314. int32_t nelements = 1;
  315. int32_t ne[2] = {1, 1};
  316. for (int i = 0; i < n_dims; ++i) {
  317. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  318. nelements *= ne[i];
  319. }
  320. std::string name(length, 0);
  321. fin.read(&name[0], length);
  322. if (model.tensors.find(name) == model.tensors.end()) {
  323. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  324. return false;
  325. }
  326. auto tensor = model.tensors[name];
  327. if (ggml_nelements(tensor) != nelements) {
  328. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  329. return false;
  330. }
  331. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  332. fprintf(stderr,
  333. "%s: tensor '%s' has wrong shape in model file: got [%5d, "
  334. "%5d], expected [%5d, %5d]\n",
  335. __func__, name.c_str(), (int)tensor->ne[0], (int)tensor->ne[1], ne[0], ne[1]);
  336. return false;
  337. }
  338. // for debugging
  339. if (0) {
  340. printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), ne[0], ne[1],
  341. ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor) / 1024.0 / 1024.0, ggml_nbytes(tensor));
  342. }
  343. const size_t bpe = ggml_type_size(ggml_type(ttype));
  344. if ((nelements * bpe) / ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  345. fprintf(stderr,
  346. "%s: tensor '%s' has wrong size in model file: got %zu, "
  347. "expected %zu\n",
  348. __func__, name.c_str(), ggml_nbytes(tensor), nelements * bpe);
  349. return false;
  350. }
  351. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  352. total_size += ggml_nbytes(tensor);
  353. if (++n_tensors % 8 == 0) {
  354. printf(".");
  355. fflush(stdout);
  356. }
  357. }
  358. printf(" done\n");
  359. printf("%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size / 1024.0 / 1024.0, n_tensors);
  360. }
  361. fin.close();
  362. return true;
  363. }
  364. // evaluate the transformer
  365. //
  366. // - model: the model
  367. // - n_threads: number of threads to use
  368. // - n_past: the context size so far
  369. // - embd_inp: the embeddings of the tokens in the context
  370. // - embd_w: the predicted logits for the next token
  371. //
  372. bool mpt_eval(const mpt_model & model, const int n_threads, const int n_past,
  373. const std::vector<gpt_vocab::id> & embd_inp, std::vector<float> & embd_w, bool logits_all, size_t & mem_per_token) {
  374. const int N = embd_inp.size();
  375. const auto & hparams = model.hparams;
  376. const int n_embd = hparams.d_model;
  377. const int n_layer = hparams.n_layers;
  378. const int n_head = hparams.n_heads;
  379. const int n_vocab = hparams.n_vocab;
  380. const int n_ctx = hparams.n_ctx;
  381. const float eps = 1e-5f;
  382. static size_t buf_size = 256u * 1024 * 1024;
  383. static void * buf = malloc(buf_size);
  384. // use 2 scratch buffers
  385. // TODO: very hacky solution - reimplement in a more elegant way
  386. static size_t scr0_size = 256u*1024*1024;
  387. static void * scr0 = malloc(scr0_size);
  388. static size_t scr1_size = 256u*1024*1024;
  389. static void * scr1 = malloc(scr1_size);
  390. if (mem_per_token > 0 && mem_per_token * N > buf_size) {
  391. const size_t buf_size_new = 1.1 * (mem_per_token * N); // add 10% to account for ggml object overhead
  392. // printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__,
  393. // buf_size, buf_size_new);
  394. // reallocate
  395. buf_size = buf_size_new;
  396. buf = realloc(buf, buf_size);
  397. if (buf == nullptr) {
  398. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  399. return false;
  400. }
  401. }
  402. struct ggml_init_params params = {
  403. /*.mem_size =*/ buf_size,
  404. /*.mem_buffer =*/ buf,
  405. /*.no_alloc =*/ false,
  406. };
  407. struct ggml_context * ctx0 = ggml_init(params);
  408. struct ggml_cgraph gf = {};
  409. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  410. memcpy(embd->data, embd_inp.data(), N * ggml_element_size(embd));
  411. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.wte_weight, embd);
  412. for (int il = 0; il < n_layer; ++il) {
  413. struct ggml_tensor * cur;
  414. ggml_set_scratch(ctx0, { 0, scr0_size, scr0, });
  415. // a = self.ln_1(x)
  416. {
  417. cur = ggml_norm(ctx0, inpL, eps);
  418. cur = ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].norm_1_weight, cur), cur);
  419. }
  420. // self-attention
  421. // b, _, past_key_value = self.attn(a, past_key_value=past_key_value,
  422. // attn_bias=attn_bias, attention_mask=attention_mask,
  423. // is_causal=is_causal)
  424. {
  425. // compute QKV
  426. cur = ggml_mul_mat(ctx0, model.layers[il].c_attn_wqkv_weight, cur);
  427. if (model.hparams.clip_qkv > 0.0f) {
  428. cur = ggml_clamp(ctx0, cur, -model.hparams.clip_qkv, model.hparams.clip_qkv);
  429. }
  430. struct ggml_tensor * Qcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 0 * sizeof(float) * n_embd);
  431. struct ggml_tensor * Kcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 1 * sizeof(float) * n_embd);
  432. struct ggml_tensor * Vcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 2 * sizeof(float) * n_embd);
  433. // store key and value to memory
  434. {
  435. struct ggml_tensor * k =
  436. ggml_view_1d(ctx0, model.memory_k, N * n_embd,
  437. (ggml_element_size(model.memory_k) * n_embd) * (il * n_ctx + n_past));
  438. struct ggml_tensor * v =
  439. ggml_view_1d(ctx0, model.memory_v, N * n_embd,
  440. (ggml_element_size(model.memory_v) * n_embd) * (il * n_ctx + n_past));
  441. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  442. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  443. }
  444. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0,
  445. // 2, 1, 3) [64, N, 12]
  446. struct ggml_tensor * Q = ggml_permute(
  447. ctx0, ggml_cpy(ctx0, Qcur, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd / n_head, n_head, N)), 0, 2,
  448. 1, 3);
  449. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1,
  450. // 3) [64, n_past + N, 12]
  451. struct ggml_tensor * K =
  452. ggml_permute(ctx0,
  453. ggml_reshape_3d(ctx0,
  454. ggml_view_1d(ctx0, model.memory_k, (n_past + N) * n_embd,
  455. il * n_ctx * ggml_element_size(model.memory_k) * n_embd),
  456. n_embd / n_head, n_head, n_past + N),
  457. 0, 2, 1, 3);
  458. // K * Q
  459. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  460. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  461. struct ggml_tensor * KQ_scaled =
  462. ggml_scale(ctx0, KQ, ggml_new_f32(ctx0, 1.0f / sqrt(float(n_embd) / n_head)));
  463. struct ggml_tensor * KQ_scaled_alibi =
  464. ggml_alibi(ctx0, KQ_scaled, n_past, n_head, model.hparams.alibi_bias_max);
  465. // KQ_masked = mask_past(KQ_scaled)
  466. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled_alibi, n_past);
  467. // KQ = soft_max(KQ_masked)
  468. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  469. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1,
  470. // 2, 0, 3).contiguous() [n_past + N, 64, 12]
  471. struct ggml_tensor * V_trans = ggml_cpy(
  472. ctx0,
  473. ggml_permute(ctx0,
  474. ggml_reshape_3d(ctx0,
  475. ggml_view_1d(ctx0, model.memory_v, (n_past + N) * n_embd,
  476. il * n_ctx * ggml_element_size(model.memory_v) * n_embd),
  477. n_embd / n_head, n_head, n_past + N),
  478. 1, 2, 0, 3),
  479. ggml_new_tensor_3d(ctx0, model.memory_v->type, n_past + N, n_embd / n_head, n_head));
  480. // KQV = transpose(V) * KQ_soft_max
  481. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  482. // KQV_merged = KQV.permute(0, 2, 1, 3)
  483. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  484. // cur = KQV_merged.contiguous().view(n_embd, N)
  485. cur = ggml_cpy(ctx0, KQV_merged, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  486. // projection
  487. { cur = ggml_mul_mat(ctx0, model.layers[il].c_attn_out_proj_weight, cur); }
  488. }
  489. inpL = ggml_add(ctx0, inpL, cur);
  490. ggml_set_scratch(ctx0, { 0, scr1_size, scr1, });
  491. // m = self.ln_2(x)
  492. {
  493. cur = ggml_norm(ctx0, inpL, eps);
  494. cur = ggml_mul(ctx0, ggml_repeat(ctx0, model.layers[il].norm_2_weight, cur), cur);
  495. }
  496. // n = self.mlp(m)
  497. {
  498. cur = ggml_mul_mat(ctx0, model.layers[il].ffn_up_proj, cur);
  499. // GELU activation
  500. cur = ggml_gelu(ctx0, cur);
  501. // projection
  502. // cur = proj_w*cur + proj_b
  503. cur = ggml_mul_mat(ctx0, model.layers[il].ffn_down_proj, cur);
  504. }
  505. // x = x + n
  506. inpL = ggml_add(ctx0, inpL, cur);
  507. }
  508. ggml_set_scratch(ctx0, { 0, scr0_size, scr0, });
  509. // norm
  510. {
  511. inpL = ggml_norm(ctx0, inpL, eps);
  512. // inpL = ln_f_g*inpL
  513. inpL = ggml_mul(ctx0, ggml_repeat(ctx0, model.norm_f_weight, inpL), inpL);
  514. }
  515. ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  516. // output embedding weight tied to input embedding
  517. inpL = ggml_mul_mat(ctx0, model.wte_weight, inpL);
  518. // logits -> probs
  519. // inpL = ggml_soft_max(ctx0, inpL);
  520. // run the computation
  521. ggml_build_forward_expand(&gf, inpL);
  522. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  523. // std::cout << "Qcur" << std::endl;
  524. // print_tensor(Qcur);
  525. // if (n_past%100 == 0) {
  526. // ggml_graph_print(&gf);
  527. // ggml_graph_dump_dot(&gf, NULL, "mpt-model.dot");
  528. // }
  529. if (logits_all) {
  530. // return result for all tokens
  531. embd_w.resize(n_vocab *N);
  532. memcpy(embd_w.data(), (float *)ggml_get_data(inpL) , sizeof(float) * n_vocab * N);
  533. } else {
  534. // return result for just the last token
  535. embd_w.resize(n_vocab);
  536. memcpy(embd_w.data(), (float *)ggml_get_data(inpL) + (n_vocab * (N - 1)), sizeof(float) * n_vocab);
  537. }
  538. if (mem_per_token == 0) {
  539. mem_per_token = ggml_used_mem(ctx0) / N;
  540. }
  541. // printf("used_mem = %zu\n", ggml_used_mem(ctx0));
  542. ggml_free(ctx0);
  543. return true;
  544. }
  545. std::vector<float> softmax(const std::vector<float> & logits) {
  546. std::vector<float> probs(logits.size());
  547. float max_logit = logits[0];
  548. for (float v : logits) max_logit = std::max(max_logit, v);
  549. double sum_exp = 0.0;
  550. for (size_t i = 0; i < logits.size(); i++) {
  551. // Subtract the maximum logit value from the current logit value for numerical stability
  552. const float logit = logits[i] - max_logit;
  553. const float exp_logit = expf(logit);
  554. sum_exp += exp_logit;
  555. probs[i] = exp_logit;
  556. }
  557. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  558. return probs;
  559. }
  560. int perplexity(const mpt_params & params) {
  561. ggml_time_init();
  562. const int64_t t_main_start_us = ggml_time_us();
  563. printf("%s: n_threads = %d\n", __func__, params.n_threads);
  564. printf("%s: n_batch = %d\n", __func__, params.n_batch);
  565. printf("%s: n_ctx = %d\n", __func__, params.n_ctx);
  566. printf("\n");
  567. int64_t t_load_us = 0;
  568. gpt_vocab vocab;
  569. mpt_model model;
  570. model.hparams.n_ctx = params.n_ctx;
  571. // load the model
  572. {
  573. const int64_t t_start_us = ggml_time_us();
  574. if (!mpt_model_load(params.model, model, vocab)) {
  575. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  576. return 1;
  577. }
  578. t_load_us = ggml_time_us() - t_start_us;
  579. }
  580. int64_t t_predict_us = 0;
  581. std::vector<float> logits;
  582. // tokenize the prompt
  583. std::vector<int> embd_inp = ::gpt_tokenize(vocab, params.prompt);
  584. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  585. // determine the required inference memory per token:
  586. size_t mem_per_token = 0;
  587. mpt_eval(model, params.n_threads, 0, {0, 1, 2, 3}, logits, false, mem_per_token);
  588. int count = 0;
  589. const int n_chunk = embd_inp.size() / params.n_ctx;
  590. const int n_vocab = model.hparams.n_vocab;
  591. const int n_batch = params.n_batch;
  592. double nll = 0.0;
  593. fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
  594. for (int i = 0; i < n_chunk; ++i) {
  595. const int start = i * params.n_ctx;
  596. const int end = start + params.n_ctx;
  597. const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
  598. std::vector<float> logits;
  599. const auto t_start = std::chrono::high_resolution_clock::now();
  600. for (int j = 0; j < num_batches; ++j) {
  601. const int batch_start = start + j * n_batch;
  602. const int batch_size = std::min(end - batch_start, n_batch);
  603. std::vector<gpt_vocab::id> embd;
  604. for(int p=0;p<batch_size;p++) {
  605. embd.push_back( embd_inp[batch_start+p] );
  606. }
  607. std::vector<float> batch_logits;// = llama_get_logits(ctx);
  608. const int64_t t_start_us = ggml_time_us();
  609. if (!mpt_eval(model, params.n_threads, j * batch_size, embd, batch_logits, true, mem_per_token)) {
  610. printf("%s: failed to evaluate model\n", __func__);
  611. return 1;
  612. }
  613. t_predict_us += ggml_time_us() - t_start_us;
  614. logits.insert(logits.end(), batch_logits.data(), batch_logits.data() + batch_size * n_vocab);
  615. }
  616. const auto t_end = std::chrono::high_resolution_clock::now();
  617. if (i == 0) {
  618. const float t_total = std::chrono::duration<float>(t_end - t_start).count();
  619. fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
  620. int total_seconds = (int)(t_total * n_chunk);
  621. if (total_seconds >= 60*60) {
  622. fprintf(stderr, "%d hours ", total_seconds / (60*60));
  623. total_seconds = total_seconds % (60*60);
  624. }
  625. fprintf(stderr, "%d minutes\n", total_seconds / 60);
  626. printf("\nChunk\tPPL cumulative\tPPL chunk\n");
  627. }
  628. // We get the logits for all the tokens in the context window (params.n_ctx)
  629. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  630. // calculate the perplexity over the last half of the window (so the model always has
  631. // some context to predict the token).
  632. //
  633. // We rely on the fact that attention in the forward pass only looks at previous
  634. // tokens here, so the logits returned for each token are an accurate representation
  635. // of what the model would have predicted at that point.
  636. //
  637. // Example, we have a context window of 512, we will compute perplexity for each of the
  638. // last 256 tokens. Then, we split the input up into context window size chunks to
  639. // process the entire prompt.
  640. double nllchunk = 0.0;
  641. int countchunk = 0;
  642. for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
  643. // Calculate probability of next token, given the previous ones.
  644. const std::vector<float> tok_logits(
  645. logits.begin() + (j + 0) * n_vocab,
  646. logits.begin() + (j + 1) * n_vocab);
  647. const float prob = softmax(tok_logits)[embd_inp[ start+ j + 1]];
  648. nllchunk += -std::log(prob);
  649. ++countchunk;
  650. }
  651. nll += nllchunk;
  652. count += countchunk;
  653. // perplexity is e^(average negative log-likelihood)
  654. printf("%d\t%.8lf\t%.8lf\n", i + 1, std::exp(nll / count), std::exp(nllchunk/countchunk) );
  655. fflush(stdout);
  656. }
  657. // report timing
  658. {
  659. const int64_t t_main_end_us = ggml_time_us();
  660. printf("\n\n");
  661. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  662. printf("%s: load time = %8.2f ms\n", __func__, t_load_us / 1000.0f);
  663. printf("%s: eval time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us / 1000.0f, t_predict_us / 1000.0f / (n_chunk * params.n_ctx));
  664. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us) / 1000.0f);
  665. }
  666. ggml_free(model.ctx);
  667. return 0;
  668. }
  669. int main(int argc, char ** argv) {
  670. mpt_params params;
  671. if (mpt_params_parse(argc, argv, params) == false) {
  672. return 1;
  673. }
  674. if (params.perplexity) {
  675. return perplexity(params);
  676. }
  677. ggml_time_init();
  678. const int64_t t_main_start_us = ggml_time_us();
  679. if (params.seed < 0) {
  680. params.seed = time(NULL);
  681. }
  682. if (params.n_predict < 0) {
  683. params.n_predict = 0;
  684. }
  685. printf("%s: seed = %d\n", __func__, params.seed);
  686. printf("%s: n_threads = %d\n", __func__, params.n_threads);
  687. printf("%s: n_batch = %d\n", __func__, params.n_batch);
  688. printf("%s: n_ctx = %d\n", __func__, params.n_ctx);
  689. printf("%s: n_predict = %d\n\n", __func__, params.n_predict);
  690. std::mt19937 rng(params.seed);
  691. if (params.prompt.empty()) {
  692. params.prompt = gpt_random_prompt(rng);
  693. }
  694. int64_t t_load_us = 0;
  695. gpt_vocab vocab;
  696. mpt_model model;
  697. model.hparams.n_ctx = params.n_ctx;
  698. // load the model
  699. {
  700. const int64_t t_start_us = ggml_time_us();
  701. if (!mpt_model_load(params.model, model, vocab)) {
  702. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  703. return 1;
  704. }
  705. t_load_us = ggml_time_us() - t_start_us;
  706. test_gpt_tokenizer(vocab, params.token_test);
  707. }
  708. if (params.top_k == 0) {
  709. params.top_k = model.hparams.n_vocab;
  710. }
  711. if (params.repeat_last_n == -1) {
  712. params.repeat_last_n = params.n_ctx;
  713. }
  714. printf("\n");
  715. printf("%s: temp = %.3f\n", __func__, params.temp);
  716. printf("%s: top_k = %d\n", __func__, params.top_k);
  717. printf("%s: top_p = %.3f\n", __func__, params.top_p);
  718. printf("%s: repeat_last_n = %d\n", __func__, params.repeat_last_n);
  719. printf("%s: repeat_penalty = %.3f\n", __func__, params.repeat_penalty);
  720. int64_t t_sample_us = 0;
  721. int64_t t_predict_us = 0;
  722. std::vector<int32_t> last_n_tokens(params.n_ctx);
  723. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  724. // tokenize the prompt
  725. std::vector<int> embd_inp = ::gpt_tokenize(vocab, params.prompt);
  726. printf("\n");
  727. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  728. for (size_t i = 0; i < embd_inp.size(); i++) {
  729. printf("%s: token[%zu] = %6d\n", __func__, i, embd_inp[i]);
  730. }
  731. printf("\n");
  732. std::vector<gpt_vocab::id> embd;
  733. std::vector<float> logits;
  734. // determine the required inference memory per token:
  735. size_t mem_per_token = 0;
  736. mpt_eval(model, params.n_threads, 0, {0, 1, 2, 3}, logits, false, mem_per_token);
  737. int n_past = 0;
  738. int n_consumed = 0;
  739. int n_sampled = 0;
  740. while (n_sampled < params.n_predict) {
  741. // predict
  742. if (embd.size() > 0) {
  743. const int64_t t_start_us = ggml_time_us();
  744. if (!mpt_eval(model, params.n_threads, n_past, embd, logits, false, mem_per_token)) {
  745. printf("%s: failed to predict\n", __func__);
  746. return 1;
  747. }
  748. t_predict_us += ggml_time_us() - t_start_us;
  749. n_past += embd.size();
  750. embd.clear();
  751. }
  752. if ((int)embd_inp.size() <= n_consumed) {
  753. // sample next token
  754. const int top_k = params.top_k;
  755. const float top_p = params.top_p;
  756. const float temp = params.temp;
  757. const int repeat_last_n = params.repeat_last_n;
  758. const float repeat_penalty = params.repeat_penalty;
  759. gpt_vocab::id id = 0;
  760. {
  761. const int64_t t_start_sample_us = ggml_time_us();
  762. id = gpt_sample_top_k_top_p_repeat(vocab, logits.data() + (logits.size() - model.hparams.n_vocab), last_n_tokens.data(), last_n_tokens.size(), top_k, top_p, temp, repeat_last_n, repeat_penalty, rng);
  763. last_n_tokens.erase(last_n_tokens.begin());
  764. last_n_tokens.push_back(id);
  765. t_sample_us += ggml_time_us() - t_start_sample_us;
  766. }
  767. // add it to the context
  768. embd.push_back(id);
  769. ++n_sampled;
  770. } else {
  771. // if here, it means we are still processing the input prompt
  772. while ((int) embd_inp.size() > n_consumed) {
  773. embd.push_back(embd_inp[n_consumed]);
  774. last_n_tokens.erase(last_n_tokens.begin());
  775. last_n_tokens.push_back(embd_inp[n_consumed]);
  776. ++n_consumed;
  777. if ((int) embd.size() >= params.n_batch) {
  778. break;
  779. }
  780. }
  781. }
  782. // display text
  783. for (auto id : embd) {
  784. printf("%s", vocab.id_to_token[id].c_str());
  785. }
  786. fflush(stdout);
  787. // end of text token
  788. if (embd.back() == 0) {
  789. break;
  790. }
  791. }
  792. // report timing
  793. {
  794. const int64_t t_main_end_us = ggml_time_us();
  795. printf("\n\n\n");
  796. printf("%s: sampled tokens = %8d\n", __func__, n_sampled);
  797. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  798. printf("%s: load time = %8.2f ms\n", __func__, t_load_us / 1000.0f);
  799. printf("%s: sample time = %8.2f ms / %.2f ms per token\n", __func__, t_sample_us / 1000.0f, t_sample_us / 1000.0f / n_sampled);
  800. printf("%s: eval time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us / 1000.0f, t_predict_us / 1000.0f / n_past);
  801. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us) / 1000.0f);
  802. }
  803. ggml_free(model.ctx);
  804. return 0;
  805. }