cui-llama.rn 1.4.3 → 1.4.6

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 (134) hide show
  1. package/README.md +93 -114
  2. package/android/src/main/CMakeLists.txt +5 -0
  3. package/android/src/main/java/com/rnllama/LlamaContext.java +91 -17
  4. package/android/src/main/java/com/rnllama/RNLlama.java +37 -4
  5. package/android/src/main/jni-utils.h +6 -0
  6. package/android/src/main/jni.cpp +289 -31
  7. package/android/src/main/jniLibs/arm64-v8a/librnllama.so +0 -0
  8. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8.so +0 -0
  9. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2.so +0 -0
  10. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_dotprod.so +0 -0
  11. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_dotprod_i8mm.so +0 -0
  12. package/android/src/main/jniLibs/arm64-v8a/librnllama_v8_2_i8mm.so +0 -0
  13. package/android/src/main/jniLibs/x86_64/librnllama.so +0 -0
  14. package/android/src/main/jniLibs/x86_64/librnllama_x86_64.so +0 -0
  15. package/android/src/newarch/java/com/rnllama/RNLlamaModule.java +7 -2
  16. package/android/src/oldarch/java/com/rnllama/RNLlamaModule.java +7 -2
  17. package/cpp/chat-template.hpp +529 -0
  18. package/cpp/chat.cpp +1779 -0
  19. package/cpp/chat.h +135 -0
  20. package/cpp/common.cpp +2064 -1873
  21. package/cpp/common.h +700 -699
  22. package/cpp/ggml-alloc.c +1039 -1042
  23. package/cpp/ggml-alloc.h +1 -1
  24. package/cpp/ggml-backend-impl.h +255 -255
  25. package/cpp/ggml-backend-reg.cpp +586 -582
  26. package/cpp/ggml-backend.cpp +2004 -2002
  27. package/cpp/ggml-backend.h +354 -354
  28. package/cpp/ggml-common.h +1851 -1853
  29. package/cpp/ggml-cpp.h +39 -39
  30. package/cpp/ggml-cpu-aarch64.cpp +4248 -4247
  31. package/cpp/ggml-cpu-aarch64.h +8 -8
  32. package/cpp/ggml-cpu-impl.h +531 -386
  33. package/cpp/ggml-cpu-quants.c +12527 -10920
  34. package/cpp/ggml-cpu-traits.cpp +36 -36
  35. package/cpp/ggml-cpu-traits.h +38 -38
  36. package/cpp/ggml-cpu.c +15766 -14391
  37. package/cpp/ggml-cpu.cpp +655 -635
  38. package/cpp/ggml-cpu.h +138 -135
  39. package/cpp/ggml-impl.h +567 -567
  40. package/cpp/ggml-metal-impl.h +235 -0
  41. package/cpp/ggml-metal.h +1 -1
  42. package/cpp/ggml-metal.m +5146 -4884
  43. package/cpp/ggml-opt.cpp +854 -854
  44. package/cpp/ggml-opt.h +216 -216
  45. package/cpp/ggml-quants.c +5238 -5238
  46. package/cpp/ggml-threading.h +14 -14
  47. package/cpp/ggml.c +6529 -6514
  48. package/cpp/ggml.h +2198 -2194
  49. package/cpp/gguf.cpp +1329 -1329
  50. package/cpp/gguf.h +202 -202
  51. package/cpp/json-schema-to-grammar.cpp +1024 -1045
  52. package/cpp/json-schema-to-grammar.h +21 -8
  53. package/cpp/json.hpp +24766 -24766
  54. package/cpp/llama-adapter.cpp +347 -347
  55. package/cpp/llama-adapter.h +74 -74
  56. package/cpp/llama-arch.cpp +1513 -1487
  57. package/cpp/llama-arch.h +403 -400
  58. package/cpp/llama-batch.cpp +368 -368
  59. package/cpp/llama-batch.h +88 -88
  60. package/cpp/llama-chat.cpp +588 -578
  61. package/cpp/llama-chat.h +53 -52
  62. package/cpp/llama-context.cpp +1775 -1775
  63. package/cpp/llama-context.h +128 -128
  64. package/cpp/llama-cparams.cpp +1 -1
  65. package/cpp/llama-cparams.h +37 -37
  66. package/cpp/llama-cpp.h +30 -30
  67. package/cpp/llama-grammar.cpp +1219 -1139
  68. package/cpp/llama-grammar.h +173 -143
  69. package/cpp/llama-hparams.cpp +71 -71
  70. package/cpp/llama-hparams.h +139 -139
  71. package/cpp/llama-impl.cpp +167 -167
  72. package/cpp/llama-impl.h +61 -61
  73. package/cpp/llama-kv-cache.cpp +718 -718
  74. package/cpp/llama-kv-cache.h +219 -218
  75. package/cpp/llama-mmap.cpp +600 -590
  76. package/cpp/llama-mmap.h +68 -67
  77. package/cpp/llama-model-loader.cpp +1124 -1124
  78. package/cpp/llama-model-loader.h +167 -167
  79. package/cpp/llama-model.cpp +4087 -3997
  80. package/cpp/llama-model.h +370 -370
  81. package/cpp/llama-sampling.cpp +2558 -2408
  82. package/cpp/llama-sampling.h +32 -32
  83. package/cpp/llama-vocab.cpp +3264 -3247
  84. package/cpp/llama-vocab.h +125 -125
  85. package/cpp/llama.cpp +10284 -10077
  86. package/cpp/llama.h +1354 -1323
  87. package/cpp/log.cpp +393 -401
  88. package/cpp/log.h +132 -121
  89. package/cpp/minja/chat-template.hpp +529 -0
  90. package/cpp/minja/minja.hpp +2915 -0
  91. package/cpp/minja.hpp +2915 -0
  92. package/cpp/rn-llama.cpp +66 -6
  93. package/cpp/rn-llama.h +26 -1
  94. package/cpp/sampling.cpp +570 -505
  95. package/cpp/sampling.h +3 -0
  96. package/cpp/sgemm.cpp +2598 -2597
  97. package/cpp/sgemm.h +14 -14
  98. package/cpp/speculative.cpp +278 -277
  99. package/cpp/speculative.h +28 -28
  100. package/cpp/unicode.cpp +9 -2
  101. package/ios/CMakeLists.txt +6 -0
  102. package/ios/RNLlama.h +0 -8
  103. package/ios/RNLlama.mm +27 -3
  104. package/ios/RNLlamaContext.h +10 -1
  105. package/ios/RNLlamaContext.mm +269 -57
  106. package/jest/mock.js +21 -2
  107. package/lib/commonjs/NativeRNLlama.js.map +1 -1
  108. package/lib/commonjs/grammar.js +3 -0
  109. package/lib/commonjs/grammar.js.map +1 -1
  110. package/lib/commonjs/index.js +87 -13
  111. package/lib/commonjs/index.js.map +1 -1
  112. package/lib/module/NativeRNLlama.js.map +1 -1
  113. package/lib/module/grammar.js +3 -0
  114. package/lib/module/grammar.js.map +1 -1
  115. package/lib/module/index.js +86 -13
  116. package/lib/module/index.js.map +1 -1
  117. package/lib/typescript/NativeRNLlama.d.ts +107 -2
  118. package/lib/typescript/NativeRNLlama.d.ts.map +1 -1
  119. package/lib/typescript/grammar.d.ts.map +1 -1
  120. package/lib/typescript/index.d.ts +32 -7
  121. package/lib/typescript/index.d.ts.map +1 -1
  122. package/llama-rn.podspec +1 -1
  123. package/package.json +3 -2
  124. package/src/NativeRNLlama.ts +115 -3
  125. package/src/grammar.ts +3 -0
  126. package/src/index.ts +138 -21
  127. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CMakeCCompiler.cmake +0 -81
  128. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CMakeSystem.cmake +0 -15
  129. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CompilerIdC/CMakeCCompilerId.c +0 -904
  130. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CompilerIdC/CMakeCCompilerId.o +0 -0
  131. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CompilerIdCXX/CMakeCXXCompilerId.cpp +0 -919
  132. package/android/src/main/build-arm64/CMakeFiles/3.31.4/CompilerIdCXX/CMakeCXXCompilerId.o +0 -0
  133. package/android/src/main/build-arm64/CMakeFiles/CMakeConfigureLog.yaml +0 -55
  134. package/cpp/rn-llama.hpp +0 -913
