debug.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include "ggml.h"
  6. #include <cmath>
  7. #include <cstdint>
  8. #include <cstdlib>
  9. #include <string>
  10. #include <vector>
  11. #include <filesystem>
  12. #include <fstream>
  13. #include <regex>
  14. static void print_usage(int, char ** argv) {
  15. const std::string usage_template = R"(
  16. example usage:
  17. Print tensors:
  18. {prog} -m model.gguf -p "Hello my name is" --verbose
  19. The tensors to be printed can be filtered with --tensor-filter option.
  20. Save logits/embeddings:
  21. {prog} -m model.gguf -p "Hello my name is" --save-logits
  22. Add --embedding to save embeddings)" "\n";
  23. // Fix the source code indentation above that is introduced by the raw string literal.
  24. std::string usage = std::regex_replace(usage_template, std::regex("\\n {8}"), "\n");
  25. usage = std::regex_replace(usage, std::regex("\\{prog\\}"), argv[0]);
  26. LOG("%s\n", usage.c_str());
  27. }
  28. static bool ggml_debug(struct ggml_tensor * t, bool ask, void * user_data);
  29. struct callback_data {
  30. std::vector<uint8_t> data;
  31. std::vector<std::regex> tensor_filters;
  32. callback_data() = default;
  33. callback_data(common_params & params, const std::vector<std::string> & filter_patterns) {
  34. for (const auto & pattern : filter_patterns) {
  35. try {
  36. std::string anchored_pattern = "^" + pattern;
  37. tensor_filters.emplace_back(anchored_pattern, std::regex::optimize);
  38. } catch (const std::regex_error & e) {
  39. throw std::runtime_error("Invalid regex pattern '" + pattern + "': " + e.what());
  40. }
  41. }
  42. params.cb_eval = ggml_debug;
  43. params.cb_eval_user_data = this;
  44. }
  45. };
  46. static bool has_pooling(llama_context * ctx) {
  47. switch (llama_pooling_type(ctx)) {
  48. case LLAMA_POOLING_TYPE_NONE:
  49. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  50. return false;
  51. default:
  52. return true;
  53. }
  54. }
  55. struct output_data {
  56. float * data_ptr = nullptr;
  57. int data_size = 0;
  58. std::string type_suffix;
  59. std::vector<float> embd_norm;
  60. std::string prompt;
  61. std::vector<llama_token> tokens;
  62. output_data(llama_context * ctx, const llama_model * model, const common_params & params) {
  63. const llama_vocab * vocab = llama_model_get_vocab(model);
  64. const bool add_bos = llama_vocab_get_add_bos(vocab);
  65. tokens = common_tokenize(ctx, params.prompt, add_bos);
  66. prompt = params.prompt;
  67. if (params.embedding) {
  68. const int n_embd = llama_model_n_embd_out(model);
  69. const bool pooling = has_pooling(ctx);
  70. const int n_embd_count = pooling ? 1 : tokens.size();
  71. const int n_floats = n_embd * n_embd_count;
  72. float * embd_raw = pooling ? llama_get_embeddings_seq(ctx, 0) : llama_get_embeddings(ctx);
  73. if (embd_raw == nullptr) {
  74. throw std::runtime_error("failed to get embeddings from the model");
  75. }
  76. LOG_DBG("pooling_enabled: %s\n", pooling ? "true" : "false");
  77. LOG_DBG("n_embd: %d\n", n_embd);
  78. LOG_DBG("n_floats: %d\n", n_floats);
  79. LOG_DBG("n_embd_count: %d\n", n_embd_count);
  80. data_ptr = embd_raw;
  81. data_size = n_floats;
  82. type_suffix = "-embeddings";
  83. if (params.embd_normalize >= 0) {
  84. embd_norm.resize(n_floats);
  85. for (int i = 0; i < n_embd_count; i++) {
  86. common_embd_normalize(embd_raw+i*n_embd, embd_norm.data()+i*n_embd, n_embd, params.embd_normalize);
  87. }
  88. data_ptr = embd_norm.data();
  89. }
  90. } else {
  91. const float * logits = llama_get_logits_ith(ctx, tokens.size() - 1);
  92. const int n_logits = llama_vocab_n_tokens(vocab);
  93. data_ptr = const_cast<float*>(logits);
  94. data_size = n_logits;
  95. type_suffix = "";
  96. }
  97. }
  98. };
  99. static std::string ggml_ne_string(const ggml_tensor * t) {
  100. std::string str;
  101. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  102. str += std::to_string(t->ne[i]);
  103. if (i + 1 < GGML_MAX_DIMS) {
  104. str += ", ";
  105. }
  106. }
  107. return str;
  108. }
  109. static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
  110. union {
  111. float f;
  112. uint32_t i;
  113. } u;
  114. u.i = (uint32_t)h.bits << 16;
  115. return u.f;
  116. }
  117. static float ggml_get_float_value(const uint8_t * data, ggml_type type,
  118. const size_t * nb, size_t i0, size_t i1, size_t i2, size_t i3) {
  119. size_t i = i3 * nb[3] + i2 * nb[2] + i1 * nb[1] + i0 * nb[0];
  120. switch (type) {
  121. case GGML_TYPE_F16:
  122. return ggml_fp16_to_fp32(*(const ggml_fp16_t *) &data[i]);
  123. case GGML_TYPE_F32:
  124. return *(const float *) &data[i];
  125. case GGML_TYPE_I64:
  126. return (float) *(const int64_t *) &data[i];
  127. case GGML_TYPE_I32:
  128. return (float) *(const int32_t *) &data[i];
  129. case GGML_TYPE_I16:
  130. return (float) *(const int16_t *) &data[i];
  131. case GGML_TYPE_I8:
  132. return (float) *(const int8_t *) &data[i];
  133. case GGML_TYPE_BF16:
  134. return ggml_compute_bf16_to_fp32(*(const ggml_bf16_t *) &data[i]);
  135. default:
  136. GGML_ABORT("fatal error");
  137. }
  138. }
  139. static void ggml_print_tensor(uint8_t * data, ggml_type type, const int64_t * ne, const size_t * nb, int64_t n) {
  140. GGML_ASSERT(n > 0);
  141. float sum = 0;
  142. float sum_sq = 0.0;
  143. for (int64_t i3 = 0; i3 < ne[3]; i3++) {
  144. for (int64_t i2 = 0; i2 < ne[2]; i2++) {
  145. for (int64_t i1 = 0; i1 < ne[1]; i1++) {
  146. for (int64_t i0 = 0; i0 < ne[0]; i0++) {
  147. const float v = ggml_get_float_value(data, type, nb, i0, i1, i2, i3);
  148. sum += v;
  149. sum_sq += v * v;
  150. }
  151. }
  152. }
  153. }
  154. for (int64_t i3 = 0; i3 < ne[3]; i3++) {
  155. LOG_DBG(" [\n");
  156. for (int64_t i2 = 0; i2 < ne[2]; i2++) {
  157. if (i2 == n && ne[2] > 2*n) {
  158. LOG_DBG(" ..., \n");
  159. i2 = ne[2] - n;
  160. }
  161. LOG_DBG(" [\n");
  162. for (int64_t i1 = 0; i1 < ne[1]; i1++) {
  163. if (i1 == n && ne[1] > 2*n) {
  164. LOG_DBG(" ..., \n");
  165. i1 = ne[1] - n;
  166. }
  167. LOG_DBG(" [");
  168. for (int64_t i0 = 0; i0 < ne[0]; i0++) {
  169. if (i0 == n && ne[0] > 2*n) {
  170. LOG_DBG("..., ");
  171. i0 = ne[0] - n;
  172. }
  173. const float v = ggml_get_float_value(data, type, nb, i0, i1, i2, i3);
  174. LOG_DBG("%12.4f", v);
  175. if (i0 < ne[0] - 1) {
  176. LOG_DBG(", ");
  177. }
  178. }
  179. LOG_DBG("],\n");
  180. }
  181. LOG_DBG(" ],\n");
  182. }
  183. LOG_DBG(" ]\n");
  184. LOG_DBG(" sum = %f\n", sum);
  185. LOG_DBG(" sum_sq = %f\n", sum_sq);
  186. }
  187. if (std::isnan(sum)) {
  188. LOG_ERR("encountered NaN - aborting\n");
  189. exit(0);
  190. }
  191. }
  192. /**
  193. * GGML operations callback during the graph execution.
  194. *
  195. * @param t current tensor
  196. * @param ask when ask is true, the scheduler wants to know if we are interested in data from this tensor
  197. * if we return true, a follow-up call will be made with ask=false in which we can do the actual collection.
  198. * see ggml_backend_sched_eval_callback
  199. * @param user_data user data to pass at each call back
  200. * @return true to receive data or continue the graph, false otherwise
  201. */
  202. static bool ggml_debug(struct ggml_tensor * t, bool ask, void * user_data) {
  203. auto * cb_data = (callback_data *) user_data;
  204. const struct ggml_tensor * src0 = t->src[0];
  205. const struct ggml_tensor * src1 = t->src[1];
  206. if (ask) {
  207. return true; // Always retrieve data
  208. }
  209. bool matches_filter = cb_data->tensor_filters.empty();
  210. if (!matches_filter) {
  211. for (const auto & filter : cb_data->tensor_filters) {
  212. if (std::regex_search(t->name, filter)) {
  213. matches_filter = true;
  214. break;
  215. }
  216. }
  217. }
  218. char src1_str[128] = {0};
  219. if (src1) {
  220. snprintf(src1_str, sizeof(src1_str), "%s{%s}", src1->name, ggml_ne_string(src1).c_str());
  221. }
  222. if (matches_filter) {
  223. LOG_DBG("%s: %24s = (%s) %10s(%s{%s}, %s}) = {%s}\n", __func__,
  224. t->name,
  225. ggml_type_name(t->type),
  226. ggml_op_desc(t),
  227. src0->name,
  228. ggml_ne_string(src0).c_str(),
  229. src1 ? src1_str : "",
  230. ggml_ne_string(t).c_str());
  231. }
  232. const bool is_host = ggml_backend_buffer_is_host(t->buffer);
  233. if (!is_host) {
  234. auto n_bytes = ggml_nbytes(t);
  235. cb_data->data.resize(n_bytes);
  236. ggml_backend_tensor_get(t, cb_data->data.data(), 0, n_bytes);
  237. }
  238. if (!ggml_is_quantized(t->type) && matches_filter) {
  239. uint8_t * data = is_host ? (uint8_t *) t->data : cb_data->data.data();
  240. ggml_print_tensor(data, t->type, t->ne, t->nb, 3);
  241. }
  242. return true;
  243. }
  244. static void save_output_data(const output_data & output, const std::string & model_name, const std::string & output_dir) {
  245. std::filesystem::create_directory(output_dir);
  246. auto base_path = std::filesystem::path{output_dir} / ("llamacpp-" + model_name + output.type_suffix);
  247. // Save logits/embeddings to binary file.
  248. {
  249. std::filesystem::path filepath{base_path.string() + ".bin"};
  250. std::ofstream file{filepath, std::ios::binary};
  251. if (!file) {
  252. throw std::runtime_error("failed to open binary output file: " + filepath.string());
  253. }
  254. file.write(reinterpret_cast<const char*>(output.data_ptr), output.data_size * sizeof(float));
  255. LOG("Data saved to %s\n", filepath.c_str());
  256. }
  257. // Save logits/embeddings to text file.
  258. {
  259. std::filesystem::path filepath{base_path.string() + ".txt"};
  260. std::ofstream file{filepath};
  261. if (!file) {
  262. throw std::runtime_error("failed to open text output file: " + filepath.string());
  263. }
  264. for (int i = 0; i < output.data_size; i++) {
  265. file << i << ": " << output.data_ptr[i] << '\n';
  266. }
  267. LOG("Data saved to %s\n", filepath.c_str());
  268. }
  269. // Save prompt and tokens to text file.
  270. {
  271. std::filesystem::path filepath{base_path.string() + "-prompt.txt"};
  272. std::ofstream file{filepath};
  273. if (!file) {
  274. throw std::runtime_error("failed to open prompt output file: " + filepath.string());
  275. }
  276. file << "prompt: " << output.prompt << '\n';
  277. file << "n_tokens: " << output.tokens.size() << '\n';
  278. file << "token ids: ";
  279. for (size_t i = 0; i < output.tokens.size(); i++) {
  280. file << output.tokens[i];
  281. if (i + 1 < output.tokens.size()) {
  282. file << ", ";
  283. }
  284. }
  285. file << '\n';
  286. LOG("Prompt saved to %s\n", filepath.c_str());
  287. }
  288. // Save token ids to binary file.
  289. {
  290. std::filesystem::path filepath{base_path.string() + "-tokens.bin"};
  291. std::ofstream file{filepath, std::ios::binary};
  292. if (!file) {
  293. throw std::runtime_error("failed to open tokens binary file: " + filepath.string());
  294. }
  295. file.write(reinterpret_cast<const char*>(output.tokens.data()), output.tokens.size() * sizeof(llama_token));
  296. LOG("Tokens saved to %s\n", filepath.c_str());
  297. }
  298. }
  299. static void print_tokenized_prompt(llama_context * ctx, const std::vector<llama_token> & tokens, const std::string & prompt) {
  300. const llama_model * model = llama_get_model(ctx);
  301. const llama_vocab * vocab = llama_model_get_vocab(model);
  302. LOG("Model add_bos: %s\n", llama_vocab_get_add_bos(vocab) ? "true" : "false");
  303. LOG("Input prompt: \"%s\"\n", prompt.c_str());
  304. LOG("Token ids (%zu):\n", tokens.size());
  305. for (auto id : tokens) {
  306. std::string piece(128, '\0');
  307. int n = llama_token_to_piece(vocab, id, piece.data(), piece.size(), 0, true);
  308. if (n < 0) {
  309. LOG_ERR("failed to convert token %d to piece\n", id);
  310. continue;
  311. }
  312. piece.resize(n);
  313. LOG("%s(%d) ", piece.c_str(), id);
  314. }
  315. LOG("\n");
  316. }
  317. static bool run(llama_context * ctx, const common_params & params) {
  318. const llama_model * model = llama_get_model(ctx);
  319. const llama_vocab * vocab = llama_model_get_vocab(model);
  320. const bool add_bos = llama_vocab_get_add_bos(vocab);
  321. std::vector<llama_token> tokens = common_tokenize(ctx, params.prompt, add_bos);
  322. if (tokens.empty()) {
  323. LOG_ERR("%s : there are not input tokens to process - (try to provide a prompt with '-p')\n", __func__);
  324. return false;
  325. }
  326. if (llama_decode(ctx, llama_batch_get_one(tokens.data(), tokens.size()))) {
  327. LOG_ERR("%s : failed to eval\n", __func__);
  328. return false;
  329. }
  330. print_tokenized_prompt(ctx, tokens, params.prompt);
  331. if (params.save_logits) {
  332. output_data output {ctx, model, params};
  333. std::filesystem::path model_path{params.model.path};
  334. std::string model_name{model_path.stem().string()};
  335. save_output_data(output, model_name, params.logits_output_dir);
  336. }
  337. return true;
  338. }
  339. int main(int argc, char ** argv) {
  340. common_params params;
  341. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_DEBUG, print_usage)) {
  342. return 1;
  343. }
  344. common_init();
  345. llama_backend_init();
  346. llama_numa_init(params.numa);
  347. callback_data cb_data(params, params.tensor_filter);
  348. auto llama_init = common_init_from_params(params);
  349. auto * model = llama_init->model();
  350. auto * ctx = llama_init->context();
  351. if (model == nullptr || ctx == nullptr) {
  352. LOG_ERR("%s : failed to init\n", __func__);
  353. return 1;
  354. }
  355. {
  356. LOG_INF("\n");
  357. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  358. LOG_INF("\n");
  359. }
  360. if (!run(ctx, params)) {
  361. return 1;
  362. }
  363. LOG("\n");
  364. llama_perf_context_print(ctx);
  365. llama_backend_free();
  366. return 0;
  367. }