1
0

logits.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #include "llama.h"
  2. #include "common.h"
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <string>
  6. #include <vector>
  7. #include <ctype.h>
  8. #include <filesystem>
  9. static void print_usage(int, char ** argv) {
  10. printf("\nexample usage:\n");
  11. printf("\n %s -m model.gguf [-ngl n_gpu_layers] -embd-mode [-pooling] [-embd-norm <norm>] [prompt]\n", argv[0]);
  12. printf("\n");
  13. printf(" -embd-norm: normalization type for pooled embeddings (default: 2)\n");
  14. printf(" -1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm\n");
  15. printf("\n");
  16. }
  17. int main(int argc, char ** argv) {
  18. std::string model_path;
  19. std::string prompt = "Hello, my name is";
  20. int ngl = 0;
  21. bool embedding_mode = false;
  22. bool pooling_enabled = false;
  23. int32_t embd_norm = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)
  24. {
  25. int i = 1;
  26. for (; i < argc; i++) {
  27. if (strcmp(argv[i], "-m") == 0) {
  28. if (i + 1 < argc) {
  29. model_path = argv[++i];
  30. } else {
  31. print_usage(argc, argv);
  32. return 1;
  33. }
  34. } else if (strcmp(argv[i], "-ngl") == 0) {
  35. if (i + 1 < argc) {
  36. try {
  37. ngl = std::stoi(argv[++i]);
  38. } catch (...) {
  39. print_usage(argc, argv);
  40. return 1;
  41. }
  42. } else {
  43. print_usage(argc, argv);
  44. return 1;
  45. }
  46. } else if (strcmp(argv[i], "-embd-mode") == 0) {
  47. embedding_mode = true;
  48. } else if (strcmp(argv[i], "-pooling") == 0) {
  49. pooling_enabled = true;
  50. } else if (strcmp(argv[i], "-embd-norm") == 0) {
  51. if (i + 1 < argc) {
  52. try {
  53. embd_norm = std::stoi(argv[++i]);
  54. } catch (...) {
  55. print_usage(argc, argv);
  56. return 1;
  57. }
  58. } else {
  59. print_usage(argc, argv);
  60. return 1;
  61. }
  62. } else {
  63. // prompt starts here
  64. break;
  65. }
  66. }
  67. if (model_path.empty()) {
  68. print_usage(argc, argv);
  69. return 1;
  70. }
  71. if (i < argc) {
  72. prompt = argv[i++];
  73. for (; i < argc; i++) {
  74. prompt += " ";
  75. prompt += argv[i];
  76. }
  77. }
  78. }
  79. ggml_backend_load_all();
  80. llama_model_params model_params = llama_model_default_params();
  81. model_params.n_gpu_layers = ngl;
  82. llama_model * model = llama_model_load_from_file(model_path.c_str(), model_params);
  83. if (model == NULL) {
  84. fprintf(stderr , "%s: error: unable to load model\n" , __func__);
  85. return 1;
  86. }
  87. // Extract basename from model_path
  88. const char * basename = strrchr(model_path.c_str(), '/');
  89. basename = (basename == NULL) ? model_path.c_str() : basename + 1;
  90. char model_name[256];
  91. strncpy(model_name, basename, 255);
  92. model_name[255] = '\0';
  93. char * dot = strrchr(model_name, '.');
  94. if (dot != NULL && strcmp(dot, ".gguf") == 0) {
  95. *dot = '\0';
  96. }
  97. printf("Model name: %s\n", model_name);
  98. const llama_vocab * vocab = llama_model_get_vocab(model);
  99. const int n_prompt = -llama_tokenize(vocab, prompt.c_str(), prompt.size(), NULL, 0, true, true);
  100. std::vector<llama_token> prompt_tokens(n_prompt);
  101. if (llama_tokenize(vocab, prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), true, true) < 0) {
  102. fprintf(stderr, "%s: error: failed to tokenize the prompt\n", __func__);
  103. return 1;
  104. }
  105. llama_context_params ctx_params = llama_context_default_params();
  106. ctx_params.n_ctx = n_prompt;
  107. ctx_params.n_batch = n_prompt;
  108. ctx_params.no_perf = false;
  109. if (embedding_mode) {
  110. ctx_params.embeddings = true;
  111. ctx_params.pooling_type = pooling_enabled ? LLAMA_POOLING_TYPE_MEAN : LLAMA_POOLING_TYPE_NONE;
  112. ctx_params.n_ubatch = ctx_params.n_batch;
  113. }
  114. llama_context * ctx = llama_init_from_model(model, ctx_params);
  115. if (ctx == NULL) {
  116. fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
  117. return 1;
  118. }
  119. printf("Input prompt: \"%s\"\n", prompt.c_str());
  120. printf("Tokenized prompt (%d tokens): ", n_prompt);
  121. for (auto id : prompt_tokens) {
  122. char buf[128];
  123. int n = llama_token_to_piece(vocab, id, buf, sizeof(buf), 0, true);
  124. if (n < 0) {
  125. fprintf(stderr, "%s: error: failed to convert token to piece\n", __func__);
  126. return 1;
  127. }
  128. std::string s(buf, n);
  129. printf("%s", s.c_str());
  130. }
  131. printf("\n");
  132. llama_batch batch = llama_batch_get_one(prompt_tokens.data(), prompt_tokens.size());
  133. if (llama_decode(ctx, batch)) {
  134. fprintf(stderr, "%s : failed to eval\n", __func__);
  135. return 1;
  136. }
  137. float * data_ptr;
  138. int data_size;
  139. const char * type;
  140. std::vector<float> embd_out;
  141. if (embedding_mode) {
  142. const int n_embd = llama_model_n_embd(model);
  143. const int n_embd_count = pooling_enabled ? 1 : batch.n_tokens;
  144. const int n_embeddings = n_embd * n_embd_count;
  145. float * embeddings;
  146. type = "-embeddings";
  147. if (llama_pooling_type(ctx) != LLAMA_POOLING_TYPE_NONE) {
  148. embeddings = llama_get_embeddings_seq(ctx, 0);
  149. embd_out.resize(n_embeddings);
  150. printf("Normalizing embeddings using norm: %d\n", embd_norm);
  151. common_embd_normalize(embeddings, embd_out.data(), n_embeddings, embd_norm);
  152. embeddings = embd_out.data();
  153. } else {
  154. embeddings = llama_get_embeddings(ctx);
  155. }
  156. printf("Embedding dimension: %d\n", n_embd);
  157. printf("\n");
  158. // Print embeddings in the specified format
  159. for (int j = 0; j < n_embd_count; j++) {
  160. printf("embedding %d: ", j);
  161. // Print first 3 values
  162. for (int i = 0; i < 3 && i < n_embd; i++) {
  163. printf("%9.6f ", embeddings[j * n_embd + i]);
  164. }
  165. printf(" ... ");
  166. // Print last 3 values
  167. for (int i = n_embd - 3; i < n_embd; i++) {
  168. if (i >= 0) {
  169. printf("%9.6f ", embeddings[j * n_embd + i]);
  170. }
  171. }
  172. printf("\n");
  173. }
  174. printf("\n");
  175. printf("Embeddings size: %d\n", n_embeddings);
  176. data_ptr = embeddings;
  177. data_size = n_embeddings;
  178. } else {
  179. float * logits = llama_get_logits_ith(ctx, batch.n_tokens - 1);
  180. const int n_logits = llama_vocab_n_tokens(vocab);
  181. type = "";
  182. printf("Vocab size: %d\n", n_logits);
  183. data_ptr = logits;
  184. data_size = n_logits;
  185. }
  186. std::filesystem::create_directory("data");
  187. // Save data to binary file
  188. char bin_filename[512];
  189. snprintf(bin_filename, sizeof(bin_filename), "data/llamacpp-%s%s.bin", model_name, type);
  190. printf("Saving data to %s\n", bin_filename);
  191. FILE * f = fopen(bin_filename, "wb");
  192. if (f == NULL) {
  193. fprintf(stderr, "%s: error: failed to open binary output file\n", __func__);
  194. return 1;
  195. }
  196. fwrite(data_ptr, sizeof(float), data_size, f);
  197. fclose(f);
  198. // Also save as text for debugging
  199. char txt_filename[512];
  200. snprintf(txt_filename, sizeof(txt_filename), "data/llamacpp-%s%s.txt", model_name, type);
  201. f = fopen(txt_filename, "w");
  202. if (f == NULL) {
  203. fprintf(stderr, "%s: error: failed to open text output file\n", __func__);
  204. return 1;
  205. }
  206. for (int i = 0; i < data_size; i++) {
  207. fprintf(f, "%d: %.6f\n", i, data_ptr[i]);
  208. }
  209. fclose(f);
  210. if (!embedding_mode) {
  211. printf("First 10 logits: ");
  212. for (int i = 0; i < 10 && i < data_size; i++) {
  213. printf("%.6f ", data_ptr[i]);
  214. }
  215. printf("\n");
  216. printf("Last 10 logits: ");
  217. for (int i = data_size - 10; i < data_size; i++) {
  218. if (i >= 0) printf("%.6f ", data_ptr[i]);
  219. }
  220. printf("\n\n");
  221. }
  222. printf("Data saved to %s\n", bin_filename);
  223. printf("Data saved to %s\n", txt_filename);
  224. llama_free(ctx);
  225. llama_model_free(model);
  226. return 0;
  227. }