debug.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #include "debug.h"
  2. #include "arg.h"
  3. #include "common.h"
  4. #include "log.h"
  5. #include "llama.h"
  6. #include <cstdlib>
  7. #include <string>
  8. #include <vector>
  9. #include <filesystem>
  10. #include <fstream>
  11. #include <regex>
  12. static void print_usage(int /*argc*/, char ** argv) {
  13. const std::string usage_template = R"(
  14. example usage:
  15. Print tensors:
  16. {prog} -m model.gguf -p "Hello my name is" --verbose
  17. The tensors to be printed can be filtered with --tensor-filter option.
  18. Save logits/embeddings:
  19. {prog} -m model.gguf -p "Hello my name is" --save-logits
  20. Add --embedding to save embeddings)" "\n";
  21. // Fix the source code indentation above that is introduced by the raw string literal.
  22. std::string usage = std::regex_replace(usage_template, std::regex("\\n {8}"), "\n");
  23. usage = std::regex_replace(usage, std::regex("\\{prog\\}"), argv[0]);
  24. LOG("%s\n", usage.c_str());
  25. }
  26. static bool has_pooling(llama_context * ctx) {
  27. switch (llama_pooling_type(ctx)) {
  28. case LLAMA_POOLING_TYPE_NONE:
  29. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  30. return false;
  31. default:
  32. return true;
  33. }
  34. }
  35. struct output_data {
  36. float * data_ptr = nullptr;
  37. int data_size = 0;
  38. std::string type_suffix;
  39. std::vector<float> embd_norm;
  40. std::string prompt;
  41. std::vector<llama_token> tokens;
  42. output_data(llama_context * ctx, const llama_model * model, const common_params & params) {
  43. const llama_vocab * vocab = llama_model_get_vocab(model);
  44. const bool add_bos = llama_vocab_get_add_bos(vocab);
  45. tokens = common_tokenize(ctx, params.prompt, add_bos);
  46. prompt = params.prompt;
  47. if (params.embedding) {
  48. const int n_embd = llama_model_n_embd_out(model);
  49. const bool pooling = has_pooling(ctx);
  50. const int n_embd_count = pooling ? 1 : tokens.size();
  51. const int n_floats = n_embd * n_embd_count;
  52. float * embd_raw = pooling ? llama_get_embeddings_seq(ctx, 0) : llama_get_embeddings(ctx);
  53. if (embd_raw == nullptr) {
  54. throw std::runtime_error("failed to get embeddings from the model");
  55. }
  56. LOG_DBG("pooling_enabled: %s\n", pooling ? "true" : "false");
  57. LOG_DBG("n_embd: %d\n", n_embd);
  58. LOG_DBG("n_floats: %d\n", n_floats);
  59. LOG_DBG("n_embd_count: %d\n", n_embd_count);
  60. data_ptr = embd_raw;
  61. data_size = n_floats;
  62. type_suffix = "-embeddings";
  63. if (params.embd_normalize >= 0) {
  64. embd_norm.resize(n_floats);
  65. for (int i = 0; i < n_embd_count; i++) {
  66. common_embd_normalize(embd_raw+i*n_embd, embd_norm.data()+i*n_embd, n_embd, params.embd_normalize);
  67. }
  68. data_ptr = embd_norm.data();
  69. }
  70. } else {
  71. const float * logits = llama_get_logits_ith(ctx, tokens.size() - 1);
  72. const int n_logits = llama_vocab_n_tokens(vocab);
  73. data_ptr = const_cast<float*>(logits);
  74. data_size = n_logits;
  75. type_suffix = "";
  76. }
  77. }
  78. };
  79. static void save_output_data(const output_data & output, const std::string & model_name, const std::string & output_dir) {
  80. std::filesystem::create_directory(output_dir);
  81. auto base_path = std::filesystem::path{output_dir} / ("llamacpp-" + model_name + output.type_suffix);
  82. // Save logits/embeddings to binary file.
  83. {
  84. std::filesystem::path filepath{base_path.string() + ".bin"};
  85. std::ofstream file{filepath, std::ios::binary};
  86. if (!file) {
  87. throw std::runtime_error("failed to open binary output file: " + filepath.string());
  88. }
  89. file.write(reinterpret_cast<const char*>(output.data_ptr), output.data_size * sizeof(float));
  90. LOG("Data saved to %s\n", filepath.c_str());
  91. }
  92. // Save logits/embeddings to text file.
  93. {
  94. std::filesystem::path filepath{base_path.string() + ".txt"};
  95. std::ofstream file{filepath};
  96. if (!file) {
  97. throw std::runtime_error("failed to open text output file: " + filepath.string());
  98. }
  99. for (int i = 0; i < output.data_size; i++) {
  100. file << i << ": " << output.data_ptr[i] << '\n';
  101. }
  102. LOG("Data saved to %s\n", filepath.c_str());
  103. }
  104. // Save prompt and tokens to text file.
  105. {
  106. std::filesystem::path filepath{base_path.string() + "-prompt.txt"};
  107. std::ofstream file{filepath};
  108. if (!file) {
  109. throw std::runtime_error("failed to open prompt output file: " + filepath.string());
  110. }
  111. file << "prompt: " << output.prompt << '\n';
  112. file << "n_tokens: " << output.tokens.size() << '\n';
  113. file << "token ids: ";
  114. for (size_t i = 0; i < output.tokens.size(); i++) {
  115. file << output.tokens[i];
  116. if (i + 1 < output.tokens.size()) {
  117. file << ", ";
  118. }
  119. }
  120. file << '\n';
  121. LOG("Prompt saved to %s\n", filepath.c_str());
  122. }
  123. // Save token ids to binary file.
  124. {
  125. std::filesystem::path filepath{base_path.string() + "-tokens.bin"};
  126. std::ofstream file{filepath, std::ios::binary};
  127. if (!file) {
  128. throw std::runtime_error("failed to open tokens binary file: " + filepath.string());
  129. }
  130. file.write(reinterpret_cast<const char*>(output.tokens.data()), output.tokens.size() * sizeof(llama_token));
  131. LOG("Tokens saved to %s\n", filepath.c_str());
  132. }
  133. }
  134. static void print_tokenized_prompt(llama_context * ctx, const std::vector<llama_token> & tokens, const std::string & prompt) {
  135. const llama_model * model = llama_get_model(ctx);
  136. const llama_vocab * vocab = llama_model_get_vocab(model);
  137. LOG("Model add_bos: %s\n", llama_vocab_get_add_bos(vocab) ? "true" : "false");
  138. LOG("Input prompt: \"%s\"\n", prompt.c_str());
  139. LOG("Token ids (%zu):\n", tokens.size());
  140. for (auto id : tokens) {
  141. std::string piece(128, '\0');
  142. int n = llama_token_to_piece(vocab, id, piece.data(), piece.size(), 0, true);
  143. if (n < 0) {
  144. LOG_ERR("failed to convert token %d to piece\n", id);
  145. continue;
  146. }
  147. piece.resize(n);
  148. LOG("%s(%d) ", piece.c_str(), id);
  149. }
  150. LOG("\n");
  151. }
  152. static bool run(llama_context * ctx, const common_params & params) {
  153. const llama_model * model = llama_get_model(ctx);
  154. const llama_vocab * vocab = llama_model_get_vocab(model);
  155. const bool add_bos = llama_vocab_get_add_bos(vocab);
  156. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, add_bos);
  157. if (tokens.empty()) {
  158. LOG_ERR("%s : there are not input tokens to process - (try to provide a prompt with '-p')\n", __func__);
  159. return false;
  160. }
  161. if (llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size()))) {
  162. LOG_ERR("%s : failed to eval\n", __func__);
  163. return false;
  164. }
  165. print_tokenized_prompt(ctx, tokens, params.prompt);
  166. if (params.save_logits) {
  167. output_data output {ctx, model, params};
  168. std::filesystem::path model_path{params.model.path};
  169. std::string model_name{model_path.stem().string()};
  170. save_output_data(output, model_name, params.logits_output_dir);
  171. }
  172. return true;
  173. }
  174. int main(int argc, char ** argv) {
  175. common_params params;
  176. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_DEBUG, print_usage)) {
  177. return 1;
  178. }
  179. common_init();
  180. llama_backend_init();
  181. llama_numa_init(params.numa);
  182. base_callback_data cb_data(params, params.tensor_filter);
  183. auto llama_init = common_init_from_params(params);
  184. auto * model = llama_init->model();
  185. auto * ctx = llama_init->context();
  186. if (model == nullptr || ctx == nullptr) {
  187. LOG_ERR("%s : failed to init\n", __func__);
  188. return 1;
  189. }
  190. {
  191. LOG_INF("\n");
  192. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  193. LOG_INF("\n");
  194. }
  195. if (!run(ctx, params)) {
  196. return 1;
  197. }
  198. LOG("\n");
  199. llama_perf_context_print(ctx);
  200. llama_backend_free();
  201. return 0;
  202. }