@fugood/llama.node 0.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CMakeLists.txt +85 -0
  2. package/README.md +56 -0
  3. package/bin/darwin/arm64/llama-node.node +0 -0
  4. package/bin/darwin/x64/llama-node.node +0 -0
  5. package/bin/linux/arm64/llama-node.node +0 -0
  6. package/bin/linux/x64/llama-node.node +0 -0
  7. package/bin/win32/arm64/llama-node.node +0 -0
  8. package/bin/win32/arm64/node.lib +0 -0
  9. package/bin/win32/x64/llama-node.node +0 -0
  10. package/bin/win32/x64/node.lib +0 -0
  11. package/lib/binding.js +13 -0
  12. package/lib/binding.ts +57 -0
  13. package/lib/index.js +24 -0
  14. package/lib/index.ts +13 -0
  15. package/package.json +65 -0
  16. package/src/addons.cpp +506 -0
  17. package/src/llama.cpp/CMakeLists.txt +1320 -0
  18. package/src/llama.cpp/build.zig +172 -0
  19. package/src/llama.cpp/cmake/FindSIMD.cmake +100 -0
  20. package/src/llama.cpp/common/CMakeLists.txt +87 -0
  21. package/src/llama.cpp/common/base64.hpp +392 -0
  22. package/src/llama.cpp/common/common.cpp +2949 -0
  23. package/src/llama.cpp/common/common.h +324 -0
  24. package/src/llama.cpp/common/console.cpp +501 -0
  25. package/src/llama.cpp/common/console.h +19 -0
  26. package/src/llama.cpp/common/grammar-parser.cpp +440 -0
  27. package/src/llama.cpp/common/grammar-parser.h +29 -0
  28. package/src/llama.cpp/common/json-schema-to-grammar.cpp +764 -0
  29. package/src/llama.cpp/common/json-schema-to-grammar.h +4 -0
  30. package/src/llama.cpp/common/json.hpp +24766 -0
  31. package/src/llama.cpp/common/log.h +724 -0
  32. package/src/llama.cpp/common/ngram-cache.cpp +282 -0
  33. package/src/llama.cpp/common/ngram-cache.h +94 -0
  34. package/src/llama.cpp/common/sampling.cpp +353 -0
  35. package/src/llama.cpp/common/sampling.h +147 -0
  36. package/src/llama.cpp/common/stb_image.h +8396 -0
  37. package/src/llama.cpp/common/train.cpp +1513 -0
  38. package/src/llama.cpp/common/train.h +233 -0
  39. package/src/llama.cpp/examples/CMakeLists.txt +52 -0
  40. package/src/llama.cpp/examples/baby-llama/CMakeLists.txt +5 -0
  41. package/src/llama.cpp/examples/baby-llama/baby-llama.cpp +1640 -0
  42. package/src/llama.cpp/examples/batched/CMakeLists.txt +5 -0
  43. package/src/llama.cpp/examples/batched/batched.cpp +262 -0
  44. package/src/llama.cpp/examples/batched-bench/CMakeLists.txt +5 -0
  45. package/src/llama.cpp/examples/batched-bench/batched-bench.cpp +261 -0
  46. package/src/llama.cpp/examples/beam-search/CMakeLists.txt +5 -0
  47. package/src/llama.cpp/examples/beam-search/beam-search.cpp +188 -0
  48. package/src/llama.cpp/examples/benchmark/CMakeLists.txt +6 -0
  49. package/src/llama.cpp/examples/benchmark/benchmark-matmult.cpp +275 -0
  50. package/src/llama.cpp/examples/convert-llama2c-to-ggml/CMakeLists.txt +5 -0
  51. package/src/llama.cpp/examples/convert-llama2c-to-ggml/convert-llama2c-to-ggml.cpp +936 -0
  52. package/src/llama.cpp/examples/embedding/CMakeLists.txt +5 -0
  53. package/src/llama.cpp/examples/embedding/embedding.cpp +211 -0
  54. package/src/llama.cpp/examples/eval-callback/CMakeLists.txt +9 -0
  55. package/src/llama.cpp/examples/eval-callback/eval-callback.cpp +195 -0
  56. package/src/llama.cpp/examples/export-lora/CMakeLists.txt +5 -0
  57. package/src/llama.cpp/examples/export-lora/export-lora.cpp +462 -0
  58. package/src/llama.cpp/examples/finetune/CMakeLists.txt +5 -0
  59. package/src/llama.cpp/examples/finetune/finetune.cpp +1861 -0
  60. package/src/llama.cpp/examples/gbnf-validator/CMakeLists.txt +5 -0
  61. package/src/llama.cpp/examples/gbnf-validator/gbnf-validator.cpp +132 -0
  62. package/src/llama.cpp/examples/gguf/CMakeLists.txt +5 -0
  63. package/src/llama.cpp/examples/gguf/gguf.cpp +256 -0
  64. package/src/llama.cpp/examples/gguf-split/CMakeLists.txt +5 -0
  65. package/src/llama.cpp/examples/gguf-split/gguf-split.cpp +553 -0
  66. package/src/llama.cpp/examples/gritlm/CMakeLists.txt +5 -0
  67. package/src/llama.cpp/examples/gritlm/gritlm.cpp +215 -0
  68. package/src/llama.cpp/examples/imatrix/CMakeLists.txt +5 -0
  69. package/src/llama.cpp/examples/imatrix/imatrix.cpp +655 -0
  70. package/src/llama.cpp/examples/infill/CMakeLists.txt +5 -0
  71. package/src/llama.cpp/examples/infill/infill.cpp +767 -0
  72. package/src/llama.cpp/examples/jeopardy/questions.txt +100 -0
  73. package/src/llama.cpp/examples/llama-bench/CMakeLists.txt +5 -0
  74. package/src/llama.cpp/examples/llama-bench/llama-bench.cpp +1286 -0
  75. package/src/llama.cpp/examples/llama.android/app/src/main/cpp/CMakeLists.txt +50 -0
  76. package/src/llama.cpp/examples/llama.android/app/src/main/cpp/llama-android.cpp +443 -0
  77. package/src/llama.cpp/examples/llava/CMakeLists.txt +37 -0
  78. package/src/llama.cpp/examples/llava/clip.cpp +2027 -0
  79. package/src/llama.cpp/examples/llava/clip.h +85 -0
  80. package/src/llama.cpp/examples/llava/llava-cli.cpp +309 -0
  81. package/src/llama.cpp/examples/llava/llava.cpp +426 -0
  82. package/src/llama.cpp/examples/llava/llava.h +50 -0
  83. package/src/llama.cpp/examples/llava/requirements.txt +3 -0
  84. package/src/llama.cpp/examples/lookahead/CMakeLists.txt +5 -0
  85. package/src/llama.cpp/examples/lookahead/lookahead.cpp +485 -0
  86. package/src/llama.cpp/examples/lookup/CMakeLists.txt +23 -0
  87. package/src/llama.cpp/examples/lookup/lookup-create.cpp +41 -0
  88. package/src/llama.cpp/examples/lookup/lookup-merge.cpp +47 -0
  89. package/src/llama.cpp/examples/lookup/lookup-stats.cpp +160 -0
  90. package/src/llama.cpp/examples/lookup/lookup.cpp +258 -0
  91. package/src/llama.cpp/examples/main/CMakeLists.txt +5 -0
  92. package/src/llama.cpp/examples/main/main.cpp +957 -0
  93. package/src/llama.cpp/examples/main-cmake-pkg/CMakeLists.txt +33 -0
  94. package/src/llama.cpp/examples/parallel/CMakeLists.txt +5 -0
  95. package/src/llama.cpp/examples/parallel/parallel.cpp +427 -0
  96. package/src/llama.cpp/examples/passkey/CMakeLists.txt +5 -0
  97. package/src/llama.cpp/examples/passkey/passkey.cpp +302 -0
  98. package/src/llama.cpp/examples/perplexity/CMakeLists.txt +5 -0
  99. package/src/llama.cpp/examples/perplexity/perplexity.cpp +1943 -0
  100. package/src/llama.cpp/examples/quantize/CMakeLists.txt +6 -0
  101. package/src/llama.cpp/examples/quantize/quantize.cpp +423 -0
  102. package/src/llama.cpp/examples/quantize-stats/CMakeLists.txt +6 -0
  103. package/src/llama.cpp/examples/quantize-stats/quantize-stats.cpp +424 -0
  104. package/src/llama.cpp/examples/retrieval/CMakeLists.txt +5 -0
  105. package/src/llama.cpp/examples/retrieval/retrieval.cpp +350 -0
  106. package/src/llama.cpp/examples/save-load-state/CMakeLists.txt +5 -0
  107. package/src/llama.cpp/examples/save-load-state/save-load-state.cpp +246 -0
  108. package/src/llama.cpp/examples/server/CMakeLists.txt +40 -0
  109. package/src/llama.cpp/examples/server/bench/requirements.txt +2 -0
  110. package/src/llama.cpp/examples/server/httplib.h +9465 -0
  111. package/src/llama.cpp/examples/server/server.cpp +3826 -0
  112. package/src/llama.cpp/examples/server/tests/requirements.txt +6 -0
  113. package/src/llama.cpp/examples/server/utils.hpp +653 -0
  114. package/src/llama.cpp/examples/simple/CMakeLists.txt +5 -0
  115. package/src/llama.cpp/examples/simple/simple.cpp +183 -0
  116. package/src/llama.cpp/examples/speculative/CMakeLists.txt +5 -0
  117. package/src/llama.cpp/examples/speculative/speculative.cpp +614 -0
  118. package/src/llama.cpp/examples/sycl/CMakeLists.txt +9 -0
  119. package/src/llama.cpp/examples/sycl/ls-sycl-device.cpp +13 -0
  120. package/src/llama.cpp/examples/tokenize/CMakeLists.txt +5 -0
  121. package/src/llama.cpp/examples/tokenize/tokenize.cpp +42 -0
  122. package/src/llama.cpp/examples/train-text-from-scratch/CMakeLists.txt +5 -0
  123. package/src/llama.cpp/examples/train-text-from-scratch/train-text-from-scratch.cpp +1252 -0
  124. package/src/llama.cpp/ggml-alloc.c +985 -0
  125. package/src/llama.cpp/ggml-alloc.h +76 -0
  126. package/src/llama.cpp/ggml-backend-impl.h +141 -0
  127. package/src/llama.cpp/ggml-backend.c +2099 -0
  128. package/src/llama.cpp/ggml-backend.h +233 -0
  129. package/src/llama.cpp/ggml-common.h +1853 -0
  130. package/src/llama.cpp/ggml-cuda.h +43 -0
  131. package/src/llama.cpp/ggml-impl.h +265 -0
  132. package/src/llama.cpp/ggml-kompute.cpp +2006 -0
  133. package/src/llama.cpp/ggml-kompute.h +46 -0
  134. package/src/llama.cpp/ggml-metal.h +66 -0
  135. package/src/llama.cpp/ggml-mpi.c +216 -0
  136. package/src/llama.cpp/ggml-mpi.h +39 -0
  137. package/src/llama.cpp/ggml-opencl.cpp +2301 -0
  138. package/src/llama.cpp/ggml-opencl.h +36 -0
  139. package/src/llama.cpp/ggml-quants.c +12678 -0
  140. package/src/llama.cpp/ggml-quants.h +133 -0
  141. package/src/llama.cpp/ggml-sycl.cpp +17882 -0
  142. package/src/llama.cpp/ggml-sycl.h +49 -0
  143. package/src/llama.cpp/ggml-vulkan-shaders.hpp +69849 -0
  144. package/src/llama.cpp/ggml-vulkan.cpp +6442 -0
  145. package/src/llama.cpp/ggml-vulkan.h +29 -0
  146. package/src/llama.cpp/ggml.c +21819 -0
  147. package/src/llama.cpp/ggml.h +2403 -0
  148. package/src/llama.cpp/llama.cpp +17468 -0
  149. package/src/llama.cpp/llama.h +1117 -0
  150. package/src/llama.cpp/pocs/CMakeLists.txt +12 -0
  151. package/src/llama.cpp/pocs/vdot/CMakeLists.txt +9 -0
  152. package/src/llama.cpp/pocs/vdot/q8dot.cpp +172 -0
  153. package/src/llama.cpp/pocs/vdot/vdot.cpp +310 -0
  154. package/src/llama.cpp/prompts/LLM-questions.txt +49 -0
  155. package/src/llama.cpp/prompts/alpaca.txt +1 -0
  156. package/src/llama.cpp/prompts/assistant.txt +31 -0
  157. package/src/llama.cpp/prompts/chat-with-baichuan.txt +4 -0
  158. package/src/llama.cpp/prompts/chat-with-bob.txt +7 -0
  159. package/src/llama.cpp/prompts/chat-with-qwen.txt +1 -0
  160. package/src/llama.cpp/prompts/chat-with-vicuna-v0.txt +7 -0
  161. package/src/llama.cpp/prompts/chat-with-vicuna-v1.txt +7 -0
  162. package/src/llama.cpp/prompts/chat.txt +28 -0
  163. package/src/llama.cpp/prompts/dan-modified.txt +1 -0
  164. package/src/llama.cpp/prompts/dan.txt +1 -0
  165. package/src/llama.cpp/prompts/mnemonics.txt +93 -0
  166. package/src/llama.cpp/prompts/parallel-questions.txt +43 -0
  167. package/src/llama.cpp/prompts/reason-act.txt +18 -0
  168. package/src/llama.cpp/requirements/requirements-convert-hf-to-gguf.txt +3 -0
  169. package/src/llama.cpp/requirements/requirements-convert-llama-ggml-to-gguf.txt +1 -0
  170. package/src/llama.cpp/requirements/requirements-convert-lora-to-ggml.txt +2 -0
  171. package/src/llama.cpp/requirements/requirements-convert-persimmon-to-gguf.txt +2 -0
  172. package/src/llama.cpp/requirements/requirements-convert.txt +5 -0
  173. package/src/llama.cpp/requirements.txt +12 -0
  174. package/src/llama.cpp/scripts/gen-build-info-cpp.cmake +24 -0
  175. package/src/llama.cpp/scripts/xxd.cmake +16 -0
  176. package/src/llama.cpp/sgemm.cpp +999 -0
  177. package/src/llama.cpp/sgemm.h +12 -0
  178. package/src/llama.cpp/tests/CMakeLists.txt +78 -0
  179. package/src/llama.cpp/tests/get-model.cpp +21 -0
  180. package/src/llama.cpp/tests/get-model.h +2 -0
  181. package/src/llama.cpp/tests/test-autorelease.cpp +24 -0
  182. package/src/llama.cpp/tests/test-backend-ops.cpp +2266 -0
  183. package/src/llama.cpp/tests/test-c.c +7 -0
  184. package/src/llama.cpp/tests/test-chat-template.cpp +107 -0
  185. package/src/llama.cpp/tests/test-double-float.cpp +57 -0
  186. package/src/llama.cpp/tests/test-grad0.cpp +1606 -0
  187. package/src/llama.cpp/tests/test-grammar-integration.cpp +243 -0
  188. package/src/llama.cpp/tests/test-grammar-parser.cpp +250 -0
  189. package/src/llama.cpp/tests/test-json-schema-to-grammar.cpp +899 -0
  190. package/src/llama.cpp/tests/test-llama-grammar.cpp +402 -0
  191. package/src/llama.cpp/tests/test-model-load-cancel.cpp +27 -0
  192. package/src/llama.cpp/tests/test-opt.cpp +181 -0
  193. package/src/llama.cpp/tests/test-quantize-fns.cpp +185 -0
  194. package/src/llama.cpp/tests/test-quantize-perf.cpp +363 -0
  195. package/src/llama.cpp/tests/test-rope.cpp +221 -0
  196. package/src/llama.cpp/tests/test-sampling.cpp +301 -0
  197. package/src/llama.cpp/tests/test-tokenizer-0-falcon.cpp +187 -0
  198. package/src/llama.cpp/tests/test-tokenizer-0-llama.cpp +190 -0
  199. package/src/llama.cpp/tests/test-tokenizer-1-bpe.cpp +123 -0
  200. package/src/llama.cpp/tests/test-tokenizer-1-llama.cpp +111 -0
  201. package/src/llama.cpp/unicode-data.cpp +1651 -0
  202. package/src/llama.cpp/unicode-data.h +16 -0
  203. package/src/llama.cpp/unicode.cpp +277 -0
  204. package/src/llama.cpp/unicode.h +28 -0
