passkey.cpp 8.7 KB

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