batched.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <string>
  7. #include <vector>
  8. int main(int argc, char ** argv) {
  9. gpt_params params;
  10. if (argc == 1 || argv[1][0] == '-') {
  11. printf("usage: %s MODEL_PATH [PROMPT] [PARALLEL] [LEN]\n" , argv[0]);
  12. return 1 ;
  13. }
  14. // number of parallel batches
  15. int n_parallel = 1;
  16. // total length of the sequences including the prompt
  17. int n_len = 32;
  18. if (argc >= 2) {
  19. params.model = argv[1];
  20. }
  21. if (argc >= 3) {
  22. params.prompt = argv[2];
  23. }
  24. if (argc >= 4) {
  25. n_parallel = std::atoi(argv[3]);
  26. }
  27. if (argc >= 5) {
  28. n_len = std::atoi(argv[4]);
  29. }
  30. if (params.prompt.empty()) {
  31. params.prompt = "Hello my name is";
  32. }
  33. // init LLM
  34. llama_backend_init(params.numa);
  35. // initialize the model
  36. llama_model_params model_params = llama_model_default_params();
  37. // model_params.n_gpu_layers = 99; // offload all layers to the GPU
  38. llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);
  39. if (model == NULL) {
  40. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  41. return 1;
  42. }
  43. // tokenize the prompt
  44. std::vector<llama_token> tokens_list;
  45. tokens_list = ::llama_tokenize(model, params.prompt, true);
  46. const int n_kv_req = tokens_list.size() + (n_len - tokens_list.size())*n_parallel;
  47. // initialize the context
  48. llama_context_params ctx_params = llama_context_default_params();
  49. ctx_params.seed = 1234;
  50. ctx_params.n_ctx = n_kv_req;
  51. ctx_params.n_batch = std::max(n_len, n_parallel);
  52. ctx_params.n_threads = params.n_threads;
  53. ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  54. llama_context * ctx = llama_new_context_with_model(model, ctx_params);
  55. if (ctx == NULL) {
  56. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  57. return 1;
  58. }
  59. const int n_ctx = llama_n_ctx(ctx);
  60. LOG_TEE("\n%s: n_len = %d, n_ctx = %d, n_batch = %d, n_parallel = %d, n_kv_req = %d\n", __func__, n_len, n_ctx, ctx_params.n_batch, n_parallel, n_kv_req);
  61. // make sure the KV cache is big enough to hold all the prompt and generated tokens
  62. if (n_kv_req > n_ctx) {
  63. LOG_TEE("%s: error: n_kv_req (%d) > n_ctx, the required KV cache size is not big enough\n", __func__, n_kv_req);
  64. LOG_TEE("%s: either reduce n_parallel or increase n_ctx\n", __func__);
  65. return 1;
  66. }
  67. // print the prompt token-by-token
  68. fprintf(stderr, "\n");
  69. for (auto id : tokens_list) {
  70. fprintf(stderr, "%s", llama_token_to_piece(ctx, id).c_str());
  71. }
  72. fflush(stderr);
  73. // create a llama_batch
  74. // we use this object to submit token data for decoding
  75. llama_batch batch = llama_batch_init(std::max(tokens_list.size(), (size_t)n_parallel), 0, 1);
  76. // evaluate the initial prompt
  77. for (size_t i = 0; i < tokens_list.size(); ++i) {
  78. llama_batch_add(batch, tokens_list[i], i, { 0 }, false);
  79. }
  80. GGML_ASSERT(batch.n_tokens == (int) tokens_list.size());
  81. // llama_decode will output logits only for the last token of the prompt
  82. batch.logits[batch.n_tokens - 1] = true;
  83. if (llama_decode(ctx, batch) != 0) {
  84. LOG_TEE("%s: llama_decode() failed\n", __func__);
  85. return 1;
  86. }
  87. // assign the system KV cache to all parallel sequences
  88. // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them
  89. for (int32_t i = 1; i < n_parallel; ++i) {
  90. llama_kv_cache_seq_cp(ctx, 0, i, 0, batch.n_tokens);
  91. }
  92. if (n_parallel > 1) {
  93. LOG_TEE("\n\n%s: generating %d sequences ...\n", __func__, n_parallel);
  94. }
  95. // main loop
  96. // we will store the parallel decoded sequences in this vector
  97. std::vector<std::string> streams(n_parallel);
  98. // remember the batch index of the last token for each parallel sequence
  99. // we need this to determine which logits to sample from
  100. std::vector<int32_t> i_batch(n_parallel, batch.n_tokens - 1);
  101. int n_cur = batch.n_tokens;
  102. int n_decode = 0;
  103. const auto t_main_start = ggml_time_us();
  104. while (n_cur <= n_len) {
  105. // prepare the next batch
  106. llama_batch_clear(batch);
  107. // sample the next token for each parallel sequence / stream
  108. for (int32_t i = 0; i < n_parallel; ++i) {
  109. if (i_batch[i] < 0) {
  110. // the stream has already finished
  111. continue;
  112. }
  113. auto n_vocab = llama_n_vocab(model);
  114. auto * logits = llama_get_logits_ith(ctx, i_batch[i]);
  115. std::vector<llama_token_data> candidates;
  116. candidates.reserve(n_vocab);
  117. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  118. candidates.emplace_back(llama_token_data{ token_id, logits[token_id], 0.0f });
  119. }
  120. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  121. const int top_k = 40;
  122. const float top_p = 0.9f;
  123. const float temp = 0.4f;
  124. llama_sample_top_k(ctx, &candidates_p, top_k, 1);
  125. llama_sample_top_p(ctx, &candidates_p, top_p, 1);
  126. llama_sample_temp (ctx, &candidates_p, temp);
  127. const llama_token new_token_id = llama_sample_token(ctx, &candidates_p);
  128. //const llama_token new_token_id = llama_sample_token_greedy(ctx, &candidates_p);
  129. // is it an end of stream? -> mark the stream as finished
  130. if (new_token_id == llama_token_eos(ctx) || n_cur == n_len) {
  131. i_batch[i] = -1;
  132. LOG_TEE("\n");
  133. if (n_parallel > 1) {
  134. LOG_TEE("%s: stream %d finished at n_cur = %d", __func__, i, n_cur);
  135. }
  136. continue;
  137. }
  138. // if there is only one stream, we print immediately to stdout
  139. if (n_parallel == 1) {
  140. LOG_TEE("%s", llama_token_to_piece(ctx, new_token_id).c_str());
  141. fflush(stdout);
  142. }
  143. streams[i] += llama_token_to_piece(ctx, new_token_id);
  144. i_batch[i] = batch.n_tokens;
  145. // push this new token for next evaluation
  146. llama_batch_add(batch, new_token_id, n_cur, { i }, true);
  147. n_decode += 1;
  148. }
  149. // all streams are finished
  150. if (batch.n_tokens == 0) {
  151. break;
  152. }
  153. n_cur += 1;
  154. // evaluate the current batch with the transformer model
  155. if (llama_decode(ctx, batch)) {
  156. fprintf(stderr, "%s : failed to eval, return code %d\n", __func__, 1);
  157. return 1;
  158. }
  159. }
  160. LOG_TEE("\n");
  161. if (n_parallel > 1) {
  162. LOG_TEE("\n");
  163. for (int32_t i = 0; i < n_parallel; ++i) {
  164. LOG_TEE("sequence %d:\n\n%s%s\n\n", i, params.prompt.c_str(), streams[i].c_str());
  165. }
  166. }
  167. const auto t_main_end = ggml_time_us();
  168. LOG_TEE("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
  169. __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
  170. llama_print_timings(ctx);
  171. fprintf(stderr, "\n");
  172. llama_batch_free(batch);
  173. llama_free(ctx);
  174. llama_free_model(model);
  175. llama_backend_free();
  176. return 0;
  177. }