falcon-main.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. #include "ggml.h"
  2. #include "cmpnct_gpt2bpe.hpp"
  3. #include <cassert>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <cinttypes>
  8. #include <fstream>
  9. #include <map>
  10. #include <string>
  11. #include <vector>
  12. #include <thread>
  13. #include <random>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. // default hparams
  18. struct falcon_hparams {
  19. size_t n_merges = 0;
  20. size_t n_vocab = 0;
  21. uint32_t n_ctx = 0;
  22. uint32_t n_embd = 0;
  23. uint32_t n_head = 0;
  24. uint32_t n_head_kv = 1; // Needs to be 1 for 7B model
  25. uint32_t n_ff = 0;
  26. uint32_t n_block = 0;
  27. float norm_eps = 1e-5;
  28. };
  29. struct falcon_block {
  30. // normalization
  31. struct ggml_tensor* input_layernorm;
  32. struct ggml_tensor* input_layernorm_b;
  33. struct ggml_tensor* attention_norm; // Falcon-40B only
  34. struct ggml_tensor* attention_norm_b; // Falcon-40B only
  35. // attention
  36. struct ggml_tensor* query_key_value;
  37. struct ggml_tensor* wo;
  38. // ff
  39. struct ggml_tensor* ffn_up;
  40. struct ggml_tensor* ffn_down;
  41. };
  42. struct falcon_model {
  43. falcon_hparams hparams;
  44. struct ggml_tensor* tok_embeddings;
  45. struct ggml_tensor* output_norm;
  46. struct ggml_tensor* output_norm_b;
  47. struct ggml_tensor* lm_head;
  48. std::vector<falcon_block> blocks;
  49. // key + value memory
  50. struct ggml_tensor* memory_k;
  51. struct ggml_tensor* memory_v;
  52. struct gguf_context * ggufctx;
  53. struct ggml_context * ctx;
  54. struct ggml_context * kvctx;
  55. std::map<std::string, struct ggml_tensor*> tensors;
  56. };
  57. struct gpt_params {
  58. int32_t seed = -1; // RNG seed
  59. int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
  60. uint32_t n_predict = 200; // new tokens to predict
  61. uint32_t n_batch = 512; // batch size for prompt processing
  62. // sampling parameters
  63. int32_t top_k = 40;
  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. std::string model = ""; // model path
  69. std::string prompt = "";
  70. std::string token_test = "";
  71. bool interactive = false;
  72. int32_t interactive_port = -1;
  73. int32_t n_gpu_layers = 0;
  74. };
  75. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  76. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  77. fprintf(stderr, "\n");
  78. fprintf(stderr, "options:\n");
  79. fprintf(stderr, " -h, --help show this help message and exit\n");
  80. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
  81. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  82. fprintf(stderr, " -ngl N, --gpu-layers N number of layers to offload to GPU on supported models (default: %d)\n", params.n_gpu_layers);
  83. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  84. fprintf(stderr, " prompt to start generation with (default: random)\n");
  85. fprintf(stderr, " -f FNAME, --file FNAME\n");
  86. fprintf(stderr, " load prompt from a file\n");
  87. fprintf(stderr, " -tt TOKEN_TEST, --token_test TOKEN_TEST\n");
  88. fprintf(stderr, " test tokenization\n");
  89. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
  90. fprintf(stderr, " --top_k N top-k sampling, 0 = n_vocab (default: %d)\n", params.top_k);
  91. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
  92. fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
  93. fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled)\n", params.repeat_last_n);
  94. fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.2f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  95. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  96. fprintf(stderr, " -m FNAME, --model FNAME\n");
  97. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  98. fprintf(stderr, "\n");
  99. }
  100. // Function to check if the next argument exists
  101. std::string get_next_arg(int& i, int argc, char** argv, const std::string& flag, gpt_params& params) {
  102. if (i + 1 < argc && argv[i + 1][0] != '-') {
  103. return argv[++i];
  104. } else {
  105. fprintf(stderr, "error: %s requires one argument.\n", flag.c_str());
  106. gpt_print_usage(argc, argv, params);
  107. exit(0);
  108. }
  109. }
  110. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  111. for (int i = 1; i < argc; i++) {
  112. std::string arg = argv[i];
  113. if (arg == "-s" || arg == "--seed") {
  114. params.seed = std::stoi(get_next_arg(i, argc, argv, arg, params));
  115. } else if (arg == "-t" || arg == "--threads") {
  116. params.n_threads = std::stoi(get_next_arg(i, argc, argv, arg, params));
  117. } else if (arg == "-ngl" || arg == "--gpu-layers" || arg == "--n-gpu-layers") {
  118. params.n_gpu_layers = std::stoi(get_next_arg(i, argc, argv, arg, params));
  119. } else if (arg == "-p" || arg == "--prompt") {
  120. params.prompt = get_next_arg(i, argc, argv, arg, params);
  121. } else if (arg == "-n" || arg == "--n_predict") {
  122. params.n_predict = std::stoi(get_next_arg(i, argc, argv, arg, params));
  123. } else if (arg == "--top_k") {
  124. params.top_k = std::stoi(get_next_arg(i, argc, argv, arg, params));
  125. } else if (arg == "--top_p") {
  126. params.top_p = std::stof(get_next_arg(i, argc, argv, arg, params));
  127. } else if (arg == "--temp") {
  128. params.temp = std::stof(get_next_arg(i, argc, argv, arg, params));
  129. } else if (arg == "--repeat-last-n") {
  130. params.repeat_last_n = std::stoi(get_next_arg(i, argc, argv, arg, params));
  131. } else if (arg == "--repeat-penalty") {
  132. params.repeat_penalty = std::stof(get_next_arg(i, argc, argv, arg, params));
  133. } else if (arg == "-b" || arg == "--batch_size") {
  134. params.n_batch= std::stoi(get_next_arg(i, argc, argv, arg, params));
  135. } else if (arg == "-m" || arg == "--model") {
  136. params.model = get_next_arg(i, argc, argv, arg, params);
  137. } else if (arg == "-i" || arg == "--interactive") {
  138. params.interactive = true;
  139. } else if (arg == "-ip" || arg == "--interactive-port") {
  140. params.interactive = true;
  141. params.interactive_port = std::stoi(get_next_arg(i, argc, argv, arg, params));
  142. } else if (arg == "-h" || arg == "--help") {
  143. gpt_print_usage(argc, argv, params);
  144. exit(0);
  145. } else if (arg == "-f" || arg == "--file") {
  146. get_next_arg(i, argc, argv, arg, params);
  147. std::ifstream file(argv[i]);
  148. if (!file) {
  149. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  150. break;
  151. }
  152. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  153. if (params.prompt.back() == '\n') {
  154. params.prompt.pop_back();
  155. }
  156. } else if (arg == "-tt" || arg == "--token_test") {
  157. params.token_test = get_next_arg(i, argc, argv, arg, params);
  158. }
  159. else {
  160. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  161. gpt_print_usage(argc, argv, params);
  162. exit(0);
  163. }
  164. }
  165. return true;
  166. }
  167. gpt2bpe_vocab::id sample_top_k_top_p_repeat(
  168. const gpt2bpe_vocab & vocab,
  169. const float * logits,
  170. const int32_t * last_n_tokens_data,
  171. size_t last_n_tokens_data_size,
  172. int top_k,
  173. double top_p,
  174. double temp,
  175. int repeat_last_n,
  176. float repeat_penalty,
  177. std::mt19937 & rng) {
  178. int n_logits = vocab.id_to_token.size();
  179. const auto * plogits = logits;
  180. const auto last_n_tokens = std::vector<int32_t>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_data_size);
  181. if (temp <= 0) {
  182. // select the token with the highest logit directly
  183. float max_logit = plogits[0];
  184. gpt2bpe_vocab::id max_id = 0;
  185. for (int i = 1; i < n_logits; ++i) {
  186. if (plogits[i] > max_logit) {
  187. max_logit = plogits[i];
  188. max_id = i;
  189. }
  190. }
  191. return max_id;
  192. }
  193. std::vector<std::pair<double, gpt2bpe_vocab::id>> logits_id;
  194. logits_id.reserve(n_logits);
  195. {
  196. const float scale = 1.0f/temp;
  197. for (int i = 0; i < n_logits; ++i) {
  198. // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
  199. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  200. if (repeat_last_n > 0 && std::find(last_n_tokens.end()-repeat_last_n, last_n_tokens.end(), i) != last_n_tokens.end()) {
  201. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  202. if (plogits[i] < 0.0f) {
  203. logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
  204. } else {
  205. logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
  206. }
  207. } else {
  208. logits_id.push_back(std::make_pair(plogits[i]*scale, i));
  209. }
  210. }
  211. }
  212. // find the top K tokens
  213. std::partial_sort(
  214. logits_id.begin(),
  215. logits_id.begin() + top_k, logits_id.end(),
  216. [](const std::pair<double, gpt2bpe_vocab::id> & a, const std::pair<double, gpt2bpe_vocab::id> & b) {
  217. return a.first > b.first;
  218. });
  219. logits_id.resize(top_k);
  220. double maxl = -INFINITY;
  221. for (const auto & kv : logits_id) {
  222. maxl = std::max(maxl, kv.first);
  223. }
  224. // compute probs for the top K tokens
  225. std::vector<double> probs;
  226. probs.reserve(logits_id.size());
  227. double sum = 0.0;
  228. for (const auto & kv : logits_id) {
  229. double p = exp(kv.first - maxl);
  230. probs.push_back(p);
  231. sum += p;
  232. }
  233. // normalize the probs
  234. for (auto & p : probs) {
  235. p /= sum;
  236. }
  237. if (top_p < 1.0f) {
  238. double cumsum = 0.0f;
  239. for (int i = 0; i < top_k; i++) {
  240. cumsum += probs[i];
  241. if (cumsum >= top_p) {
  242. top_k = i + 1;
  243. probs.resize(top_k);
  244. logits_id.resize(top_k);
  245. break;
  246. }
  247. }
  248. cumsum = 1.0/cumsum;
  249. for (int i = 0; i < (int) probs.size(); i++) {
  250. probs[i] *= cumsum;
  251. }
  252. }
  253. // printf("\n");
  254. // for (int i = 0; i < (int) probs.size(); i++) {
  255. // for (int i = 0; i < 10; i++) {
  256. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  257. // }
  258. std::discrete_distribution<> dist(probs.begin(), probs.end());
  259. int idx = dist(rng);
  260. return logits_id[idx].second;
  261. }
  262. struct ggml_tensor * get_tensor_ex( struct ggml_context * ctx, std::string name){
  263. struct ggml_tensor * cur = ggml_get_tensor(ctx, name.c_str());
  264. if( cur == NULL ) {
  265. printf("%s: tensor '%s' not found!\n", __func__, name.c_str());
  266. } else {
  267. // printf("%s: n_dims = %d, name = '%s'\n", __func__, cur->n_dims, cur->name);
  268. }
  269. return cur;
  270. }
  271. // load the model's weights from a file
  272. bool falcon_model_load(const std::string & fname, falcon_model & model, gpt2bpe_vocab & vocab) {
  273. printf("%s: loading model from '%s'..\n", __func__, fname.c_str());
  274. model.ctx = NULL;
  275. struct gguf_init_params ggufparams = {
  276. /*.no_alloc = */ false,
  277. /*.ctx = */ &model.ctx,
  278. };
  279. auto & ggufctx = model.ggufctx;
  280. ggufctx = gguf_init_from_file(fname.c_str(), ggufparams);
  281. if (!ggufctx) {
  282. fprintf(stderr, "%s: gguf_init_from_file() failed\n", __func__);
  283. return false;
  284. }
  285. printf("%s: gguf version = %d\n", __func__, gguf_get_version(ggufctx));
  286. printf("%s: gguf alignment = %zu\n", __func__, gguf_get_alignment(ggufctx));
  287. printf("%s: gguf data offset = %zu\n", __func__, gguf_get_data_offset(ggufctx));
  288. // print all kv
  289. #if 0
  290. {
  291. const int n_kv = gguf_get_n_kv(ggufctx);
  292. printf("%s: n_kv: %d\n", __func__, n_kv);
  293. for (int i = 0; i < n_kv; ++i) {
  294. const char * key = gguf_get_key(ggufctx, i);
  295. printf("%s: kv[%d]: key = %s\n", __func__, i, key);
  296. }
  297. }
  298. #endif
  299. // print some standard metadata
  300. {
  301. int keyidx;
  302. keyidx = gguf_find_key(ggufctx, "general.name");
  303. if (keyidx != -1) { printf("%s: model name = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  304. keyidx = gguf_find_key(ggufctx, "general.description");
  305. if (keyidx != -1) { printf("%s: model description = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  306. keyidx = gguf_find_key(ggufctx, "general.author");
  307. if (keyidx != -1) { printf("%s: model author = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  308. keyidx = gguf_find_key(ggufctx, "general.license");
  309. if (keyidx != -1) { printf("%s: model license = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  310. keyidx = gguf_find_key(ggufctx, "general.architecture");
  311. if (keyidx != -1) { printf("%s: model architecture = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  312. keyidx = gguf_find_key(ggufctx, "general.file_type");
  313. if (keyidx != -1) { printf("%s: model file type = %" PRIu32 "\n", __func__, gguf_get_val_u32(ggufctx, keyidx)); }
  314. keyidx = gguf_find_key(ggufctx, "gptneox.tensor_data_layout");
  315. if (keyidx != -1) { printf("%s: model data layout = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  316. keyidx = gguf_find_key(ggufctx, "general.source.huggingface.repository");
  317. if (keyidx != -1) { printf("%s: model source HF repo = %s\n", __func__, gguf_get_val_str(ggufctx, keyidx)); }
  318. }
  319. // check required metadata
  320. {
  321. int keyidx;
  322. // check model architecture kv
  323. keyidx = gguf_find_key(ggufctx, "general.architecture");
  324. if (keyidx != -1) {
  325. if ( strcmp(gguf_get_val_str(ggufctx, keyidx), "falcon") != 0) {
  326. printf("%s: model architecture not supported!\n", __func__);
  327. return false;
  328. }
  329. } else {
  330. printf("%s: gguf model architecture not found!\n", __func__);
  331. return false;
  332. }
  333. // check model tensor data layout kv
  334. keyidx = gguf_find_key(ggufctx, "falcon.tensor_data_layout");
  335. if (keyidx != -1) {
  336. if ( strcmp(gguf_get_val_str(ggufctx, keyidx), "jploski") != 0) {
  337. printf("%s: model tensor data layout not supported!\n", __func__);
  338. return false;
  339. }
  340. } else {
  341. printf("%s: gguf model tensor data layout not found!\n", __func__);
  342. return false;
  343. }
  344. }
  345. // load hparams
  346. {
  347. auto & hparams = model.hparams;
  348. bool ok = true;
  349. int keyidx;
  350. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.context_length");
  351. if (keyidx != -1) { hparams.n_ctx = gguf_get_val_u32(ggufctx, keyidx); } else { ok = false; } }
  352. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.embedding_length");
  353. if (keyidx != -1) { hparams.n_embd = gguf_get_val_u32(ggufctx, keyidx); } else { ok = false; } }
  354. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.attention.head_count");
  355. if (keyidx != -1) { hparams.n_head = gguf_get_val_u32(ggufctx, keyidx); } else { ok = false; } }
  356. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.feed_forward_length");
  357. if (keyidx != -1) { hparams.n_ff = gguf_get_val_u32(ggufctx, keyidx); } else { ok = false; } }
  358. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.block_count");
  359. if (keyidx != -1) { hparams.n_block = gguf_get_val_u32(ggufctx, keyidx); } else { ok = false; } }
  360. if (ok) { keyidx = gguf_find_key(ggufctx, "falcon.attention.layer_norm_epsilon");
  361. if (keyidx != -1) { hparams.norm_eps= gguf_get_val_f32(ggufctx, keyidx); } else { ok = false; } }
  362. if (!ok) {
  363. fprintf(stderr, "%s: required hparam missing!\n", __func__);
  364. return false;
  365. }
  366. keyidx = gguf_find_key(ggufctx, "falcon.attention.head_count_kv");
  367. if (keyidx != -1) { hparams.n_head_kv = gguf_get_val_u32(ggufctx, keyidx); }
  368. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  369. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  370. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  371. printf("%s: n_head_kv = %d\n", __func__, hparams.n_head_kv);
  372. printf("%s: n_block = %d\n", __func__, hparams.n_block);
  373. printf("%s: norm_eps = %g\n", __func__, hparams.norm_eps);
  374. }
  375. // load vocab
  376. {
  377. auto & hparams = model.hparams;
  378. int keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.model");
  379. if (keyidx != -1) {
  380. if ( strcmp(gguf_get_val_str(ggufctx, keyidx), "gpt2") != 0) {
  381. printf("%s: tokenizer model not supported!\n", __func__);
  382. return false;
  383. }
  384. } else {
  385. printf("%s: tokenizer model not found!\n", __func__);
  386. return false;
  387. }
  388. int tokens_keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.tokens");
  389. if (tokens_keyidx == -1) {
  390. printf("%s: gpt2 tokenizer vocab not found!\n", __func__);
  391. return false;
  392. }
  393. int merges_keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.merges");
  394. if (merges_keyidx == -1) {
  395. printf("%s: gpt2 tokenizer merges not found!\n", __func__);
  396. return false;
  397. }
  398. hparams.n_vocab = gguf_get_arr_n(ggufctx,tokens_keyidx);
  399. hparams.n_merges = gguf_get_arr_n(ggufctx,merges_keyidx);
  400. printf("%s: gpt2 tokenizer vocab = %zu\n", __func__, hparams.n_vocab);
  401. printf("%s: gpt2 tokenizer merges = %zu\n", __func__, hparams.n_merges);
  402. for (size_t i = 0; i < hparams.n_vocab; i++) {
  403. std::string word = gguf_get_arr_str(ggufctx, tokens_keyidx, i);
  404. // printf("token %d = '%s'\n",i,word.c_str() );
  405. vocab.token_to_id[word] = i;
  406. vocab.id_to_token[i] = word;
  407. if( vocab.id_to_token[i] == "\n" ) {
  408. vocab.linefeed_id = i;
  409. }
  410. }
  411. std::vector<std::pair<std::string, std::string>> bpe_merges;
  412. for (size_t i = 0; i < hparams.n_merges; i++) {
  413. std::string word = gguf_get_arr_str(ggufctx, merges_keyidx, i);
  414. // Split the merges
  415. std::string first, second;
  416. size_t pos = word.find(' ', 1); // Start the search from the second character
  417. if (pos != std::string::npos) {
  418. first = word.substr(0, pos);
  419. second = word.substr(pos + 1);
  420. }
  421. bpe_merges.push_back(std::make_pair(first, second));
  422. }
  423. vocab.populate_bpe_ranks(bpe_merges);
  424. keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.bos_token_id"); if( keyidx != -1 ) { vocab.special_bos_id = (int32_t)gguf_get_val_u32(ggufctx, keyidx); }
  425. keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.eos_token_id"); if( keyidx != -1 ) { vocab.special_eos_id = (int32_t)gguf_get_val_u32(ggufctx, keyidx); }
  426. keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.unknown_token_id"); if( keyidx != -1 ) { vocab.special_unk_id = (int32_t)gguf_get_val_u32(ggufctx, keyidx); }
  427. keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.separator_token_id"); if( keyidx != -1 ) { vocab.special_sep_id = (int32_t)gguf_get_val_u32(ggufctx, keyidx); }
  428. keyidx = gguf_find_key(ggufctx, "tokenizer.ggml.padding_token_id"); if( keyidx != -1 ) { vocab.special_pad_id = (int32_t)gguf_get_val_u32(ggufctx, keyidx); }
  429. if( vocab.special_bos_id != -1 ) { printf("%s: BOS token = %d '%s'\n", __func__, vocab.special_bos_id, vocab.id_to_token[vocab.special_bos_id].c_str() ); }
  430. if( vocab.special_eos_id != -1 ) { printf("%s: EOS token = %d '%s'\n", __func__, vocab.special_eos_id, vocab.id_to_token[vocab.special_eos_id].c_str() ); }
  431. if( vocab.special_unk_id != -1 ) { printf("%s: UNK token = %d '%s'\n", __func__, vocab.special_unk_id, vocab.id_to_token[vocab.special_unk_id].c_str() ); }
  432. if( vocab.special_sep_id != -1 ) { printf("%s: SEP token = %d '%s'\n", __func__, vocab.special_sep_id, vocab.id_to_token[vocab.special_sep_id].c_str() ); }
  433. if( vocab.special_pad_id != -1 ) { printf("%s: PAD token = %d '%s'\n", __func__, vocab.special_pad_id, vocab.id_to_token[vocab.special_pad_id].c_str() ); }
  434. if( vocab.linefeed_id != -1 ) { printf("%s: LF token = %d\n", __func__, vocab.linefeed_id ); }
  435. }
  436. auto & ctx = model.ctx;
  437. size_t ctx_size = ggml_get_mem_size(ctx);
  438. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  439. // print tensor info
  440. #if 0
  441. {
  442. const int n_tensors = gguf_get_n_tensors(ggufctx);
  443. printf("%s: n_tensors: %d\n", __func__, n_tensors);
  444. for (int i = 0; i < n_tensors; ++i) {
  445. const char * name = gguf_get_tensor_name (ggufctx, i);
  446. const size_t offset = gguf_get_tensor_offset(ggufctx, i);
  447. printf("%s: tensor[%d]: name = %s, offset = %zu\n", __func__, i, name, offset);
  448. }
  449. }
  450. #endif
  451. // prepare memory for the weights
  452. {
  453. auto & hparams = model.hparams;
  454. const int n_block = hparams.n_block;
  455. model.blocks.resize(n_block);
  456. model.tok_embeddings = ggml_get_tensor(ctx, "token_embd.weight");
  457. model.output_norm = ggml_get_tensor(ctx, "output_norm.weight");
  458. model.output_norm_b = ggml_get_tensor(ctx, "output_norm.bias");
  459. model.lm_head = ggml_get_tensor(ctx, "output.weight");
  460. // map by name
  461. model.tensors["token_embd.weight"] = model.tok_embeddings;
  462. model.tensors["output_norm.weight"] = model.output_norm;
  463. model.tensors["output_norm.bias"] = model.output_norm_b;
  464. model.tensors["output.weight"] = model.lm_head;
  465. for (int i = 0; i < n_block; ++i) {
  466. auto& block = model.blocks[i];
  467. std::string blocknamestart = "blk." + std::to_string(i) + ".";
  468. block.input_layernorm = get_tensor_ex(ctx, blocknamestart + "attn_norm.weight" );
  469. block.input_layernorm_b = get_tensor_ex(ctx, blocknamestart + "attn_norm.bias" );
  470. if ( hparams.n_head_kv == 8 ) { // Falcon-40B
  471. block.attention_norm = get_tensor_ex(ctx, blocknamestart + "attn_norm_2.weight" );
  472. block.attention_norm_b = get_tensor_ex(ctx, blocknamestart + "attn_norm_2.bias" );
  473. }
  474. // query_key_value shape for config.multi_query == True:
  475. block.query_key_value = get_tensor_ex(ctx, blocknamestart + "attn_qkv.weight" );
  476. block.wo = get_tensor_ex(ctx, blocknamestart + "attn_output.weight" );
  477. block.ffn_up = get_tensor_ex(ctx, blocknamestart + "ffn_up.weight" );
  478. block.ffn_down = get_tensor_ex(ctx, blocknamestart + "ffn_down.weight" );
  479. // map by name
  480. if ( hparams.n_head_kv == 8 ) { // Falcon-40B
  481. // Falcon-40B:
  482. model.tensors[blocknamestart + "attn_norm.weight"] = block.input_layernorm;
  483. model.tensors[blocknamestart + "attn_norm.bias"] = block.input_layernorm_b;
  484. model.tensors[blocknamestart + "attn_norm_2.weight"] = block.attention_norm;
  485. model.tensors[blocknamestart + "attn_norm_2.bias"] = block.attention_norm_b;
  486. } else {
  487. // Falcon-7B:
  488. model.tensors[blocknamestart + "attn_norm.weight"] = block.input_layernorm;
  489. model.tensors[blocknamestart + "attn_norm.bias"] = block.input_layernorm_b;
  490. }
  491. model.tensors[blocknamestart + "attn_qkv.weight"] = block.query_key_value;
  492. model.tensors[blocknamestart + "attn_output.weight"] = block.wo;
  493. model.tensors[blocknamestart + "ffn_up.weight"] = block.ffn_up;
  494. model.tensors[blocknamestart + "ffn_down.weight"] = block.ffn_down;
  495. }
  496. }
  497. // key + value memory
  498. {
  499. const auto & kvctx = model.kvctx;
  500. const auto & hparams = model.hparams;
  501. const int n_block = hparams.n_block;
  502. const int n_ctx = hparams.n_ctx;
  503. const int n_embd = hparams.n_embd;
  504. const int64_t n_mem = n_block*n_ctx;
  505. const int64_t n_elements = n_embd*n_mem;
  506. // create the ggml context
  507. {
  508. struct ggml_init_params params = {
  509. /*.mem_size =*/ size_t(n_elements*4+ggml_tensor_overhead()*2),
  510. /*.mem_buffer =*/ NULL,
  511. /*.no_alloc =*/ false,
  512. };
  513. model.kvctx = ggml_init(params);
  514. if (!model.kvctx) {
  515. fprintf(stderr, "%s: kv ggml_init() failed\n", __func__);
  516. return false;
  517. }
  518. }
  519. model.memory_k = ggml_new_tensor_1d(kvctx, GGML_TYPE_F16, n_elements);
  520. model.memory_v = ggml_new_tensor_1d(kvctx, GGML_TYPE_F16, n_elements);
  521. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  522. printf("%s: memory_size = %8.2f MB, n_mem = %" PRId64 "\n", __func__, memory_size/1024.0/1024.0, n_mem);
  523. }
  524. return true;
  525. }
  526. // evaluate the transformer
  527. //
  528. // - model: the model
  529. // - n_threads: number of threads to use
  530. // - n_past: the context size so far
  531. // - embd_inp: the embeddings of the tokens in the context
  532. // - embd_w: the predicted logits for the next token
  533. //
  534. bool falcon_eval(
  535. const falcon_model & model,
  536. const int n_threads,
  537. const int n_past,
  538. const std::vector<gpt2bpe_vocab::id> & embd_inp,
  539. std::vector<float> & embd_w,
  540. size_t & mem_per_token) {
  541. const int N = embd_inp.size();
  542. const auto & hparams = model.hparams;
  543. const int n_embd = hparams.n_embd;
  544. const int n_block = hparams.n_block;
  545. const int n_ctx = hparams.n_ctx;
  546. const int n_head = hparams.n_head;
  547. const int n_head_kv = hparams.n_head_kv;
  548. const int n_vocab = hparams.n_vocab;
  549. const size_t head_dim = n_embd / n_head;
  550. static size_t buf_size = 256u*1024*1024;
  551. static void * buf = malloc(buf_size);
  552. // use 2 scratch buffers
  553. // TODO: very hacky solution - reimplement in a more elegant way
  554. static size_t scr0_size = 256u*1024*1024;
  555. static void * scr0 = malloc(scr0_size);
  556. static size_t scr1_size = 256u*1024*1024;
  557. static void * scr1 = malloc(scr1_size);
  558. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  559. const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
  560. //printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  561. // reallocate
  562. buf_size = buf_size_new;
  563. buf = realloc(buf, buf_size);
  564. if (buf == nullptr) {
  565. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  566. return false;
  567. }
  568. }
  569. struct ggml_init_params params = {
  570. /*.mem_size =*/ buf_size,
  571. /*.mem_buffer =*/ buf,
  572. /*.no_alloc =*/ false,
  573. };
  574. struct ggml_context * ctx0 = ggml_init(params);
  575. struct ggml_cgraph gf = {};
  576. // gf.n_threads = n_threads;
  577. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  578. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  579. // wte
  580. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  581. // struct ggml_tensor* repeat_dummy = ggml_new_tensor_3d(ctx0, inpL->type, head_dim, N + n_past, n_head);
  582. ggml_type wtype = GGML_TYPE_F32;
  583. const int sizeof_wtype = ggml_type_sizef(wtype);
  584. for (int il = 0; il < n_block; ++il) {
  585. struct ggml_tensor * cur;
  586. struct ggml_tensor * layernorm_output;
  587. ggml_set_scratch(ctx0, { 0, scr0_size, scr0, });
  588. // self-attention
  589. {
  590. layernorm_output = ggml_norm(ctx0, inpL);
  591. layernorm_output = ggml_add(ctx0,
  592. ggml_mul(ctx0,
  593. ggml_repeat(ctx0, model.blocks[il].input_layernorm, layernorm_output),
  594. layernorm_output),
  595. ggml_repeat(ctx0, model.blocks[il].input_layernorm_b, layernorm_output));
  596. if ( hparams.n_head_kv == 8 ) { // Falcon-40B
  597. cur = ggml_norm(ctx0, inpL);
  598. cur = ggml_add(ctx0,
  599. ggml_mul(ctx0,
  600. ggml_repeat(ctx0, model.blocks[il].attention_norm, cur),
  601. cur),
  602. ggml_repeat(ctx0, model.blocks[il].attention_norm_b, cur));
  603. }
  604. else { // Falcon 7B
  605. cur = layernorm_output;
  606. }
  607. // compute QKV
  608. cur = ggml_mul_mat(ctx0, model.blocks[il].query_key_value, cur);
  609. // Note that the strides for Kcur, Vcur are set up so that the
  610. // resulting views are misaligned with the tensor's storage
  611. // (by applying the K/V offset we shift the tensor's original
  612. // view to stick out behind the viewed QKV tensor's allocated
  613. // memory, so to say). This is ok because no actual accesses
  614. // happen to that out-of-range memory, but it can require some
  615. // trickery when trying to accurately dump these views for
  616. // debugging.
  617. struct ggml_tensor * Qcur = ggml_view_3d(
  618. ctx0, cur, head_dim, n_head, N,
  619. head_dim * sizeof_wtype,
  620. head_dim * (n_head + 2 * n_head_kv) * sizeof_wtype,
  621. 0);
  622. struct ggml_tensor * Kcur = ggml_view_3d(
  623. ctx0, cur, head_dim, n_head_kv, N,
  624. head_dim * sizeof_wtype,
  625. head_dim * (n_head + 2 * n_head_kv) * sizeof_wtype,
  626. head_dim * n_head * sizeof_wtype);
  627. struct ggml_tensor * Vcur = ggml_view_3d(
  628. ctx0, cur, head_dim, n_head_kv, N,
  629. head_dim * sizeof_wtype,
  630. head_dim * (n_head + 2 * n_head_kv) * sizeof_wtype,
  631. head_dim * (n_head + n_head_kv) * sizeof_wtype);
  632. // using mode = 2 for neox mode
  633. Qcur = ggml_rope_inplace(ctx0, Qcur, n_past, head_dim, 2, 0);
  634. Kcur = ggml_rope_inplace(ctx0, Kcur, n_past, head_dim, 2, 0);
  635. // store key and value to memory
  636. {
  637. struct ggml_tensor* k = ggml_view_1d(
  638. ctx0, model.memory_k, N * n_head_kv * head_dim,
  639. (ggml_element_size(model.memory_k) * n_head_kv * head_dim) *
  640. (il * n_ctx + n_past));
  641. struct ggml_tensor* v = ggml_view_1d(
  642. ctx0, model.memory_v, N * n_head_kv * head_dim,
  643. (ggml_element_size(model.memory_v) * n_head_kv * head_dim) *
  644. (il * n_ctx + n_past));
  645. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  646. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  647. }
  648. struct ggml_tensor * K = ggml_permute(
  649. ctx0,
  650. ggml_reshape_3d(
  651. ctx0,
  652. ggml_view_1d(ctx0, model.memory_k, (n_past + N) * n_head_kv * head_dim,
  653. il * n_ctx *
  654. ggml_element_size(model.memory_k) *
  655. n_head_kv *
  656. head_dim),
  657. head_dim, n_head_kv, n_past + N),
  658. 0, 2, 1, 3);
  659. // K * Q
  660. // K = ggml_cont(ctx0, ggml_repeat2(ctx0, K, repeat_dummy));
  661. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  662. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  663. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  664. struct ggml_tensor * KQ_scaled =
  665. ggml_scale_inplace(ctx0,
  666. KQ,
  667. ggml_new_f32(ctx0, 1.0f/sqrt(float(head_dim)))
  668. );
  669. // KQ_masked = mask_past(KQ_scaled)
  670. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  671. // KQ = soft_max(KQ_masked)
  672. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  673. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  674. struct ggml_tensor* V = ggml_permute(
  675. ctx0,
  676. ggml_reshape_3d(
  677. ctx0,
  678. ggml_view_1d(ctx0, model.memory_v, (n_past + N) * n_head_kv * head_dim,
  679. il * n_ctx *
  680. ggml_element_size(model.memory_v) *
  681. n_head_kv *
  682. head_dim),
  683. head_dim, n_head_kv, n_past + N),
  684. 0, 2, 1, 3);
  685. // V = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_repeat2(ctx0, V, repeat_dummy)));
  686. V = ggml_cont(ctx0, ggml_transpose(ctx0, V));
  687. // KQV = transpose(V) * KQ_soft_max
  688. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  689. // KQV_merged = KQV.permute(0, 2, 1, 3)
  690. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  691. // cur = KQV_merged.contiguous().view(n_embd, N)
  692. cur = ggml_cpy(ctx0,
  693. KQV_merged,
  694. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  695. // projection
  696. {
  697. cur = ggml_mul_mat(ctx0,
  698. model.blocks[il].wo,
  699. cur);
  700. }
  701. }
  702. ggml_set_scratch(ctx0, { 0, scr1_size, scr1, });
  703. struct ggml_tensor* inpFF = layernorm_output;
  704. struct ggml_tensor* attn_out = ggml_cpy(
  705. ctx0, cur, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  706. {
  707. cur = ggml_mul_mat(ctx0, model.blocks[il].ffn_up, inpFF);
  708. cur = ggml_gelu(ctx0, cur);
  709. cur = ggml_mul_mat(ctx0, model.blocks[il].ffn_down, cur);
  710. }
  711. cur = ggml_add(ctx0, cur, attn_out);
  712. cur = ggml_add(ctx0, cur, inpL);
  713. // input for next layer
  714. inpL = cur;
  715. }
  716. ggml_set_scratch(ctx0, { 0, scr0_size, scr0, });
  717. // norm
  718. {
  719. inpL = ggml_norm(ctx0, inpL);
  720. // inpL = ln_f_g*inpL + ln_f_b
  721. inpL = ggml_add(ctx0,
  722. ggml_mul(ctx0,
  723. ggml_repeat(ctx0, model.output_norm, inpL),
  724. inpL),
  725. ggml_repeat(ctx0, model.output_norm_b, inpL));
  726. }
  727. ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  728. // lm_head
  729. {
  730. inpL = ggml_mul_mat(ctx0, model.lm_head, inpL);
  731. //inpL = ggml_add(ctx0,
  732. // ggml_repeat(ctx0, model.lmh_b, inpL),
  733. // inpL);
  734. }
  735. // logits -> probs
  736. //inpL = ggml_soft_max_inplace(ctx0, inpL);
  737. // run the computation
  738. ggml_build_forward_expand(&gf, inpL);
  739. // ggml_graph_compute (ctx0, &gf);
  740. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  741. //if (n_past%100 == 0) {
  742. // ggml_graph_print (&gf);
  743. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  744. //}
  745. // return result for just the last token
  746. embd_w.resize(n_vocab);
  747. memcpy(embd_w.data(), (float *)ggml_get_data(inpL) + (n_vocab * (N - 1)), sizeof(float) * n_vocab);
  748. if (mem_per_token == 0) {
  749. mem_per_token = ggml_used_mem(ctx0)/N;
  750. }
  751. //printf("used_mem = %zu\n", ggml_used_mem(ctx0));
  752. ggml_free(ctx0);
  753. return true;
  754. }
  755. int main(int argc, char ** argv) {
  756. ggml_time_init();
  757. const int64_t t_main_start_us = ggml_time_us();
  758. gpt_params params;
  759. if (!gpt_params_parse(argc, argv, params)) {
  760. return 1;
  761. }
  762. int64_t t_load_us = 0;
  763. gpt2bpe_vocab vocab;
  764. falcon_model model;
  765. // load the model
  766. {
  767. const int64_t t_start_us = ggml_time_us();
  768. if (!falcon_model_load(params.model, model, vocab)) {
  769. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  770. return 1;
  771. }
  772. t_load_us = ggml_time_us() - t_start_us;
  773. }
  774. if (params.seed < 0) {
  775. params.seed = time(NULL);
  776. }
  777. if (params.top_k == 0) {
  778. params.top_k = model.hparams.n_vocab;
  779. }
  780. printf("%s: seed = %d\n", __func__, params.seed);
  781. printf("%s: temp = %.3f\n", __func__, params.temp);
  782. printf("%s: top_k = %d\n", __func__, params.top_k);
  783. printf("%s: top_p = %.3f\n", __func__, params.top_p);
  784. printf("%s: repeat_last_n = %d\n", __func__, params.repeat_last_n);
  785. printf("%s: repeat_penalty = %.3f\n", __func__, params.repeat_penalty);
  786. std::mt19937 rng(params.seed);
  787. if (params.prompt.empty()) {
  788. params.prompt = "Once upon";
  789. }
  790. std::vector<int32_t> last_n_tokens(model.hparams.n_ctx);
  791. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  792. int n_past = 0;
  793. int64_t t_sample_us = 0;
  794. int64_t t_predict_us = 0;
  795. std::vector<float> logits;
  796. // tokenize the prompt
  797. std::vector<gpt2bpe_vocab::id> embd_inp = gpt2bpe_tokenize(vocab, params.prompt,false, false);
  798. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  799. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  800. // for (size_t i = 0; i < embd_inp.size(); i++) {
  801. // printf("%s: token[%zu] = %6d, %s\n", __func__, i, embd_inp[i], vocab.id_to_token[embd_inp[i]].c_str());
  802. // }
  803. if( model.hparams.n_ctx < params.n_predict+embd_inp.size() ) {
  804. params.n_predict = model.hparams.n_ctx-embd_inp.size();
  805. }
  806. printf("%s: n_predict = %d\n", __func__, params.n_predict);
  807. printf("\n");
  808. std::vector<gpt2bpe_vocab::id> embd;
  809. // determine the required inference memory per token:
  810. size_t mem_per_token = 0;
  811. falcon_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  812. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  813. // predict
  814. if (embd.size() > 0) {
  815. const int64_t t_start_us = ggml_time_us();
  816. if (!falcon_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  817. printf("Failed to predict\n");
  818. return 1;
  819. }
  820. t_predict_us += ggml_time_us() - t_start_us;
  821. }
  822. n_past += embd.size();
  823. embd.clear();
  824. if (i >= embd_inp.size()) {
  825. // sample next token
  826. const int top_k = params.top_k;
  827. const float top_p = params.top_p;
  828. const float temp = params.temp;
  829. const int repeat_last_n = params.repeat_last_n;
  830. const float repeat_penalty = params.repeat_penalty;
  831. const int n_vocab = model.hparams.n_vocab;
  832. gpt2bpe_vocab::id id = 0;
  833. {
  834. const int64_t t_start_sample_us = ggml_time_us();
  835. id = sample_top_k_top_p_repeat(vocab, logits.data() + (logits.size() - n_vocab), last_n_tokens.data(), last_n_tokens.size(), top_k, top_p, temp, repeat_last_n, repeat_penalty, rng);
  836. last_n_tokens.erase(last_n_tokens.begin());
  837. last_n_tokens.push_back(id);
  838. t_sample_us += ggml_time_us() - t_start_sample_us;
  839. }
  840. // add it to the context
  841. embd.push_back(id);
  842. } else {
  843. // if here, it means we are still processing the input prompt
  844. for (size_t k = i; k < embd_inp.size(); k++) {
  845. embd.push_back(embd_inp[k]);
  846. if (embd.size() > params.n_batch) {
  847. break;
  848. }
  849. }
  850. i += embd.size() - 1;
  851. }
  852. // display text
  853. for (auto id : embd) {
  854. printf("%s", vocab.id_to_token[id].c_str() );
  855. }
  856. fflush(stdout);
  857. // end of text token
  858. if (vocab.special_eos_id != -1 && embd.back() == vocab.special_eos_id) {
  859. break;
  860. }
  861. }
  862. // report timing
  863. {
  864. const int64_t t_main_end_us = ggml_time_us();
  865. printf("\n\n");
  866. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  867. printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  868. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  869. 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);
  870. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  871. }
  872. ggml_free(model.ctx);
  873. return 0;
  874. }