batched.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include "sampling.h"
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <string>
  9. #include <vector>
  10. static void print_usage(int, char ** argv) {
  11. LOG("\nexample usage:\n");
  12. LOG("\n %s -m model.gguf -p \"Hello my name is\" -n 32 -np 4\n", argv[0]);
  13. LOG("\n");
  14. }
  15. int main(int argc, char ** argv) {
  16. common_params params;
  17. params.prompt = "Hello my name is";
  18. params.n_predict = 32;
  19. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_BATCHED, print_usage)) {
  20. return 1;
  21. }
  22. common_init();
  23. // number of parallel batches
  24. int n_parallel = params.n_parallel;
  25. // total length of the sequences including the prompt
  26. int n_predict = params.n_predict;
  27. // init LLM
  28. llama_backend_init();
  29. llama_numa_init(params.numa);
  30. // initialize the model
  31. llama_model_params model_params = common_model_params_to_llama(params);
  32. llama_model * model = llama_model_load_from_file(params.model.path.c_str(), model_params);
  33. if (model == NULL) {
  34. LOG_ERR("%s: error: unable to load model\n" , __func__);
  35. return 1;
  36. }
  37. const llama_vocab * vocab = llama_model_get_vocab(model);
  38. // tokenize the prompt
  39. std::vector<llama_token> tokens_list;
  40. tokens_list = common_tokenize(vocab, params.prompt, true);
  41. const int n_kv_req = tokens_list.size() + (n_predict - tokens_list.size())*n_parallel;
  42. // initialize the context
  43. llama_context_params ctx_params = common_context_params_to_llama(params);
  44. ctx_params.n_ctx = n_kv_req;
  45. ctx_params.n_batch = std::max(n_predict, n_parallel);
  46. auto sparams = llama_sampler_chain_default_params();
  47. sparams.no_perf = false;
  48. std::vector<llama_sampler_seq_config> sampler_configs;
  49. for (int32_t i = 0; i < n_parallel; ++i) {
  50. llama_sampler * smpl = llama_sampler_chain_init(sparams);
  51. llama_sampler_chain_add(smpl, llama_sampler_init_top_k(params.sampling.top_k));
  52. llama_sampler_chain_add(smpl, llama_sampler_init_top_p(params.sampling.top_p, params.sampling.min_keep));
  53. llama_sampler_chain_add(smpl, llama_sampler_init_temp (params.sampling.temp));
  54. llama_sampler_chain_add(smpl, llama_sampler_init_dist (params.sampling.seed));
  55. sampler_configs.push_back({ i, smpl });
  56. }
  57. if (params.sampling.backend_sampling) {
  58. ctx_params.samplers = sampler_configs.data();
  59. ctx_params.n_samplers = sampler_configs.size();
  60. }
  61. llama_context * ctx = llama_init_from_model(model, ctx_params);
  62. if (ctx == NULL) {
  63. LOG_ERR("%s: error: failed to create the llama_context\n" , __func__);
  64. return 1;
  65. }
  66. const int n_ctx = llama_n_ctx(ctx);
  67. LOG_INF("\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);
  68. // make sure the KV cache is big enough to hold all the prompt and generated tokens
  69. if (n_kv_req > n_ctx) {
  70. LOG_ERR("%s: error: n_kv_req (%d) > n_ctx, the required KV cache size is not big enough\n", __func__, n_kv_req);
  71. LOG_ERR("%s: either reduce n_parallel or increase n_ctx\n", __func__);
  72. return 1;
  73. }
  74. // print the prompt token-by-token
  75. LOG("\n");
  76. for (auto id : tokens_list) {
  77. LOG("%s", common_token_to_piece(ctx, id).c_str());
  78. }
  79. // create a llama_batch
  80. // we use this object to submit token data for decoding
  81. llama_batch batch = llama_batch_init(std::max(tokens_list.size(), (size_t) n_parallel), 0, n_parallel);
  82. std::vector<llama_seq_id> seq_ids(n_parallel, 0);
  83. for (int32_t i = 0; i < n_parallel; ++i) {
  84. seq_ids[i] = i;
  85. }
  86. // evaluate the initial prompt
  87. for (size_t i = 0; i < tokens_list.size(); ++i) {
  88. common_batch_add(batch, tokens_list[i], i, seq_ids, false);
  89. }
  90. GGML_ASSERT(batch.n_tokens == (int) tokens_list.size());
  91. if (llama_model_has_encoder(model)) {
  92. if (llama_encode(ctx, batch)) {
  93. LOG_ERR("%s : failed to eval\n", __func__);
  94. return 1;
  95. }
  96. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  97. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  98. decoder_start_token_id = llama_vocab_bos(vocab);
  99. }
  100. common_batch_clear(batch);
  101. common_batch_add(batch, decoder_start_token_id, 0, seq_ids, false);
  102. }
  103. // llama_decode will output logits only for the last token of the prompt
  104. batch.logits[batch.n_tokens - 1] = true;
  105. if (llama_decode(ctx, batch) != 0) {
  106. LOG_ERR("%s: llama_decode() failed\n", __func__);
  107. return 1;
  108. }
  109. //// assign the system KV cache to all parallel sequences
  110. //// this way, the parallel sequences will "reuse" the prompt tokens without having to copy them
  111. //for (int32_t i = 1; i < n_parallel; ++i) {
  112. // llama_kv_cache_seq_cp(ctx, 0, i, -1, -1);
  113. //}
  114. if (n_parallel > 1) {
  115. LOG("\n\n%s: generating %d sequences ...\n", __func__, n_parallel);
  116. }
  117. // main loop
  118. // we will store the parallel decoded sequences in this vector
  119. std::vector<std::string> streams(n_parallel);
  120. // remember the batch index of the last token for each parallel sequence
  121. // we need this to determine which logits to sample from
  122. std::vector<int32_t> i_batch(n_parallel, batch.n_tokens - 1);
  123. int n_cur = batch.n_tokens;
  124. int n_decode = 0;
  125. const auto t_main_start = ggml_time_us();
  126. while (n_cur <= n_predict) {
  127. // prepare the next batch
  128. common_batch_clear(batch);
  129. // sample the next token for each parallel sequence / stream
  130. for (int32_t i = 0; i < n_parallel; ++i) {
  131. if (i_batch[i] < 0) {
  132. // the stream has already finished
  133. continue;
  134. }
  135. const llama_token new_token_id = llama_sampler_sample(sampler_configs[i].sampler, ctx, i_batch[i]);
  136. // is it an end of generation? -> mark the stream as finished
  137. if (llama_vocab_is_eog(vocab, new_token_id) || n_cur == n_predict) {
  138. i_batch[i] = -1;
  139. LOG("\n");
  140. if (n_parallel > 1) {
  141. LOG_INF("%s: stream %d finished at n_cur = %d", __func__, i, n_cur);
  142. }
  143. continue;
  144. }
  145. // if there is only one stream, we print immediately to stdout
  146. if (n_parallel == 1) {
  147. LOG("%s", common_token_to_piece(ctx, new_token_id).c_str());
  148. }
  149. streams[i] += common_token_to_piece(ctx, new_token_id);
  150. i_batch[i] = batch.n_tokens;
  151. // push this new token for next evaluation
  152. common_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. LOG_ERR("%s : failed to eval, return code %d\n", __func__, 1);
  163. return 1;
  164. }
  165. }
  166. if (n_parallel > 1) {
  167. LOG("\n");
  168. for (int32_t i = 0; i < n_parallel; ++i) {
  169. LOG("sequence %d:\n\n%s%s\n\n", i, params.prompt.c_str(), streams[i].c_str());
  170. }
  171. }
  172. const auto t_main_end = ggml_time_us();
  173. LOG_INF("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
  174. __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
  175. LOG("\n");
  176. llama_perf_sampler_print(sampler_configs[0].sampler);
  177. llama_perf_context_print(ctx);
  178. fprintf(stderr, "\n");
  179. llama_batch_free(batch);
  180. for (auto & sampler_config : sampler_configs) {
  181. llama_sampler_free(sampler_config.sampler);
  182. }
  183. llama_free(ctx);
  184. llama_model_free(model);
  185. llama_backend_free();
  186. return 0;
  187. }