beam-search.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #include <cassert>
  5. #include <cinttypes>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <ctime>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <string>
  13. #include <vector>
  14. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  15. #include <signal.h>
  16. #include <unistd.h>
  17. #elif defined (_WIN32)
  18. #define WIN32_LEAN_AND_MEAN
  19. #ifndef NOMINMAX
  20. # define NOMINMAX
  21. #endif
  22. #include <windows.h>
  23. #include <signal.h>
  24. #endif
  25. // Used for debugging to print out beam tokens.
  26. struct ostream_beam_view {
  27. llama_context * ctx;
  28. llama_beam_view beam_view;
  29. };
  30. std::ostream& operator<<(std::ostream& os, const ostream_beam_view & obv) {
  31. os << "p(" << obv.beam_view.p << ") eob(" << std::boolalpha << obv.beam_view.eob << ") tokens(";
  32. for (size_t i = 0 ; i < obv.beam_view.n_tokens ; ++i) {
  33. os << llama_token_to_piece(obv.ctx, obv.beam_view.tokens[i]);
  34. }
  35. return os << ')';
  36. }
  37. // Put here anything you want back in beam_search_callback().
  38. struct beam_search_callback_data {
  39. llama_context * ctx;
  40. std::vector<llama_token> response;
  41. };
  42. // In this case, end-of-beam (eob) is equivalent to end-of-sentence (eos) but this need not always be the same.
  43. // For example, eob can be flagged due to maximum token length, stop words, etc.
  44. bool is_at_eob(const beam_search_callback_data & callback_data, const llama_token * tokens, const size_t n_tokens) {
  45. return n_tokens && tokens[n_tokens-1] == llama_token_eos(callback_data.ctx);
  46. }
  47. // Function matching type llama_beam_search_callback_fn_t.
  48. // Custom callback example is called each time the beams lengths increase:
  49. // * Show progress by printing ',' following by number of convergent beam tokens if any.
  50. // * When all beams converge to a common prefix, they are made available in beams_state.beams[0].
  51. // This is also called when the stop condition is met.
  52. // Collect tokens into std::vector<llama_token> response which is pointed to by callback_data.
  53. void beam_search_callback(void * callback_data_ptr, llama_beams_state beams_state) {
  54. auto& callback_data = *static_cast<beam_search_callback_data*>(callback_data_ptr);
  55. // Mark beams as EOS as needed.
  56. for (size_t i = 0 ; i < beams_state.n_beams ; ++i) {
  57. llama_beam_view& beam_view = beams_state.beam_views[i];
  58. if (!beam_view.eob && is_at_eob(callback_data, beam_view.tokens, beam_view.n_tokens)) {
  59. beam_view.eob = true;
  60. }
  61. }
  62. printf(","); // Show progress
  63. if (const size_t n = beams_state.common_prefix_length) {
  64. callback_data.response.resize(callback_data.response.size() + n);
  65. assert(0u < beams_state.n_beams);
  66. const llama_token * tokens = beams_state.beam_views[0].tokens;
  67. std::copy(tokens, tokens + n, callback_data.response.end() - n);
  68. printf("%zu", n);
  69. }
  70. fflush(stdout);
  71. #if 1 // DEBUG: print current beams for this iteration
  72. std::cout << "\n\nCurrent beams (last_call=" << beams_state.last_call << "):\n";
  73. for (size_t i = 0 ; i < beams_state.n_beams ; ++i) {
  74. std::cout << "beams["<<i<<"]: " << ostream_beam_view{callback_data.ctx,beams_state.beam_views[i]} << std::endl;
  75. }
  76. #endif
  77. }
  78. int main(int argc, char ** argv)
  79. {
  80. gpt_params params;
  81. //params.n_gpu_layers = 200;
  82. //---------------------------------
  83. // Print help :
  84. //---------------------------------
  85. if ( argc < 2 || argv[1][0] == '-' )
  86. {
  87. printf( "Usage: %s MODEL_PATH [BEAM_WIDTH=2] [PROMPT]\n" , argv[0] );
  88. return 1 ;
  89. }
  90. //---------------------------------
  91. // Load parameters :
  92. //---------------------------------
  93. params.model = argv[1];
  94. params.n_beams = 2 < argc ? std::stoi(argv[2]) : 2;
  95. if ( argc > 3 )
  96. {
  97. params.prompt = argv[3];
  98. }
  99. if ( params.prompt.empty() )
  100. {
  101. params.prompt = "### Request:\nHow many countries are there?\n\n### Response:\n";
  102. }
  103. //---------------------------------
  104. // Init LLM :
  105. //---------------------------------
  106. llama_backend_init(params.numa);
  107. llama_model * model;
  108. llama_context * ctx;
  109. std::tie(model, ctx) = llama_init_from_gpt_params( params );
  110. if ( model == NULL )
  111. {
  112. fprintf( stderr , "%s: error: unable to load model\n" , __func__ );
  113. return 1;
  114. }
  115. //---------------------------------
  116. // Tokenize the prompt :
  117. //---------------------------------
  118. std::vector<llama_token> tokens_list = llama_tokenize(ctx, params.prompt, true);
  119. const size_t max_context_size = llama_n_ctx( ctx );
  120. const size_t max_tokens_list_size = max_context_size - 4 ;
  121. if (tokens_list.size() > max_tokens_list_size)
  122. {
  123. fprintf( stderr , "%s: error: prompt too long (%zu tokens, max %zu)\n" ,
  124. __func__ , tokens_list.size() , max_tokens_list_size );
  125. return 1;
  126. }
  127. fprintf( stderr, "\n\n" );
  128. // Print the tokens from the prompt :
  129. for( auto id : tokens_list )
  130. {
  131. std::cout << llama_token_to_piece(ctx, id);
  132. }
  133. std::cout << std::flush;
  134. int n_past = llama_get_kv_cache_token_count(ctx);
  135. if (llama_eval(ctx, tokens_list.data(), tokens_list.size(), n_past, params.n_threads))
  136. {
  137. fprintf(stderr, "%s : failed to eval prompt.\n" , __func__ );
  138. return 1;
  139. }
  140. n_past += tokens_list.size();
  141. beam_search_callback_data callback_data{ctx, {}};
  142. size_t const beam_width = static_cast<size_t>(params.n_beams);
  143. int const n_predict = 256;
  144. llama_beam_search(ctx, beam_search_callback, &callback_data, beam_width, n_past, n_predict, params.n_threads);
  145. std::cout << "\n\n";
  146. for (llama_token const token_id : callback_data.response) {
  147. std::cout << llama_token_to_piece(ctx,token_id);
  148. }
  149. std::cout << std::endl;
  150. llama_free( ctx );
  151. llama_free_model( model );
  152. llama_backend_free();
  153. return 0;
  154. }