package/cpp/sampling.cpp CHANGED
@@ -1,505 +1,570 @@
1
- #include "sampling.h"
2
-
3
- #include "common.h"
4
-
5
- #include <cmath>
6
- #include <unordered_map>
7
-
8
- // the ring buffer works similarly to std::deque, but with a fixed capacity
9
- // TODO: deduplicate with llama-impl.h
10
- template<typename T>
11
- struct ring_buffer {
12
- ring_buffer(size_t cap) : capacity(cap), data(cap) {}
13
-
14
- T & front() {
15
- if (sz == 0) {
16
- throw std::runtime_error("ring buffer is empty");
17
- }
18
- return data[first];
19
- }
20
-
21
- const T & front() const {
22
- if (sz == 0) {
23
- throw std::runtime_error("ring buffer is empty");
24
- }
25
- return data[first];
26
- }
27
-
28
- T & back() {
29
- if (sz == 0) {
30
- throw std::runtime_error("ring buffer is empty");
31
- }
32
- return data[pos];
33
- }
34
-
35
- const T & back() const {
36
- if (sz == 0) {
37
- throw std::runtime_error("ring buffer is empty");
38
- }
39
- return data[pos];
40
- }
41
-
42
- void push_back(const T & value) {
43
- if (sz == capacity) {
44
- // advance the start when buffer is full
45
- first = (first + 1) % capacity;
46
- } else {
47
- sz++;
48
- }
49
- data[pos] = value;
50
- pos = (pos + 1) % capacity;
51
- }
52
-
53
- T pop_front() {
54
- if (sz == 0) {
55
- throw std::runtime_error("ring buffer is empty");
56
- }
57
- T value = data[first];
58
- first = (first + 1) % capacity;
59
- sz--;
60
- return value;
61
- }
62
-
63
- const T & rat(size_t i) const {
64
- if (i >= sz) {
65
- throw std::runtime_error("ring buffer: index out of bounds");
66
- }
67
- return data[(first + sz - i - 1) % capacity];
68
- }
69
-
70
- std::vector<T> to_vector() const {
71
- std::vector<T> result;
72
- result.reserve(sz);
73
- for (size_t i = 0; i < sz; i++) {
74
- result.push_back(data[(first + i) % capacity]);
75
- }
76
- return result;
77
- }
78
-
79
- void clear() {
80
- // here only reset the status of the buffer
81
- sz = 0;
82
- first = 0;
83
- pos = 0;
84
- }
85
-
86
- bool empty() const {
87
- return sz == 0;
88
- }
89
-
90
- size_t size() const {
91
- return sz;
92
- }
93
-
94
- size_t capacity = 0;
95
- size_t sz = 0;
96
- size_t first = 0;
97
- size_t pos = 0;
98
- std::vector<T> data;
99
- };
100
-
101
- struct common_sampler {
102
- common_params_sampling params;
103
-
104
- struct llama_sampler * grmr;
105
- struct llama_sampler * chain;
106
-
107
- ring_buffer<llama_token> prev;
108
-
109
- std::vector<llama_token_data> cur;
110
-
111
- llama_token_data_array cur_p;
112
-
113
- void set_logits(struct llama_context * ctx, int idx) {
114
- const auto * logits = llama_get_logits_ith(ctx, idx);
115
-
116
- const llama_model * model = llama_get_model(ctx);
117
- const llama_vocab * vocab = llama_model_get_vocab(model);
118
-
119
- const int n_vocab = llama_vocab_n_tokens(vocab);
120
-
121
- cur.resize(n_vocab);
122
-
123
- for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
124
- cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
125
- }
126
-
127
- cur_p = { cur.data(), cur.size(), -1, false };
128
- }
129
- };
130
-
131
- std::string common_params_sampling::print() const {
132
- char result[1024];
133
-
134
- snprintf(result, sizeof(result),
135
- "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
136
- "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
137
- "\ttop_k = %d, top_p = %.3f, min_p = %.3f, xtc_probability = %.3f, xtc_threshold = %.3f, typical_p = %.3f, temp = %.3f\n"
138
- "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
139
- penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
140
- dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
141
- top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, temp,
142
- mirostat, mirostat_eta, mirostat_tau);
143
-
144
- return std::string(result);
145
- }
146
-
147
- struct common_sampler * common_sampler_init(const struct llama_model * model, const struct common_params_sampling & params) {
148
- const llama_vocab * vocab = llama_model_get_vocab(model);
149
-
150
- llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
151
-
152
- lparams.no_perf = params.no_perf;
153
-
154
- auto * result = new common_sampler {
155
- /* .params = */ params,
156
- /* .grmr = */ llama_sampler_init_grammar(vocab, params.grammar.c_str(), "root"),
157
- /* .chain = */ llama_sampler_chain_init(lparams),
158
- /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
159
- /* .cur = */ {},
160
- /* .cur_p = */ {},
161
- };
162
-
163
- llama_sampler_chain_add(result->chain,
164
- llama_sampler_init_logit_bias(
165
- llama_vocab_n_tokens(vocab),
166
- params.logit_bias.size(),
167
- params.logit_bias.data()));
168
-
169
- if (params.mirostat == 0) {
170
- for (const auto & cnstr : params.samplers) {
171
- switch (cnstr) {
172
- case COMMON_SAMPLER_TYPE_DRY:
173
- {
174
- std::vector<const char *> c_breakers;
175
- c_breakers.reserve(params.dry_sequence_breakers.size());
176
- for (const auto & str : params.dry_sequence_breakers) {
177
- c_breakers.push_back(str.c_str());
178
- }
179
-
180
- llama_sampler_chain_add(result->chain, llama_sampler_init_dry (vocab, llama_model_n_ctx_train(model), params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
181
- }
182
- break;
183
- case COMMON_SAMPLER_TYPE_TOP_K:
184
- llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
185
- break;
186
- case COMMON_SAMPLER_TYPE_TOP_P:
187
- llama_sampler_chain_add(result->chain, llama_sampler_init_top_p (params.top_p, params.min_keep));
188
- break;
189
- case COMMON_SAMPLER_TYPE_MIN_P:
190
- llama_sampler_chain_add(result->chain, llama_sampler_init_min_p (params.min_p, params.min_keep));
191
- break;
192
- case COMMON_SAMPLER_TYPE_XTC:
193
- llama_sampler_chain_add(result->chain, llama_sampler_init_xtc (params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
194
- break;
195
- case COMMON_SAMPLER_TYPE_TYPICAL_P:
196
- llama_sampler_chain_add(result->chain, llama_sampler_init_typical (params.typ_p, params.min_keep));
197
- break;
198
- case COMMON_SAMPLER_TYPE_TEMPERATURE:
199
- llama_sampler_chain_add(result->chain, llama_sampler_init_temp_ext (params.temp, params.dynatemp_range, params.dynatemp_exponent));
200
- break;
201
- case COMMON_SAMPLER_TYPE_INFILL:
202
- llama_sampler_chain_add(result->chain, llama_sampler_init_infill (vocab));
203
- break;
204
- case COMMON_SAMPLER_TYPE_PENALTIES:
205
- llama_sampler_chain_add(result->chain, llama_sampler_init_penalties(params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
206
- break;
207
- default:
208
- LM_GGML_ASSERT(false && "unknown sampler type");
209
- }
210
- }
211
- llama_sampler_chain_add(result->chain, llama_sampler_init_dist(params.seed));
212
- } else if (params.mirostat == 1) {
213
- llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
214
- llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
215
- } else if (params.mirostat == 2) {
216
- llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
217
- llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
218
- } else {
219
- LM_GGML_ASSERT(false && "unknown mirostat version");
220
- }
221
-
222
- return result;
223
- }
224
-
225
- void common_sampler_free(struct common_sampler * gsmpl) {
226
- if (gsmpl) {
227
- llama_sampler_free(gsmpl->grmr);
228
-
229
- llama_sampler_free(gsmpl->chain);
230
-
231
- delete gsmpl;
232
- }
233
- }
234
-
235
- void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
236
- if (accept_grammar) {
237
- llama_sampler_accept(gsmpl->grmr, token);
238
- }
239
-
240
- llama_sampler_accept(gsmpl->chain, token);
241
-
242
- gsmpl->prev.push_back(token);
243
- }
244
-
245
- void common_sampler_reset(struct common_sampler * gsmpl) {
246
- llama_sampler_reset(gsmpl->grmr);
247
-
248
- llama_sampler_reset(gsmpl->chain);
249
- }
250
-
251
- struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
252
- return new common_sampler {
253
- /* .params = */ gsmpl->params,
254
- /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
255
- /* .chain = */ llama_sampler_clone(gsmpl->chain),
256
- /* .prev = */ gsmpl->prev,
257
- /* .cur = */ gsmpl->cur,
258
- /* .cur_p = */ gsmpl->cur_p,
259
- };
260
- }
261
-
262
- void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
263
- // TODO: measure grammar performance
264
-
265
- if (gsmpl) {
266
- llama_perf_sampler_print(gsmpl->chain);
267
- }
268
- if (ctx) {
269
- llama_perf_context_print(ctx);
270
- }
271
- }
272
-
273
- llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
274
- gsmpl->set_logits(ctx, idx);
275
-
276
- auto & grmr = gsmpl->grmr;
277
- auto & chain = gsmpl->chain;
278
- auto & cur_p = gsmpl->cur_p; // initialized by set_logits
279
-
280
- if (grammar_first) {
281
- llama_sampler_apply(grmr, &cur_p);
282
- }
283
-
284
- llama_sampler_apply(chain, &cur_p);
285
-
286
- LM_GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
287
-
288
- const llama_token id = cur_p.data[cur_p.selected].id;
289
-
290
- if (grammar_first) {
291
- return id;
292
- }
293
-
294
- // check if it the sampled token fits the grammar
295
- {
296
- llama_token_data single_token_data = { id, 1.0f, 0.0f };
297
- llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
298
-
299
- llama_sampler_apply(grmr, &single_token_data_array);
300
-
301
- const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
302
- if (is_valid) {
303
- return id;
304
- }
305
- }
306
-
307
- // resampling:
308
- // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
309
- gsmpl->set_logits(ctx, idx);
310
-
311
- llama_sampler_apply(grmr, &cur_p);
312
- llama_sampler_apply(chain, &cur_p);
313
-
314
- LM_GGML_ASSERT(cur_p.selected != -1 && "no selected token during re-sampling - check your sampling configuration");
315
-
316
- return cur_p.data[cur_p.selected].id;
317
- }
318
-
319
- std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
320
- LM_GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
321
-
322
- std::vector<llama_token> result;
323
- result.reserve(idxs.size());
324
-
325
- size_t i = 0;
326
- for (; i < draft.size(); i++) {
327
- const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
328
-
329
- common_sampler_accept(gsmpl, id, true);
330
-
331
- result.push_back(id);
332
-
333
- if (draft[i] != id) {
334
- break;
335
- }
336
- }
337
-
338
- if (i == draft.size()) {
339
- const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
340
-
341
- common_sampler_accept(gsmpl, id, true);
342
-
343
- result.push_back(id);
344
- }
345
-
346
- return result;
347
- }
348
-
349
- std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
350
- std::vector<int> idxs(draft.size() + 1);
351
- for (size_t i = 0; i < idxs.size(); ++i) {
352
- idxs[i] = i;
353
- }
354
-
355
- return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
356
- }
357
-
358
- uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
359
- return llama_sampler_get_seed(gsmpl->chain);
360
- }
361
-
362
- // helpers
363
-
364
- llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl) {
365
- return &gsmpl->cur_p;
366
- }
367
-
368
- llama_token common_sampler_last(const struct common_sampler * gsmpl) {
369
- return gsmpl->prev.rat(0);
370
- }
371
-
372
- std::string common_sampler_print(const struct common_sampler * gsmpl) {
373
- std::string result = "logits ";
374
-
375
- for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
376
- const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
377
- result += std::string("-> ") + llama_sampler_name(smpl) + " ";
378
- }
379
-
380
- return result;
381
- }
382
-
383
- std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
384
- n = std::min(n, (int) gsmpl->prev.size());
385
-
386
- if (n <= 0) {
387
- return "";
388
- }
389
-
390
- std::string result;
391
- result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
392
-
393
- for (int i = n - 1; i >= 0; i--) {
394
- const llama_token id = gsmpl->prev.rat(i);
395
-
396
- LM_GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
397
-
398
- result += common_token_to_piece(ctx_main, id);
399
- }
400
-
401
- return result;
402
- }
403
-
404
- char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
405
- switch (cnstr) {
406
- case COMMON_SAMPLER_TYPE_DRY: return 'd';
407
- case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
408
- case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
409
- case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
410
- case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
411
- case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
412
- case COMMON_SAMPLER_TYPE_XTC: return 'x';
413
- case COMMON_SAMPLER_TYPE_INFILL: return 'i';
414
- case COMMON_SAMPLER_TYPE_PENALTIES: return 'e';
415
- default : return '?';
416
- }
417
- }
418
-
419
- std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
420
- switch (cnstr) {
421
- case COMMON_SAMPLER_TYPE_DRY: return "dry";
422
- case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
423
- case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
424
- case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
425
- case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
426
- case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
427
- case COMMON_SAMPLER_TYPE_XTC: return "xtc";
428
- case COMMON_SAMPLER_TYPE_INFILL: return "infill";
429
- case COMMON_SAMPLER_TYPE_PENALTIES: return "penalties";
430
- default : return "";
431
- }
432
- }
433
-
434
- std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
435
- std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
436
- { "dry", COMMON_SAMPLER_TYPE_DRY },
437
- { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
438
- { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
439
- { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
440
- { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
441
- { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
442
- { "xtc", COMMON_SAMPLER_TYPE_XTC },
443
- { "infill", COMMON_SAMPLER_TYPE_INFILL },
444
- { "penalties", COMMON_SAMPLER_TYPE_PENALTIES },
445
- };
446
-
447
- // since samplers names are written multiple ways
448
- // make it ready for both system names and input names
449
- std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
450
- { "top-k", COMMON_SAMPLER_TYPE_TOP_K },
451
- { "top-p", COMMON_SAMPLER_TYPE_TOP_P },
452
- { "nucleus", COMMON_SAMPLER_TYPE_TOP_P },
453
- { "typical-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
454
- { "typical", COMMON_SAMPLER_TYPE_TYPICAL_P },
455
- { "typ-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
456
- { "typ", COMMON_SAMPLER_TYPE_TYPICAL_P },
457
- { "min-p", COMMON_SAMPLER_TYPE_MIN_P },
458
- { "temp", COMMON_SAMPLER_TYPE_TEMPERATURE },
459
- };
460
-
461
- std::vector<common_sampler_type> samplers;
462
- samplers.reserve(names.size());
463
-
464
- for (const auto & name : names) {
465
- auto sampler = sampler_canonical_name_map.find(name);
466
- if (sampler != sampler_canonical_name_map.end()) {
467
- samplers.push_back(sampler->second);
468
- } else {
469
- if (allow_alt_names) {
470
- sampler = sampler_alt_name_map.find(name);
471
- if (sampler != sampler_alt_name_map.end()) {
472
- samplers.push_back(sampler->second);
473
- }
474
- }
475
- }
476
- }
477
-
478
- return samplers;
479
- }
480
-
481
- std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
482
- std::unordered_map<char, common_sampler_type> sampler_name_map = {
483
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
484
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
485
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
486
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
487
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
488
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
489
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
490
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
491
- { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES), COMMON_SAMPLER_TYPE_PENALTIES },
492
- };
493
-
494
- std::vector<common_sampler_type> samplers;
495
- samplers.reserve(chars.size());
496
-
497
- for (const auto & c : chars) {
498
- const auto sampler = sampler_name_map.find(c);
499
- if (sampler != sampler_name_map.end()) {
500
- samplers.push_back(sampler->second);
501
- }
502
- }
503
-
504
- return samplers;
505
- }
1
+ #include "sampling.h"
2
+
3
+ #include "common.h"
4
+
5
+ #include <cmath>
6
+ #include <unordered_map>
7
+ #include <algorithm>
8
+
9
+ // the ring buffer works similarly to std::deque, but with a fixed capacity
10
+ // TODO: deduplicate with llama-impl.h
11
+ template<typename T>
12
+ struct ring_buffer {
13
+ ring_buffer(size_t cap) : capacity(cap), data(cap) {}
14
+
15
+ T & front() {
16
+ if (sz == 0) {
17
+ throw std::runtime_error("ring buffer is empty");
18
+ }
19
+ return data[first];
20
+ }
21
+
22
+ const T & front() const {
23
+ if (sz == 0) {
24
+ throw std::runtime_error("ring buffer is empty");
25
+ }
26
+ return data[first];
27
+ }
28
+
29
+ T & back() {
30
+ if (sz == 0) {
31
+ throw std::runtime_error("ring buffer is empty");
32
+ }
33
+ return data[pos];
34
+ }
35
+
36
+ const T & back() const {
37
+ if (sz == 0) {
38
+ throw std::runtime_error("ring buffer is empty");
39
+ }
40
+ return data[pos];
41
+ }
42
+
43
+ void push_back(const T & value) {
44
+ if (sz == capacity) {
45
+ // advance the start when buffer is full
46
+ first = (first + 1) % capacity;
47
+ } else {
48
+ sz++;
49
+ }
50
+ data[pos] = value;
51
+ pos = (pos + 1) % capacity;
52
+ }
53
+
54
+ T pop_front() {
55
+ if (sz == 0) {
56
+ throw std::runtime_error("ring buffer is empty");
57
+ }
58
+ T value = data[first];
59
+ first = (first + 1) % capacity;
60
+ sz--;
61
+ return value;
62
+ }
63
+
64
+ const T & rat(size_t i) const {
65
+ if (i >= sz) {
66
+ throw std::runtime_error("ring buffer: index out of bounds");
67
+ }
68
+ return data[(first + sz - i - 1) % capacity];
69
+ }
70
+
71
+ std::vector<T> to_vector() const {
72
+ std::vector<T> result;
73
+ result.reserve(sz);
74
+ for (size_t i = 0; i < sz; i++) {
75
+ result.push_back(data[(first + i) % capacity]);
76
+ }
77
+ return result;
78
+ }
79
+
80
+ void clear() {
81
+ // here only reset the status of the buffer
82
+ sz = 0;
83
+ first = 0;
84
+ pos = 0;
85
+ }
86
+
87
+ bool empty() const {
88
+ return sz == 0;
89
+ }
90
+
91
+ size_t size() const {
92
+ return sz;
93
+ }
94
+
95
+ size_t capacity = 0;
96
+ size_t sz = 0;
97
+ size_t first = 0;
98
+ size_t pos = 0;
99
+ std::vector<T> data;
100
+ };
101
+
102
+ struct common_sampler {
103
+ common_params_sampling params;
104
+
105
+ struct llama_sampler * grmr;
106
+ struct llama_sampler * chain;
107
+
108
+ ring_buffer<llama_token> prev;
109
+
110
+ std::vector<llama_token_data> cur;
111
+
112
+ llama_token_data_array cur_p;
113
+
114
+ void set_logits(struct llama_context * ctx, int idx) {
115
+ const auto * logits = llama_get_logits_ith(ctx, idx);
116
+
117
+ const llama_model * model = llama_get_model(ctx);
118
+ const llama_vocab * vocab = llama_model_get_vocab(model);
119
+
120
+ const int n_vocab = llama_vocab_n_tokens(vocab);
121
+
122
+ cur.resize(n_vocab);
123
+
124
+ for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
125
+ cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
126
+ }
127
+
128
+ cur_p = { cur.data(), cur.size(), -1, false };
129
+ }
130
+ };
131
+
132
+ std::string common_params_sampling::print() const {
133
+ char result[1024];
134
+
135
+ snprintf(result, sizeof(result),
136
+ "\trepeat_last_n = %d, repeat_penalty = %.3f, frequency_penalty = %.3f, presence_penalty = %.3f\n"
137
+ "\tdry_multiplier = %.3f, dry_base = %.3f, dry_allowed_length = %d, dry_penalty_last_n = %d\n"
138
+ "\ttop_k = %d, top_p = %.3f, min_p = %.3f, xtc_probability = %.3f, xtc_threshold = %.3f, typical_p = %.3f, top_n_sigma = %.3f, temp = %.3f\n"
139
+ "\tmirostat = %d, mirostat_lr = %.3f, mirostat_ent = %.3f",
140
+ penalty_last_n, penalty_repeat, penalty_freq, penalty_present,
141
+ dry_multiplier, dry_base, dry_allowed_length, dry_penalty_last_n,
142
+ top_k, top_p, min_p, xtc_probability, xtc_threshold, typ_p, top_n_sigma, temp,
143
+ mirostat, mirostat_eta, mirostat_tau);
144
+
145
+ return std::string(result);
146
+ }
147
+
148
+ struct common_sampler * common_sampler_init(const struct llama_model * model, const struct common_params_sampling & params) {
149
+ const llama_vocab * vocab = llama_model_get_vocab(model);
150
+
151
+ llama_sampler_chain_params lparams = llama_sampler_chain_default_params();
152
+
153
+ lparams.no_perf = params.no_perf;
154
+
155
+ struct llama_sampler * grmr;
156
+ if (params.grammar.compare(0, 11, "%llguidance") == 0) {
157
+ #ifdef LLAMA_USE_LLGUIDANCE
158
+ grmr = llama_sampler_init_llg(vocab, "lark", params.grammar.c_str());
159
+ #else
160
+ LM_GGML_ABORT("llguidance (cmake -DLLAMA_LLGUIDANCE=ON) is not enabled");
161
+ #endif // LLAMA_USE_LLGUIDANCE
162
+ } else {
163
+ std::vector<std::string> patterns_at_start;
164
+ std::vector<std::string> patterns_anywhere;
165
+ std::vector<llama_token> trigger_tokens;
166
+ for (const auto & trigger : params.grammar_triggers) {
167
+ switch (trigger.type) {
168
+ case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
169
+ {
170
+ const auto & word = trigger.value;
171
+ patterns_anywhere.push_back(regex_escape(word));
172
+ break;
173
+ }
174
+ case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
175
+ case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START:
176
+ {
177
+ const auto & pattern = trigger.value;
178
+ (trigger.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START ? patterns_at_start : patterns_anywhere).push_back(pattern);
179
+ break;
180
+ }
181
+ case COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN:
182
+ {
183
+ const auto token = trigger.token;
184
+ trigger_tokens.push_back(token);
185
+ break;
186
+ }
187
+ default:
188
+ LM_GGML_ASSERT(false && "unknown trigger type");
189
+ }
190
+ }
191
+
192
+ std::vector<std::string> trigger_patterns;
193
+ if (!patterns_at_start.empty()) {
194
+ trigger_patterns.push_back("^(" + string_join(patterns_at_start, "|") + ")[\\s\\S]*");
195
+ }
196
+ if (!patterns_anywhere.empty()) {
197
+ trigger_patterns.push_back("^[\\s\\S]*?(" + string_join(patterns_anywhere, "|") + ")[\\s\\S]*");
198
+ }
199
+
200
+ std::vector<const char *> trigger_patterns_c;
201
+ trigger_patterns_c.reserve(trigger_patterns.size());
202
+ for (const auto & regex : trigger_patterns) {
203
+ trigger_patterns_c.push_back(regex.c_str());
204
+ }
205
+
206
+ grmr = params.grammar_lazy
207
+ ? llama_sampler_init_grammar_lazy_patterns(vocab, params.grammar.c_str(), "root",
208
+ trigger_patterns_c.data(), trigger_patterns_c.size(),
209
+ trigger_tokens.data(), trigger_tokens.size())
210
+ : llama_sampler_init_grammar(vocab, params.grammar.c_str(), "root");
211
+ }
212
+
213
+ auto * result = new common_sampler {
214
+ /* .params = */ params,
215
+ /* .grmr = */ grmr,
216
+ /* .chain = */ llama_sampler_chain_init(lparams),
217
+ /* .prev = */ ring_buffer<llama_token>(std::max(32, params.n_prev)),
218
+ /* .cur = */ {},
219
+ /* .cur_p = */ {},
220
+ };
221
+
222
+ llama_sampler_chain_add(result->chain,
223
+ llama_sampler_init_logit_bias(
224
+ llama_vocab_n_tokens(vocab),
225
+ params.logit_bias.size(),
226
+ params.logit_bias.data()));
227
+
228
+ if (params.mirostat == 0) {
229
+ if (params.top_n_sigma >= 0) {
230
+ llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
231
+ llama_sampler_chain_add(result->chain, llama_sampler_init_temp (params.temp));
232
+ llama_sampler_chain_add(result->chain, llama_sampler_init_top_n_sigma (params.top_n_sigma));
233
+ } else {
234
+ for (const auto & cnstr : params.samplers) {
235
+ switch (cnstr) {
236
+ case COMMON_SAMPLER_TYPE_DRY:
237
+ {
238
+ std::vector<const char *> c_breakers;
239
+ c_breakers.reserve(params.dry_sequence_breakers.size());
240
+ for (const auto & str : params.dry_sequence_breakers) {
241
+ c_breakers.push_back(str.c_str());
242
+ }
243
+
244
+ llama_sampler_chain_add(result->chain, llama_sampler_init_dry (vocab, llama_model_n_ctx_train(model), params.dry_multiplier, params.dry_base, params.dry_allowed_length, params.dry_penalty_last_n, c_breakers.data(), c_breakers.size()));
245
+ }
246
+ break;
247
+ case COMMON_SAMPLER_TYPE_TOP_K:
248
+ llama_sampler_chain_add(result->chain, llama_sampler_init_top_k (params.top_k));
249
+ break;
250
+ case COMMON_SAMPLER_TYPE_TOP_P:
251
+ llama_sampler_chain_add(result->chain, llama_sampler_init_top_p (params.top_p, params.min_keep));
252
+ break;
253
+ case COMMON_SAMPLER_TYPE_MIN_P:
254
+ llama_sampler_chain_add(result->chain, llama_sampler_init_min_p (params.min_p, params.min_keep));
255
+ break;
256
+ case COMMON_SAMPLER_TYPE_XTC:
257
+ llama_sampler_chain_add(result->chain, llama_sampler_init_xtc (params.xtc_probability, params.xtc_threshold, params.min_keep, params.seed));
258
+ break;
259
+ case COMMON_SAMPLER_TYPE_TYPICAL_P:
260
+ llama_sampler_chain_add(result->chain, llama_sampler_init_typical (params.typ_p, params.min_keep));
261
+ break;
262
+ case COMMON_SAMPLER_TYPE_TEMPERATURE:
263
+ llama_sampler_chain_add(result->chain, llama_sampler_init_temp_ext (params.temp, params.dynatemp_range, params.dynatemp_exponent));
264
+ break;
265
+ case COMMON_SAMPLER_TYPE_INFILL:
266
+ llama_sampler_chain_add(result->chain, llama_sampler_init_infill (vocab));
267
+ break;
268
+ case COMMON_SAMPLER_TYPE_PENALTIES:
269
+ llama_sampler_chain_add(result->chain, llama_sampler_init_penalties(params.penalty_last_n, params.penalty_repeat, params.penalty_freq, params.penalty_present));
270
+ break;
271
+ default:
272
+ LM_GGML_ASSERT(false && "unknown sampler type");
273
+ }
274
+ }
275
+ }
276
+ llama_sampler_chain_add(result->chain, llama_sampler_init_dist(params.seed));
277
+ } else if (params.mirostat == 1) {
278
+ llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
279
+ llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat(llama_vocab_n_tokens(vocab), params.seed, params.mirostat_tau, params.mirostat_eta, 100));
280
+ } else if (params.mirostat == 2) {
281
+ llama_sampler_chain_add(result->chain, llama_sampler_init_temp(params.temp));
282
+ llama_sampler_chain_add(result->chain, llama_sampler_init_mirostat_v2(params.seed, params.mirostat_tau, params.mirostat_eta));
283
+ } else {
284
+ LM_GGML_ASSERT(false && "unknown mirostat version");
285
+ }
286
+
287
+ return result;
288
+ }
289
+
290
+ void common_sampler_free(struct common_sampler * gsmpl) {
291
+ if (gsmpl) {
292
+ llama_sampler_free(gsmpl->grmr);
293
+
294
+ llama_sampler_free(gsmpl->chain);
295
+
296
+ delete gsmpl;
297
+ }
298
+ }
299
+
300
+ void common_sampler_accept(struct common_sampler * gsmpl, llama_token token, bool accept_grammar) {
301
+ if (accept_grammar) {
302
+ llama_sampler_accept(gsmpl->grmr, token);
303
+ }
304
+
305
+ llama_sampler_accept(gsmpl->chain, token);
306
+
307
+ gsmpl->prev.push_back(token);
308
+ }
309
+
310
+ void common_sampler_reset(struct common_sampler * gsmpl) {
311
+ llama_sampler_reset(gsmpl->grmr);
312
+
313
+ llama_sampler_reset(gsmpl->chain);
314
+ }
315
+
316
+ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) {
317
+ return new common_sampler {
318
+ /* .params = */ gsmpl->params,
319
+ /* .grmr = */ llama_sampler_clone(gsmpl->grmr),
320
+ /* .chain = */ llama_sampler_clone(gsmpl->chain),
321
+ /* .prev = */ gsmpl->prev,
322
+ /* .cur = */ gsmpl->cur,
323
+ /* .cur_p = */ gsmpl->cur_p,
324
+ };
325
+ }
326
+
327
+ void common_perf_print(const struct llama_context * ctx, const struct common_sampler * gsmpl) {
328
+ // TODO: measure grammar performance
329
+
330
+ if (gsmpl) {
331
+ llama_perf_sampler_print(gsmpl->chain);
332
+ }
333
+ if (ctx) {
334
+ llama_perf_context_print(ctx);
335
+ }
336
+ }
337
+
338
+ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
339
+ gsmpl->set_logits(ctx, idx);
340
+
341
+ auto & grmr = gsmpl->grmr;
342
+ auto & chain = gsmpl->chain;
343
+ auto & cur_p = gsmpl->cur_p; // initialized by set_logits
344
+
345
+ if (grammar_first) {
346
+ llama_sampler_apply(grmr, &cur_p);
347
+ }
348
+
349
+ llama_sampler_apply(chain, &cur_p);
350
+
351
+ LM_GGML_ASSERT(cur_p.selected != -1 && "no selected token during sampling - check your sampling configuration");
352
+
353
+ const llama_token id = cur_p.data[cur_p.selected].id;
354
+
355
+ if (grammar_first) {
356
+ return id;
357
+ }
358
+
359
+ // check if it the sampled token fits the grammar
360
+ {
361
+ llama_token_data single_token_data = { id, 1.0f, 0.0f };
362
+ llama_token_data_array single_token_data_array = { &single_token_data, 1, -1, false };
363
+
364
+ llama_sampler_apply(grmr, &single_token_data_array);
365
+
366
+ const bool is_valid = single_token_data_array.data[0].logit != -INFINITY;
367
+ if (is_valid) {
368
+ return id;
369
+ }
370
+ }
371
+
372
+ // resampling:
373
+ // if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
374
+ gsmpl->set_logits(ctx, idx);
375
+
376
+ llama_sampler_apply(grmr, &cur_p);
377
+ llama_sampler_apply(chain, &cur_p);
378
+
379
+ LM_GGML_ASSERT(cur_p.selected != -1 && "no selected token during re-sampling - check your sampling configuration");
380
+
381
+ return cur_p.data[cur_p.selected].id;
382
+ }
383
+
384
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
385
+ LM_GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
386
+
387
+ std::vector<llama_token> result;
388
+ result.reserve(idxs.size());
389
+
390
+ size_t i = 0;
391
+ for (; i < draft.size(); i++) {
392
+ const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
393
+
394
+ common_sampler_accept(gsmpl, id, true);
395
+
396
+ result.push_back(id);
397
+
398
+ if (draft[i] != id) {
399
+ break;
400
+ }
401
+ }
402
+
403
+ if (i == draft.size()) {
404
+ const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
405
+
406
+ common_sampler_accept(gsmpl, id, true);
407
+
408
+ result.push_back(id);
409
+ }
410
+
411
+ return result;
412
+ }
413
+
414
+ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const llama_tokens & draft, bool grammar_first) {
415
+ std::vector<int> idxs(draft.size() + 1);
416
+ for (size_t i = 0; i < idxs.size(); ++i) {
417
+ idxs[i] = i;
418
+ }
419
+
420
+ return common_sampler_sample_and_accept_n(gsmpl, ctx, idxs, draft, grammar_first);
421
+ }
422
+
423
+ uint32_t common_sampler_get_seed(const struct common_sampler * gsmpl) {
424
+ return llama_sampler_get_seed(gsmpl->chain);
425
+ }
426
+
427
+ // helpers
428
+
429
+ llama_token_data_array * common_sampler_get_candidates(struct common_sampler * gsmpl) {
430
+ return &gsmpl->cur_p;
431
+ }
432
+
433
+ llama_token common_sampler_last(const struct common_sampler * gsmpl) {
434
+ return gsmpl->prev.rat(0);
435
+ }
436
+
437
+ std::string common_sampler_print(const struct common_sampler * gsmpl) {
438
+ std::string result = "logits ";
439
+
440
+ for (int i = 0; i < llama_sampler_chain_n(gsmpl->chain); i++) {
441
+ const auto * smpl = llama_sampler_chain_get(gsmpl->chain, i);
442
+ result += std::string("-> ") + llama_sampler_name(smpl) + " ";
443
+ }
444
+
445
+ return result;
446
+ }
447
+
448
+ std::string common_sampler_prev_str(common_sampler * gsmpl, llama_context * ctx_main, int n) {
449
+ n = std::min(n, (int) gsmpl->prev.size());
450
+
451
+ if (n <= 0) {
452
+ return "";
453
+ }
454
+
455
+ std::string result;
456
+ result.reserve(8*n); // 8 is the average length of a token [citation needed], TODO: compute this from the vocab
457
+
458
+ for (int i = n - 1; i >= 0; i--) {
459
+ const llama_token id = gsmpl->prev.rat(i);
460
+
461
+ LM_GGML_ASSERT(id != LLAMA_TOKEN_NULL && "null token in the sampling history - should not happen");
462
+
463
+ result += common_token_to_piece(ctx_main, id);
464
+ }
465
+
466
+ return result;
467
+ }
468
+
469
+ char common_sampler_type_to_chr(enum common_sampler_type cnstr) {
470
+ switch (cnstr) {
471
+ case COMMON_SAMPLER_TYPE_DRY: return 'd';
472
+ case COMMON_SAMPLER_TYPE_TOP_K: return 'k';
473
+ case COMMON_SAMPLER_TYPE_TYPICAL_P: return 'y';
474
+ case COMMON_SAMPLER_TYPE_TOP_P: return 'p';
475
+ case COMMON_SAMPLER_TYPE_MIN_P: return 'm';
476
+ case COMMON_SAMPLER_TYPE_TEMPERATURE: return 't';
477
+ case COMMON_SAMPLER_TYPE_XTC: return 'x';
478
+ case COMMON_SAMPLER_TYPE_INFILL: return 'i';
479
+ case COMMON_SAMPLER_TYPE_PENALTIES: return 'e';
480
+ default : return '?';
481
+ }
482
+ }
483
+
484
+ std::string common_sampler_type_to_str(enum common_sampler_type cnstr) {
485
+ switch (cnstr) {
486
+ case COMMON_SAMPLER_TYPE_DRY: return "dry";
487
+ case COMMON_SAMPLER_TYPE_TOP_K: return "top_k";
488
+ case COMMON_SAMPLER_TYPE_TYPICAL_P: return "typ_p";
489
+ case COMMON_SAMPLER_TYPE_TOP_P: return "top_p";
490
+ case COMMON_SAMPLER_TYPE_MIN_P: return "min_p";
491
+ case COMMON_SAMPLER_TYPE_TEMPERATURE: return "temperature";
492
+ case COMMON_SAMPLER_TYPE_XTC: return "xtc";
493
+ case COMMON_SAMPLER_TYPE_INFILL: return "infill";
494
+ case COMMON_SAMPLER_TYPE_PENALTIES: return "penalties";
495
+ default : return "";
496
+ }
497
+ }
498
+
499
+ std::vector<common_sampler_type> common_sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
500
+ std::unordered_map<std::string, common_sampler_type> sampler_canonical_name_map {
501
+ { "dry", COMMON_SAMPLER_TYPE_DRY },
502
+ { "top_k", COMMON_SAMPLER_TYPE_TOP_K },
503
+ { "top_p", COMMON_SAMPLER_TYPE_TOP_P },
504
+ { "typ_p", COMMON_SAMPLER_TYPE_TYPICAL_P },
505
+ { "min_p", COMMON_SAMPLER_TYPE_MIN_P },
506
+ { "temperature", COMMON_SAMPLER_TYPE_TEMPERATURE },
507
+ { "xtc", COMMON_SAMPLER_TYPE_XTC },
508
+ { "infill", COMMON_SAMPLER_TYPE_INFILL },
509
+ { "penalties", COMMON_SAMPLER_TYPE_PENALTIES },
510
+ };
511
+
512
+ // since samplers names are written multiple ways
513
+ // make it ready for both system names and input names
514
+ std::unordered_map<std::string, common_sampler_type> sampler_alt_name_map {
515
+ { "top-k", COMMON_SAMPLER_TYPE_TOP_K },
516
+ { "top-p", COMMON_SAMPLER_TYPE_TOP_P },
517
+ { "nucleus", COMMON_SAMPLER_TYPE_TOP_P },
518
+ { "typical-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
519
+ { "typical", COMMON_SAMPLER_TYPE_TYPICAL_P },
520
+ { "typ-p", COMMON_SAMPLER_TYPE_TYPICAL_P },
521
+ { "typ", COMMON_SAMPLER_TYPE_TYPICAL_P },
522
+ { "min-p", COMMON_SAMPLER_TYPE_MIN_P },
523
+ { "temp", COMMON_SAMPLER_TYPE_TEMPERATURE },
524
+ };
525
+
526
+ std::vector<common_sampler_type> samplers;
527
+ samplers.reserve(names.size());
528
+
529
+ for (const auto & name : names) {
530
+ auto sampler = sampler_canonical_name_map.find(name);
531
+ if (sampler != sampler_canonical_name_map.end()) {
532
+ samplers.push_back(sampler->second);
533
+ } else {
534
+ if (allow_alt_names) {
535
+ sampler = sampler_alt_name_map.find(name);
536
+ if (sampler != sampler_alt_name_map.end()) {
537
+ samplers.push_back(sampler->second);
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ return samplers;
544
+ }
545
+
546
+ std::vector<common_sampler_type> common_sampler_types_from_chars(const std::string & chars) {
547
+ std::unordered_map<char, common_sampler_type> sampler_name_map = {
548
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_DRY), COMMON_SAMPLER_TYPE_DRY },
549
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_K), COMMON_SAMPLER_TYPE_TOP_K },
550
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TYPICAL_P), COMMON_SAMPLER_TYPE_TYPICAL_P },
551
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TOP_P), COMMON_SAMPLER_TYPE_TOP_P },
552
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_MIN_P), COMMON_SAMPLER_TYPE_MIN_P },
553
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_TEMPERATURE), COMMON_SAMPLER_TYPE_TEMPERATURE },
554
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_XTC), COMMON_SAMPLER_TYPE_XTC },
555
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_INFILL), COMMON_SAMPLER_TYPE_INFILL },
556
+ { common_sampler_type_to_chr(COMMON_SAMPLER_TYPE_PENALTIES), COMMON_SAMPLER_TYPE_PENALTIES },
557
+ };
558
+
559
+ std::vector<common_sampler_type> samplers;
560
+ samplers.reserve(chars.size());
561
+
562
+ for (const auto & c : chars) {
563
+ const auto sampler = sampler_name_map.find(c);
564
+ if (sampler != sampler_name_map.end()) {
565
+ samplers.push_back(sampler->second);
566
+ }
567
+ }
568
+
569
+ return samplers;
570
+ }