batched.cpp 7.8 KB

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