passkey.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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();
  54. llama_numa_init(params.numa);
  55. // initialize the model
  56. llama_model_params model_params = llama_model_default_params();
  57. model_params.n_gpu_layers = 99; // offload all layers to the GPU
  58. llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);
  59. if (model == NULL) {
  60. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  61. return 1;
  62. }
  63. // initialize the context
  64. llama_context_params ctx_params = llama_context_default_params();
  65. ctx_params.seed = seed;
  66. ctx_params.n_ctx = llama_n_ctx_train(model)*n_grp + n_keep;
  67. ctx_params.n_batch = 512;
  68. ctx_params.n_threads = params.n_threads;
  69. ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  70. GGML_ASSERT(ctx_params.n_batch % n_grp == 0 && "n_batch must be divisible by n_grp");
  71. llama_context * ctx = llama_new_context_with_model(model, ctx_params);
  72. if (ctx == NULL) {
  73. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  74. return 1;
  75. }
  76. // tokenize the prompt
  77. std::vector<llama_token> tokens_list;
  78. tokens_list = ::llama_tokenize(ctx, params.prompt, true);
  79. // tokenize the prefix and use it as a sink
  80. const int n_tokens_prefix = ::llama_tokenize(ctx, prompt_prefix, true).size();
  81. const int n_tokens_all = tokens_list.size();
  82. // we leave a margin of 16 tokens for the generated text - it should contain just the passkey
  83. const int n_predict = 16;
  84. // total length of the sequences including the prompt
  85. const int n_len = n_tokens_all + n_predict;
  86. const int n_ctx = llama_n_ctx(ctx) - n_keep;
  87. const int n_kv_req = llama_n_ctx(ctx);
  88. const int n_batch = ctx_params.n_batch;
  89. const int n_batch_grp = ctx_params.n_batch/n_grp;
  90. 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);
  91. // print the prompt token-by-token
  92. LOG_TEE("\n");
  93. LOG_TEE("prefix tokens: %d\n", n_tokens_prefix);
  94. LOG_TEE("prompt tokens: %d\n", n_tokens_all);
  95. //LOG_TEE("prompt: %s\n", params.prompt.c_str());
  96. llama_batch batch = llama_batch_init(512, 0, 1);
  97. int n_past = 0;
  98. // fill the KV cache
  99. for (int i = 0; i < n_ctx; i += n_batch) {
  100. if (i > 0 && n_grp > 1) {
  101. // if SelfExtend is enabled, we compress the position from the last batch by a factor of n_grp
  102. const int ib = i/n_batch - 1;
  103. const int bd = n_batch_grp*(n_grp - 1);
  104. llama_kv_cache_seq_shift(ctx, 0, n_past - n_batch, n_past, ib*bd);
  105. llama_kv_cache_seq_div (ctx, 0, n_past - n_batch + ib*bd, n_past + ib*bd, n_grp);
  106. n_past -= bd;
  107. }
  108. llama_batch_clear(batch);
  109. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  110. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  111. }
  112. if (i + n_batch >= n_tokens_all) {
  113. batch.logits[batch.n_tokens - 1] = true;
  114. }
  115. if (llama_decode(ctx, batch) != 0) {
  116. LOG_TEE("%s: llama_decode() failed\n", __func__);
  117. return 1;
  118. }
  119. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  120. if (i + n_batch >= n_tokens_all) {
  121. break;
  122. }
  123. }
  124. for (int i = n_ctx; i < n_tokens_all; i += n_batch) {
  125. const int n_discard = n_batch;
  126. LOG_TEE("%s: shifting KV cache with %d\n", __func__, n_discard);
  127. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  128. llama_kv_cache_seq_shift(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  129. n_past -= n_discard;
  130. llama_batch_clear(batch);
  131. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  132. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  133. }
  134. if (i + n_batch >= n_tokens_all) {
  135. batch.logits[batch.n_tokens - 1] = true;
  136. }
  137. if (llama_decode(ctx, batch) != 0) {
  138. LOG_TEE("%s: llama_decode() failed\n", __func__);
  139. return 1;
  140. }
  141. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  142. }
  143. {
  144. const int n_discard = n_past - n_ctx + n_predict;
  145. if (n_discard > 0) {
  146. LOG_TEE("%s: shifting KV cache with %d to free space for the answer\n", __func__, n_discard);
  147. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  148. llama_kv_cache_seq_shift(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  149. n_past -= n_discard;
  150. }
  151. }
  152. LOG_TEE("\n");
  153. 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);
  154. LOG_TEE("\n");
  155. // main loop
  156. int n_cur = n_tokens_all;
  157. int n_decode = 0;
  158. LOG_TEE("%s", prompt_suffix.c_str());
  159. fflush(stdout);
  160. const auto t_main_start = ggml_time_us();
  161. while (n_cur <= n_len) {
  162. // sample the next token
  163. {
  164. auto n_vocab = llama_n_vocab(model);
  165. auto * logits = llama_get_logits_ith(ctx, batch.n_tokens - 1);
  166. std::vector<llama_token_data> candidates;
  167. candidates.reserve(n_vocab);
  168. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  169. candidates.emplace_back(llama_token_data{ token_id, logits[token_id], 0.0f });
  170. }
  171. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  172. // sample the most likely token
  173. const llama_token new_token_id = llama_sample_token_greedy(ctx, &candidates_p);
  174. // is it an end of stream?
  175. if (new_token_id == llama_token_eos(model) || n_cur == n_len) {
  176. LOG_TEE("\n");
  177. break;
  178. }
  179. LOG_TEE("%s", llama_token_to_piece(ctx, new_token_id).c_str());
  180. fflush(stdout);
  181. n_decode += 1;
  182. // prepare the next batch
  183. llama_batch_clear(batch);
  184. // push this new token for next evaluation
  185. llama_batch_add(batch, new_token_id, n_past++, { 0 }, true);
  186. }
  187. n_cur += 1;
  188. // evaluate the current batch with the transformer model
  189. if (llama_decode(ctx, batch)) {
  190. fprintf(stderr, "%s : failed to eval, return code %d\n", __func__, 1);
  191. return 1;
  192. }
  193. }
  194. LOG_TEE("\n");
  195. const auto t_main_end = ggml_time_us();
  196. LOG_TEE("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
  197. __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
  198. llama_print_timings(ctx);
  199. fprintf(stderr, "\n");
  200. llama_batch_free(batch);
  201. llama_free(ctx);
  202. llama_free_model(model);
  203. llama_backend_free();
  204. return 0;
  205. }