main.cpp 8.6 KB

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