@@ -0,0 +1,655 @@
1
+ #include "common.h"
2
+ #include "llama.h"
3
+
4
+ #include <cmath>
5
+ #include <cstdio>
6
+ #include <cstring>
7
+ #include <ctime>
8
+ #include <sstream>
9
+ #include <thread>
10
+ #include <mutex>
11
+ #include <vector>
12
+ #include <fstream>
13
+ #include <unordered_map>
14
+ #include <algorithm>
15
+
16
+ #if defined(_MSC_VER)
17
+ #pragma warning(disable: 4244 4267) // possible loss of data
18
+ #endif
19
+
20
+ struct Stats {
21
+ std::vector<float> values;
22
+ int ncall = 0;
23
+ };
24
+
25
+ struct StatParams {
26
+ std::string ofile = "imatrix.dat";
27
+ int n_output_frequency = 10;
28
+ int verbosity = 1;
29
+ int keep_every = 0;
30
+ bool collect_output_weight = false;
31
+ };
32
+
33
+ class IMatrixCollector {
34
+ public:
35
+ IMatrixCollector() = default;
36
+ void set_parameters(StatParams&& params) { m_params = std::move(params); }
37
+ bool collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data);
38
+ void save_imatrix() const;
39
+ bool load_imatrix(const char * file_name, bool add);
40
+ static bool load_imatrix(const char * file_name, std::unordered_map<std::string, Stats>& imatrix);
41
+ private:
42
+ std::unordered_map<std::string, Stats> m_stats;
43
+ StatParams m_params;
44
+ std::mutex m_mutex;
45
+ int m_last_call = 0;
46
+ std::vector<float> m_src1_data;
47
+ std::vector<char> m_ids; // the expert ids from ggml_mul_mat_id
48
+ //
49
+ void save_imatrix(const char * file_name) const;
50
+ void keep_imatrix(int ncall) const;
51
+ };
52
+
53
+ // remove any prefix and suffixes from the name
54
+ // CUDA0#blk.0.attn_k.weight#0 => blk.0.attn_k.weight
55
+ static std::string filter_tensor_name(const char * name) {
56
+ std::string wname;
57
+ const char * p = strchr(name, '#');
58
+ if (p != NULL) {
59
+ p = p + 1;
60
+ const char * q = strchr(p, '#');
61
+ if (q != NULL) {
62
+ wname = std::string(p, q - p);
63
+ } else {
64
+ wname = p;
65
+ }
66
+ } else {
67
+ wname = name;
68
+ }
69
+ return wname;
70
+ }
71
+
72
+ bool IMatrixCollector::collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
73
+ GGML_UNUSED(user_data);
74
+
75
+ const struct ggml_tensor * src0 = t->src[0];
76
+ const struct ggml_tensor * src1 = t->src[1];
77
+ std::string wname = filter_tensor_name(src0->name);
78
+
79
+ // when ask is true, the scheduler wants to know if we are interested in data from this tensor
80
+ // if we return true, a follow-up call will be made with ask=false in which we can do the actual collection
81
+ if (ask) {
82
+ if (t->op == GGML_OP_MUL_MAT_ID) return true; // collect all indirect matrix multiplications
83
+ if (t->op != GGML_OP_MUL_MAT) return false;
84
+ // why are small batches ignored (<16 tokens)?
85
+ if (src1->ne[1] < 16 || src1->type != GGML_TYPE_F32) return false;
86
+ if (!(wname.substr(0, 4) == "blk." || (m_params.collect_output_weight && wname == "output.weight"))) return false;
87
+ return true;
88
+ }
89
+
90
+ std::lock_guard<std::mutex> lock(m_mutex);
91
+
92
+ // copy the data from the GPU memory if needed
93
+ const bool is_host = ggml_backend_buffer_is_host(src1->buffer);
94
+
95
+ if (!is_host) {
96
+ m_src1_data.resize(ggml_nelements(src1));
97
+ ggml_backend_tensor_get(src1, m_src1_data.data(), 0, ggml_nbytes(src1));
98
+ }
99
+
100
+ const float * data = is_host ? (const float *) src1->data : m_src1_data.data();
101
+
102
+ // this has been adapted to the new format of storing merged experts in a single 3d tensor
103
+ // ref: https://github.com/ggerganov/llama.cpp/pull/6387
104
+ if (t->op == GGML_OP_MUL_MAT_ID) {
105
+ // ids -> [n_experts_used, n_tokens]
106
+ // src1 -> [cols, n_expert_used, n_tokens]
107
+ const ggml_tensor * ids = t->src[2];
108
+ const int n_as = src0->ne[2];
109
+ const int n_ids = ids->ne[0];
110
+
111
+ // the top-k selected expert ids are stored in the ids tensor
112
+ // for simplicity, always copy ids to host, because it is small
113
+ // take into account that ids is not contiguous!
114
+
115
+ GGML_ASSERT(ids->ne[1] == src1->ne[2]);
116
+
117
+ m_ids.resize(ggml_nbytes(ids));
118
+ ggml_backend_tensor_get(ids, m_ids.data(), 0, ggml_nbytes(ids));
119
+
120
+ auto & e = m_stats[wname];
121
+
122
+ ++e.ncall;
123
+ // NOTE: since we select top-k experts, the number of calls for the expert tensors will be k times larger
124
+ // using the following line, we can correct for that if needed by replacing the line above with:
125
+ //if (idx == t->src[0]->ne[0] - 1) ++e.ncall;
126
+
127
+ if (e.values.empty()) {
128
+ e.values.resize(src1->ne[0]*n_as, 0);
129
+ }
130
+ else if (e.values.size() != (size_t)src1->ne[0]*n_as) {
131
+ fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]*n_as);
132
+ exit(1); //GGML_ASSERT(false);
133
+ }
134
+ if (m_params.verbosity > 1) {
135
+ printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);
136
+ }
137
+ // loop over all possible experts, regardless if they are used or not in the batch
138
+ for (int ex = 0; ex < n_as; ++ex) {
139
+ size_t e_start = ex*src1->ne[0];
140
+
141
+ for (int idx = 0; idx < n_ids; ++idx) {
142
+ for (int row = 0; row < (int)src1->ne[2]; ++row) {
143
+ const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);
144
+
145
+ GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check
146
+
147
+ if (excur != ex) continue;
148
+
149
+ const int64_t i11 = idx % src1->ne[1];
150
+ const int64_t i12 = row;
151
+ const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);
152
+
153
+ for (int j = 0; j < (int)src1->ne[0]; ++j) {
154
+ e.values[e_start + j] += x[j]*x[j];
155
+ }
156
+ }
157
+ }
158
+ if (e.ncall > m_last_call) {
159
+ m_last_call = e.ncall;
160
+ if (m_last_call % m_params.n_output_frequency == 0) {
161
+ save_imatrix();
162
+ }
163
+ if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
164
+ keep_imatrix(m_last_call);
165
+ }
166
+ }
167
+ }
168
+ } else {
169
+ auto& e = m_stats[wname];
170
+ if (e.values.empty()) {
171
+ e.values.resize(src1->ne[0], 0);
172
+ }
173
+ else if (e.values.size() != (size_t)src1->ne[0]) {
174
+ fprintf(stderr, "Oops: inconsistent size for %s (%d vs %d)\n", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);
175
+ exit(1); //GGML_ASSERT(false);
176
+ }
177
+ ++e.ncall;
178
+ if (m_params.verbosity > 1) {
179
+ printf("%s[%d]: %32s, %s, %5d x %5d, %d\n", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);
180
+ }
181
+ for (int row = 0; row < (int)src1->ne[1]; ++row) {
182
+ const float * x = data + row * src1->ne[0];
183
+ for (int j = 0; j < (int)src1->ne[0]; ++j) {
184
+ e.values[j] += x[j]*x[j];
185
+ }
186
+ }
187
+ if (e.ncall > m_last_call) {
188
+ m_last_call = e.ncall;
189
+ if (m_last_call % m_params.n_output_frequency == 0) {
190
+ save_imatrix();
191
+ }
192
+ if (m_params.keep_every > 0 && m_last_call%m_params.keep_every == 0) {
193
+ keep_imatrix(m_last_call);
194
+ }
195
+ }
196
+ }
197
+
198
+ return true;
199
+ }
200
+
201
+ void IMatrixCollector::save_imatrix() const {
202
+ save_imatrix(m_params.ofile.empty() ? "imatrix.dat" : m_params.ofile.c_str());
203
+ }
204
+
205
+ void IMatrixCollector::keep_imatrix(int ncall) const {
206
+ auto file_name = m_params.ofile;
207
+ if (file_name.empty()) file_name = "imatrix.dat";
208
+ file_name += ".at_";
209
+ file_name += std::to_string(ncall);
210
+ save_imatrix(file_name.c_str());
211
+ }
212
+
213
+ void IMatrixCollector::save_imatrix(const char * fname) const {
214
+ std::ofstream out(fname, std::ios::binary);
215
+ int n_entries = m_stats.size();
216
+ out.write((const char*)&n_entries, sizeof(n_entries));
217
+ for (auto& p : m_stats) {
218
+ int len = p.first.size();
219
+ out.write((const char*)&len, sizeof(len));
220
+ out.write(p.first.c_str(), len);
221
+ out.write((const char*)&p.second.ncall, sizeof(p.second.ncall));
222
+ int nval = p.second.values.size();
223
+ out.write((const char*)&nval, sizeof(nval));
224
+ if (nval > 0) out.write((const char*)p.second.values.data(), nval*sizeof(float));
225
+ }
226
+ if (m_params.verbosity > 0) {
227
+ fprintf(stderr, "\n%s: stored collected data after %d chunks in %s\n",__func__,m_last_call,fname);
228
+ }
229
+ }
230
+
231
+ bool IMatrixCollector::load_imatrix(const char * imatrix_file, std::unordered_map<std::string, Stats>& imatrix_data) {
232
+ std::ifstream in(imatrix_file, std::ios::binary);
233
+ if (!in) {
234
+ printf("%s: failed to open %s\n",__func__,imatrix_file);
235
+ return false;
236
+ }
237
+ int n_entries;
238
+ in.read((char*)&n_entries, sizeof(n_entries));
239
+ if (in.fail() || n_entries < 1) {
240
+ printf("%s: no data in file %s\n", __func__, imatrix_file);
241
+ return false;
242
+ }
243
+ for (int i = 0; i < n_entries; ++i) {
244
+ int len; in.read((char *)&len, sizeof(len));
245
+ std::vector<char> name_as_vec(len+1);
246
+ in.read((char *)name_as_vec.data(), len);
247
+ if (in.fail()) {
248
+ printf("%s: failed reading name for entry %d from %s\n",__func__,i+1,imatrix_file);
249
+ return false;
250
+ }
251
+ name_as_vec[len] = 0;
252
+ std::string name{name_as_vec.data()};
253
+ auto& e = imatrix_data[std::move(name)];
254
+ int ncall;
255
+ in.read((char*)&ncall, sizeof(ncall));
256
+ int nval;
257
+ in.read((char *)&nval, sizeof(nval));
258
+ if (in.fail() || nval < 1) {
259
+ printf("%s: failed reading number of values for entry %d\n",__func__,i);
260
+ imatrix_data = {};
261
+ return false;
262
+ }
263
+ e.values.resize(nval);
264
+ in.read((char*)e.values.data(), nval*sizeof(float));
265
+ if (in.fail()) {
266
+ printf("%s: failed reading data for entry %d\n",__func__,i);
267
+ imatrix_data = {};
268
+ return false;
269
+ }
270
+ e.ncall = ncall;
271
+ }
272
+ return true;
273
+ }
274
+
275
+ bool IMatrixCollector::load_imatrix(const char * file_name, bool add) {
276
+ if (!add) {
277
+ m_stats.clear();
278
+ }
279
+ return load_imatrix(file_name, m_stats);
280
+ }
281
+
282
+ static IMatrixCollector g_collector;
283
+
284
+ static bool ik_collect_imatrix(struct ggml_tensor * t, bool ask, void * user_data) {
285
+ return g_collector.collect_imatrix(t, ask, user_data);
286
+ }
287
+
288
+
289
+ struct results_log_softmax {
290
+ double log_softmax;
291
+ float logit;
292
+ float prob;
293
+ };
294
+
295
+ static std::vector<float> softmax(const std::vector<float>& logits) {
296
+ std::vector<float> probs(logits.size());
297
+ float max_logit = logits[0];
298
+ for (float v : logits) {
299
+ max_logit = std::max(max_logit, v);
300
+ }
301
+ double sum_exp = 0.0;
302
+ for (size_t i = 0; i < logits.size(); i++) {
303
+ // Subtract the maximum logit value from the current logit value for numerical stability
304
+ const float logit = logits[i] - max_logit;
305
+ const float exp_logit = expf(logit);
306
+ sum_exp += exp_logit;
307
+ probs[i] = exp_logit;
308
+ }
309
+ for (size_t i = 0; i < probs.size(); i++) {
310
+ probs[i] /= sum_exp;
311
+ }
312
+ return probs;
313
+ }
314
+
315
+ static results_log_softmax log_softmax(int n_vocab, const float * logits, int tok) {
316
+ float max_logit = logits[0];
317
+ for (int i = 1; i < n_vocab; ++i) {
318
+ max_logit = std::max(max_logit, logits[i]);
319
+ }
320
+ double sum_exp = 0.0;
321
+ for (int i = 0; i < n_vocab; ++i) {
322
+ sum_exp += expf(logits[i] - max_logit);
323
+ }
324
+ return {logits[tok] - max_logit - log(sum_exp), logits[tok], expf(logits[tok] - max_logit) / (float) sum_exp};
325
+ }
326
+
327
+ static void process_logits(
328
+ int n_vocab, const float * logits, const int * tokens, int n_token, std::vector<std::thread> & workers,
329
+ double & nll, double & nll2, float * logit_history, float * prob_history
330
+ ) {
331
+ std::mutex mutex;
332
+ int counter = 0;
333
+ auto compute = [&mutex, &counter, &nll, &nll2, logit_history, prob_history, n_vocab, logits, tokens, n_token] () {
334
+ double local_nll = 0;
335
+ double local_nll2 = 0;
336
+ while (true) {
337
+ std::unique_lock<std::mutex> lock(mutex);
338
+ int i = counter++;
339
+ if (i >= n_token) {
340
+ nll += local_nll; nll2 += local_nll2;
341
+ break;
342
+ }
343
+ lock.unlock();
344
+ const results_log_softmax results = log_softmax(n_vocab, logits + i*n_vocab, tokens[i+1]);
345
+ const double v = -results.log_softmax;
346
+ local_nll += v;
347
+ local_nll2 += v*v;
348
+
349
+ logit_history[i] = results.logit;
350
+ prob_history[i] = results.prob;
351
+ }
352
+ };
353
+ for (auto & w : workers) {
354
+ w = std::thread(compute);
355
+ }
356
+ compute();
357
+ for (auto & w : workers) {
358
+ w.join();
359
+ }
360
+ }
361
+
362
+ static bool compute_imatrix(llama_context * ctx, const gpt_params & params, bool compute_ppl, int from_chunk) {
363
+
364
+ const bool add_bos = llama_should_add_bos_token(llama_get_model(ctx));
365
+ GGML_ASSERT(llama_add_eos_token(llama_get_model(ctx)) != 1);
366
+ const int n_ctx = llama_n_ctx(ctx);
367
+
368
+ auto tim1 = std::chrono::high_resolution_clock::now();
369
+ fprintf(stderr, "%s: tokenizing the input ..\n", __func__);
370
+
371
+ std::vector<llama_token> tokens = ::llama_tokenize(ctx, params.prompt, true);
372
+
373
+ auto tim2 = std::chrono::high_resolution_clock::now();
374
+ fprintf(stderr, "%s: tokenization took %g ms\n",__func__,1e-3*std::chrono::duration_cast<std::chrono::microseconds>(tim2-tim1).count());
375
+
376
+ if (from_chunk > 0) {
377
+ if (size_t((from_chunk + 2)*n_ctx) >= tokens.size()) {
378
+ fprintf(stderr, "%s: there will be not enough tokens left after removing %d chunks\n", __func__, from_chunk);
379
+ return false;
380
+ }
381
+ fprintf(stderr, "%s: removing initial %d chunks (%d tokens)\n", __func__, from_chunk, from_chunk*n_ctx);
382
+ tokens.erase(tokens.begin(), tokens.begin() + from_chunk*n_ctx);
383
+ }
384
+
385
+ if (int(tokens.size()) < 2*n_ctx) {
386
+ fprintf(stderr, "%s: you need at least %d tokens for a context of %d tokens\n",__func__,2*n_ctx,
387
+ n_ctx);
388
+ fprintf(stderr, "%s: the data file you provided tokenizes to only %zu tokens\n",__func__,tokens.size());
389
+ return false;
390
+ }
391
+
392
+ std::vector<float> logit_history;
393
+ std::vector<float> prob_history;
394
+
395
+ if (compute_ppl) {
396
+ logit_history.resize(tokens.size());
397
+ prob_history.resize(tokens.size());
398
+ }
399
+
400
+ const int n_chunk_max = tokens.size() / n_ctx;
401
+
402
+ const int n_chunk = params.n_chunks < 0 ? n_chunk_max : std::min(params.n_chunks, n_chunk_max);
403
+ const int n_vocab = llama_n_vocab(llama_get_model(ctx));
404
+ const int n_batch = params.n_batch;
405
+
406
+ int count = 0;
407
+ double nll = 0.0;
408
+ double nll2 = 0.0;
409
+
410
+ fprintf(stderr, "%s: computing over %d chunks with batch_size %d\n", __func__, n_chunk, n_batch);
411
+
412
+ std::vector<std::thread> workers(std::thread::hardware_concurrency() - 1);
413
+
414
+ const int num_batches = (n_ctx + n_batch - 1) / n_batch;
415
+
416
+ std::vector<float> logits;
417
+ if (compute_ppl && num_batches > 1) {
418
+ logits.reserve((size_t)n_ctx * n_vocab);
419
+ }
420
+
421
+ for (int i = 0; i < n_chunk; ++i) {
422
+ const int start = i * n_ctx;
423
+ const int end = start + n_ctx;
424
+
425
+ std::vector<float> logits;
426
+
427
+ const auto t_start = std::chrono::high_resolution_clock::now();
428
+
429
+ // clear the KV cache
430
+ llama_kv_cache_clear(ctx);
431
+
432
+ for (int j = 0; j < num_batches; ++j) {
433
+ const int batch_start = start + j * n_batch;
434
+ const int batch_size = std::min(end - batch_start, n_batch);
435
+
436
+ // save original token and restore it after eval
437
+ const auto token_org = tokens[batch_start];
438
+
439
+ // add BOS token for the first batch of each chunk
440
+ if (add_bos && j == 0) {
441
+ tokens[batch_start] = llama_token_bos(llama_get_model(ctx));
442
+ }
443
+
444
+ // TODO: use batch.logits to save computations instead of relying on logits_all == true
445
+ if (llama_decode(ctx, llama_batch_get_one(tokens.data() + batch_start, batch_size, j * n_batch, 0))) {
446
+ fprintf(stderr, "%s : failed to eval\n", __func__);
447
+ return false;
448
+ }
449
+
450
+ // restore the original token in case it was set to BOS
451
+ tokens[batch_start] = token_org;
452
+
453
+ if (compute_ppl && num_batches > 1) {
454
+ const auto * batch_logits = llama_get_logits(ctx);
455
+ logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
456
+ }
457
+ }
458
+
459
+ const auto t_end = std::chrono::high_resolution_clock::now();
460
+
461
+ if (i == 0) {
462
+ const float t_total = std::chrono::duration<float>(t_end - t_start).count();
463
+ fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
464
+ int total_seconds = (int)(t_total * n_chunk);
465
+ if (total_seconds >= 60*60) {
466
+ fprintf(stderr, "%d hours ", total_seconds / (60*60));
467
+ total_seconds = total_seconds % (60*60);
468
+ }
469
+ fprintf(stderr, "%.2f minutes\n", total_seconds / 60.0);
470
+ }
471
+
472
+ if (compute_ppl) {
473
+ const int first = n_ctx/2;
474
+ const auto all_logits = num_batches > 1 ? logits.data() : llama_get_logits(ctx);
475
+ process_logits(n_vocab, all_logits + first*n_vocab, tokens.data() + start + first, n_ctx - 1 - first,
476
+ workers, nll, nll2, logit_history.data() + start + first, prob_history.data() + start + first);
477
+ count += n_ctx - first - 1;
478
+
479
+ printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
480
+ fflush(stdout);
481
+
482
+ logits.clear();
483
+ }
484
+ }
485
+ printf("\n");
486
+
487
+ if (compute_ppl) {
488
+ nll2 /= count;
489
+ nll /= count;
490
+ const double ppl = exp(nll);
491
+ nll2 -= nll * nll;
492
+ if (nll2 > 0) {
493
+ nll2 = sqrt(nll2/(count-1));
494
+ printf("Final estimate: PPL = %.4lf +/- %.5lf\n", ppl, nll2*ppl);
495
+ } else {
496
+ printf("Unexpected negative standard deviation of log(prob)\n");
497
+ }
498
+ }
499
+
500
+ return true;
501
+ }
502
+
503
+ int main(int argc, char ** argv) {
504
+
505
+ StatParams sparams;
506
+ std::string prev_result_file;
507
+ std::string combine_files;
508
+ bool compute_ppl = true;
509
+ int from_chunk = 0;
510
+ std::vector<char*> args;
511
+ args.push_back(argv[0]);
512
+ int iarg = 1;
513
+ for (; iarg < argc-1; ++iarg) {
514
+ std::string arg{argv[iarg]};
515
+ if (arg == "-o" || arg == "--output-file") {
516
+ sparams.ofile = argv[++iarg];
517
+ }
518
+ else if (arg == "-ofreq" || arg == "--output-frequency") {
519
+ sparams.n_output_frequency = std::stoi(argv[++iarg]);
520
+ }
521
+ else if (arg == "-ow" || arg == "--output-weight") {
522
+ sparams.collect_output_weight = std::stoi(argv[++iarg]);
523
+ }
524
+ else if (arg == "--verbosity") {
525
+ sparams.verbosity = std::stoi(argv[++iarg]);
526
+ } else if (arg == "--no-ppl") {
527
+ compute_ppl = false;
528
+ } else if (arg == "--keep-imatrix") {
529
+ sparams.keep_every = std::stoi(argv[++iarg]);
530
+ } else if (arg == "--continue-from") {
531
+ prev_result_file = argv[++iarg];
532
+ } else if (arg == "--combine") {
533
+ combine_files = argv[++iarg];
534
+ }
535
+ else if (arg == "--from-chunk") {
536
+ from_chunk = std::stoi(argv[++iarg]);
537
+ } else {
538
+ args.push_back(argv[iarg]);
539
+ }
540
+ }
541
+ if (iarg < argc) {
542
+ std::string arg{argv[iarg]};
543
+ if (arg == "--no-ppl") {
544
+ compute_ppl = false;
545
+ } else {
546
+ args.push_back(argv[iarg]);
547
+ }
548
+ }
549
+
550
+ g_collector.set_parameters(std::move(sparams));
551
+
552
+ if (!combine_files.empty()) {
553
+ std::vector<std::string> files;
554
+ size_t pos = 0;
555
+ while (true) {
556
+ auto new_pos = combine_files.find(',', pos);
557
+ if (new_pos != std::string::npos) {
558
+ files.emplace_back(combine_files.substr(pos, new_pos - pos));
559
+ pos = new_pos + 1;
560
+ } else {
561
+ files.emplace_back(combine_files.substr(pos));
562
+ break;
563
+ }
564
+ }
565
+ if (files.size() < 2) {
566
+ fprintf(stderr, "You must provide at least two comma separated files to use --combine\n");
567
+ return 1;
568
+ }
569
+ printf("Combining the following %d files\n", int(files.size()));
570
+ for (auto& file : files) {
571
+ printf(" %s\n", file.c_str());
572
+ if (!g_collector.load_imatrix(file.c_str(), true)) {
573
+ fprintf(stderr, "Failed to load %s\n", file.c_str());
574
+ return 1;
575
+ }
576
+ }
577
+ g_collector.save_imatrix();
578
+ return 0;
579
+ }
580
+
581
+ if (!prev_result_file.empty()) {
582
+ if (!g_collector.load_imatrix(prev_result_file.c_str(), false)) {
583
+ fprintf(stderr, "=============== Failed to load %s\n", prev_result_file.c_str());
584
+ return 1;
585
+ }
586
+ }
587
+
588
+ gpt_params params;
589
+ params.n_batch = 512;
590
+ if (!gpt_params_parse(args.size(), args.data(), params)) {
591
+ return 1;
592
+ }
593
+
594
+ params.logits_all = true;
595
+ params.n_batch = std::min(params.n_batch, params.n_ctx);
596
+
597
+ print_build_info();
598
+
599
+ if (params.seed == LLAMA_DEFAULT_SEED) {
600
+ params.seed = time(NULL);
601
+ }
602
+
603
+ fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
604
+
605
+ std::mt19937 rng(params.seed);
606
+ if (params.random_prompt) {
607
+ params.prompt = gpt_random_prompt(rng);
608
+ }
609
+
610
+ llama_backend_init();
611
+ llama_numa_init(params.numa);
612
+
613
+ // pass the callback to the backend scheduler
614
+ // it will be executed for each node during the graph computation
615
+ params.cb_eval = ik_collect_imatrix;
616
+ params.cb_eval_user_data = NULL;
617
+ params.warmup = false;
618
+
619
+ // init
620
+ llama_model * model;
621
+ llama_context * ctx;
622
+ std::tie(model, ctx) = llama_init_from_gpt_params(params);
623
+ if (model == nullptr || ctx == nullptr) {
624
+ fprintf(stderr, "%s : failed to init\n", __func__);
625
+ return 1;
626
+ }
627
+
628
+ const int n_ctx_train = llama_n_ctx_train(model);
629
+ if (params.n_ctx > n_ctx_train) {
630
+ fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
631
+ __func__, n_ctx_train, params.n_ctx);
632
+ }
633
+
634
+ // print system information
635
+ {
636
+ fprintf(stderr, "\n");
637
+ fprintf(stderr, "%s\n", get_system_info(params).c_str());
638
+ }
639
+
640
+ bool OK = compute_imatrix(ctx, params, compute_ppl, from_chunk);
641
+ if (!OK) {
642
+ return 1;
643
+ }
644
+
645
+ g_collector.save_imatrix();
646
+
647
+ llama_print_timings(ctx);
648
+
649
+ llama_free(ctx);
650
+ llama_free_model(model);
651
+
652
+ llama_backend_free();
653
+
654
+ return 0;
655
+ }
@@ -0,0 +1,5 @@
1
+ set(TARGET infill)
2
+ add_executable(${TARGET} infill.cpp)
3
+ install(TARGETS ${TARGET} RUNTIME)
4
+ target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
5
+ target_compile_features(${TARGET} PRIVATE cxx_std_11)