batched.cpp 7.3 KB

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