passkey.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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_junk = %d, i_pos = %d\n", __func__, n_len, n_ctx, n_kv_req, n_grp, n_batch, n_junk, i_pos);
  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_add (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. llama_kv_cache_update (ctx);
  107. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  108. }
  109. llama_batch_clear(batch);
  110. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  111. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  112. }
  113. if (i + n_batch >= n_tokens_all) {
  114. batch.logits[batch.n_tokens - 1] = true;
  115. }
  116. if (llama_decode(ctx, batch) != 0) {
  117. LOG_TEE("%s: llama_decode() failed\n", __func__);
  118. return 1;
  119. }
  120. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  121. if (i + n_batch >= n_tokens_all) {
  122. break;
  123. }
  124. }
  125. for (int i = n_ctx; i < n_tokens_all; i += n_batch) {
  126. const int n_discard = n_batch;
  127. LOG_TEE("%s: shifting KV cache with %d\n", __func__, n_discard);
  128. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  129. llama_kv_cache_seq_add(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  130. //llama_kv_cache_defrag (ctx);
  131. llama_kv_cache_update (ctx);
  132. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  133. llama_batch_clear(batch);
  134. for (int j = 0; j < n_batch && i + j < n_tokens_all; j++) {
  135. llama_batch_add(batch, tokens_list[i + j], n_past++, { 0 }, false);
  136. }
  137. if (i + n_batch >= n_tokens_all) {
  138. batch.logits[batch.n_tokens - 1] = true;
  139. }
  140. if (llama_decode(ctx, batch) != 0) {
  141. LOG_TEE("%s: llama_decode() failed\n", __func__);
  142. return 1;
  143. }
  144. LOG_TEE("%s: processed: [%6d, %6d)\n", __func__, i, std::min(i + n_batch, n_tokens_all));
  145. }
  146. {
  147. const int n_discard = n_past - n_ctx + n_predict;
  148. if (n_discard > 0) {
  149. LOG_TEE("%s: shifting KV cache with %d to free space for the answer\n", __func__, n_discard);
  150. llama_kv_cache_seq_rm (ctx, 0, n_keep , n_keep + n_discard);
  151. llama_kv_cache_seq_add(ctx, 0, n_keep + n_discard, n_ctx, -n_discard);
  152. //llama_kv_cache_defrag (ctx);
  153. llama_kv_cache_update (ctx);
  154. n_past = llama_kv_cache_seq_pos_max(ctx, 0) + 1;
  155. }
  156. }
  157. LOG_TEE("\n");
  158. 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);
  159. LOG_TEE("\n");
  160. // main loop
  161. int n_cur = n_tokens_all;
  162. int n_decode = 0;
  163. LOG_TEE("%s", prompt_suffix.c_str());
  164. fflush(stdout);
  165. const auto t_main_start = ggml_time_us();
  166. while (n_cur <= n_len) {
  167. // sample the next token
  168. {
  169. auto n_vocab = llama_n_vocab(model);
  170. auto * logits = llama_get_logits_ith(ctx, batch.n_tokens - 1);
  171. std::vector<llama_token_data> candidates;
  172. candidates.reserve(n_vocab);
  173. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  174. candidates.emplace_back(llama_token_data{ token_id, logits[token_id], 0.0f });
  175. }
  176. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  177. // sample the most likely token
  178. const llama_token new_token_id = llama_sample_token_greedy(ctx, &candidates_p);
  179. // is it an end of stream?
  180. if (new_token_id == llama_token_eos(model) || n_cur == n_len) {
  181. LOG_TEE("\n");
  182. break;
  183. }
  184. LOG_TEE("%s", llama_token_to_piece(ctx, new_token_id).c_str());
  185. fflush(stdout);
  186. n_decode += 1;
  187. // prepare the next batch
  188. llama_batch_clear(batch);
  189. // push this new token for next evaluation
  190. llama_batch_add(batch, new_token_id, n_past++, { 0 }, true);
  191. }
  192. n_cur += 1;
  193. // evaluate the current batch with the transformer model
  194. if (llama_decode(ctx, batch)) {
  195. fprintf(stderr, "%s : failed to eval, return code %d\n", __func__, 1);
  196. return 1;
  197. }
  198. }
  199. LOG_TEE("\n");
  200. const auto t_main_end = ggml_time_us();
  201. LOG_TEE("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
  202. __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
  203. llama_print_timings(ctx);
  204. fprintf(stderr, "\n");
  205. llama_batch_free(batch);
  206. llama_free(ctx);
  207. llama_free_model(model);
  208. llama_backend_free();
  209. return 0;
  210. }