passkey.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <string>
  6. #include <vector>
  7. static void print_usage(int argc, char ** argv, const gpt_params & params) {
  8. gpt_params_print_usage(argc, argv, params);
  9. LOG_TEE("\nexample usage:\n");
  10. LOG_TEE("\n %s -m model.gguf --junk 250 --pos 90 --keep 32 --grp-attn-n 2 [--seed 1234]\n", argv[0]);
  11. LOG_TEE("\n");
  12. }
  13. int main(int argc, char ** argv) {
  14. gpt_params params;
  15. params.n_junk = 250;
  16. params.n_keep = 32;
  17. params.i_pos = -1;
  18. if (!gpt_params_parse(argc, argv, params)) {
  19. print_usage(argc, argv, params);
  20. return 1;
  21. }
  22. srand(params.seed == LLAMA_DEFAULT_SEED ? time(NULL) : params.seed);
  23. int n_junk = params.n_junk;
  24. int n_keep = params.n_keep;
  25. int n_grp = params.grp_attn_n;
  26. int i_pos = params.i_pos;
  27. if (i_pos == -1) {
  28. i_pos = rand() % n_junk;
  29. }
  30. const std::string prompt_prefix = "There is an important info hidden inside a lot of irrelevant text. Find it and memorize them. I will quiz you about the important information there.";
  31. const std::string prompt_suffix = " What is the pass key? The pass key is";
  32. // generate junk text
  33. params.prompt = prompt_prefix;
  34. const int passkey = rand() % 50000 + 1;
  35. for (int i = 0; i < n_junk; i++) {
  36. if (i % n_junk == i_pos) {
  37. params.prompt += " The pass key is " + std::to_string(passkey) + ". Remember it. " + std::to_string(passkey) + " is the pass key.";
  38. }
  39. params.prompt += " The grass is green. The sky is blue. The sun is yellow. Here we go. There and back again.";
  40. }
  41. params.prompt += prompt_suffix;
  42. // init LLM
  43. llama_backend_init();
  44. llama_numa_init(params.numa);
  45. // initialize the model
  46. llama_model_params model_params = llama_model_params_from_gpt_params(params);
  47. llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);
  48. if (model == NULL) {
  49. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  50. return 1;
  51. }
  52. // initialize the context
  53. llama_context_params ctx_params = llama_context_params_from_gpt_params(params);
  54. ctx_params.n_ctx = llama_n_ctx_train(model)*n_grp + n_keep;
  55. GGML_ASSERT(ctx_params.n_batch % n_grp == 0 && "n_batch must be divisible by n_grp");
  56. llama_context * ctx = llama_new_context_with_model(model, ctx_params);
  57. if (ctx == NULL) {
  58. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  59. return 1;
  60. }
  61. // tokenize the prompt
  62. std::vector<llama_token> tokens_list;
  63. tokens_list = ::llama_tokenize(ctx, params.prompt, true);
  64. // tokenize the prefix and use it as a sink
  65. const int n_tokens_prefix = ::llama_tokenize(ctx, prompt_prefix, true).size();
  66. const int n_tokens_all = tokens_list.size();
  67. // we leave a margin of 16 tokens for the generated text - it should contain just the passkey
  68. const int n_predict = 16;
  69. // total length of the sequences including the prompt
  70. const int n_len = n_tokens_all + n_predict;
  71. const int n_ctx = llama_n_ctx(ctx) - n_keep;
  72. const int n_kv_req = llama_n_ctx(ctx);
  73. const int n_batch = ctx_params.n_batch;
  74. const int n_batch_grp = ctx_params.n_batch/n_grp;
  75. LOG_TEE("\n%s: n_len = %d, n_ctx = %d, n_kv_req = %d, n_grp = %d, n_batch = %d, n_junk = %d, i_pos = %d\n", __func__, n_len, n_ctx, n_kv_req, n_grp, n_batch, n_junk, i_pos);
  76. // print the prompt token-by-token
  77. LOG_TEE("\n");
  78. LOG_TEE("prefix tokens: %d\n", n_tokens_prefix);
  79. LOG_TEE("prompt tokens: %d\n", n_tokens_all);
  80. //LOG_TEE("prompt: %s\n", params.prompt.c_str());
  81. llama_batch batch = llama_batch_init(params.n_batch, 0, 1);
  82. int n_past = 0;
  83. // fill the KV cache
  84. for (int i = 0; i < n_ctx; i += n_batch) {
  85. if (i > 0 && n_grp > 1) {
  86. // if SelfExtend is enabled, we compress the position from the last batch by a factor of n_grp
  87. const int ib = i/n_batch - 1;
  88. const int bd = n_batch_grp*(n_grp - 1);
  89. llama_kv_cache_seq_add (ctx, 0, n_past - n_batch, n_past, ib*bd);
  90. llama_kv_cache_seq_div (ctx, 0, n_past - n_batch + ib*bd, n_past + ib*bd, n_grp);
  91. llama_kv_cache_update (ctx);
  92. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  93. }
  94. llama_batch_clear(batch);
  95. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  96. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  97. }
  98. if (i + n_batch >= n_tokens_all) {
  99. batch.logits[batch.n_tokens - 1] = true;
  100. }
  101. if (llama_decode(ctx, batch) != 0) {
  102. LOG_TEE("%s: llama_decode() failed\n", __func__);
  103. return 1;
  104. }
  105. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  106. if (i + n_batch >= n_tokens_all) {
  107. break;
  108. }
  109. }
  110. for (int i = n_ctx; i < n_tokens_all; i += n_batch) {
  111. const int n_discard = n_batch;
  112. LOG_TEE("%s: shifting KV cache with %d\n", __func__, n_discard);
  113. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  114. llama_kv_cache_seq_add(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  115. //llama_kv_cache_defrag (ctx);
  116. llama_kv_cache_update (ctx);
  117. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  118. llama_batch_clear(batch);
  119. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  120. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  121. }
  122. if (i + n_batch >= n_tokens_all) {
  123. batch.logits[batch.n_tokens - 1] = true;
  124. }
  125. if (llama_decode(ctx, batch) != 0) {
  126. LOG_TEE("%s: llama_decode() failed\n", __func__);
  127. return 1;
  128. }
  129. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  130. }
  131. {
  132. const int n_discard = n_past - n_ctx + n_predict;
  133. if (n_discard > 0) {
  134. LOG_TEE("%s: shifting KV cache with %d to free space for the answer\n", __func__, n_discard);
  135. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  136. llama_kv_cache_seq_add(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  137. //llama_kv_cache_defrag (ctx);
  138. llama_kv_cache_update (ctx);
  139. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  140. }
  141. }
  142. LOG_TEE("\n");
  143. LOG_TEE("%s: passkey = %d, inserted at position %d / %d (token pos: ~%d)\n", __func__, passkey, i_pos, n_junk, (i_pos * n_tokens_all) / n_junk);
  144. LOG_TEE("\n");
  145. // main loop
  146. int n_cur = n_tokens_all;
  147. int n_decode = 0;
  148. LOG_TEE("%s", prompt_suffix.c_str());
  149. fflush(stdout);
  150. const auto t_main_start = ggml_time_us();
  151. while (n_cur <= n_len) {
  152. // sample the next token
  153. {
  154. auto n_vocab = llama_n_vocab(model);
  155. auto * logits = llama_get_logits_ith(ctx, batch.n_tokens - 1);
  156. std::vector<llama_token_data> candidates;
  157. candidates.reserve(n_vocab);
  158. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  159. candidates.emplace_back(llama_token_data{ token_id, logits[token_id], 0.0f });
  160. }
  161. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  162. // sample the most likely token
  163. const llama_token new_token_id = llama_sample_token_greedy(ctx, &candidates_p);
  164. // is it an end of generation?
  165. if (llama_token_is_eog(model, new_token_id) || n_cur == n_len) {
  166. LOG_TEE("\n");
  167. break;
  168. }
  169. LOG_TEE("%s", llama_token_to_piece(ctx, new_token_id).c_str());
  170. fflush(stdout);
  171. n_decode += 1;
  172. // prepare the next batch
  173. llama_batch_clear(batch);
  174. // push this new token for next evaluation
  175. llama_batch_add(batch, new_token_id, n_past++, { 0 }, true);
  176. }
  177. n_cur += 1;
  178. // evaluate the current batch with the transformer model
  179. if (llama_decode(ctx, batch)) {
  180. fprintf(stderr, "%s : failed to eval, return code %d\n", __func__, 1);
  181. return 1;
  182. }
  183. }
  184. LOG_TEE("\n");
  185. const auto t_main_end = ggml_time_us();
  186. LOG_TEE("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
  187. __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
  188. llama_print_timings(ctx);
  189. fprintf(stderr, "\n");
  190. llama_batch_free(batch);
  191. llama_free(ctx);
  192. llama_free_model(model);
  193. llama_backend_free();
  194. return 0;
  195. }