debug.cpp 14 KB

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