interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / common.cpp

677 lines · 23353 bytes Raw Blame History
1#define _USE_MATH_DEFINES // for M_PI
2
3#include "common.h"
4
5#include <cmath>
6#include <codecvt>
7#include <cstring>
8#include <fstream>
9#include <locale>
10#include <regex>
11#include <sstream>
12
13// Function to check if the next argument exists
14static std::string get_next_arg(int& i, int argc, char** argv, const std::string& flag, gpt_params& params) {
15 if (i + 1 < argc && argv[i + 1][0] != '-') {
16 return argv[++i];
17 } else {
18 fprintf(stderr, "error: %s requires one argument.\n", flag.c_str());
19 gpt_print_usage(argc, argv, params);
20 exit(0);
21 }
22}
23
24bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
25 for (int i = 1; i < argc; i++) {
26 std::string arg = argv[i];
27
28 if (arg == "-s" || arg == "--seed") {
29 params.seed = std::stoi(get_next_arg(i, argc, argv, arg, params));
30 } else if (arg == "-t" || arg == "--threads") {
31 params.n_threads = std::stoi(get_next_arg(i, argc, argv, arg, params));
32 } else if (arg == "-p" || arg == "--prompt") {
33 params.prompt = get_next_arg(i, argc, argv, arg, params);
34 } else if (arg == "-n" || arg == "--n_predict") {
35 params.n_predict = std::stoi(get_next_arg(i, argc, argv, arg, params));
36 } else if (arg == "-np" || arg == "--n_parallel") {
37 params.n_parallel = std::stoi(get_next_arg(i, argc, argv, arg, params));
38 } else if (arg == "--top_k") {
39 params.top_k = std::stoi(get_next_arg(i, argc, argv, arg, params));
40 } else if (arg == "--top_p") {
41 params.top_p = std::stof(get_next_arg(i, argc, argv, arg, params));
42 } else if (arg == "--temp") {
43 params.temp = std::stof(get_next_arg(i, argc, argv, arg, params));
44 } else if (arg == "--repeat-last-n") {
45 params.repeat_last_n = std::stoi(get_next_arg(i, argc, argv, arg, params));
46 } else if (arg == "--repeat-penalty") {
47 params.repeat_penalty = std::stof(get_next_arg(i, argc, argv, arg, params));
48 } else if (arg == "-b" || arg == "--batch_size") {
49 params.n_batch= std::stoi(get_next_arg(i, argc, argv, arg, params));
50 } else if (arg == "-c" || arg == "--context") {
51 params.n_ctx= std::stoi(get_next_arg(i, argc, argv, arg, params));
52 } else if (arg == "-ngl" || arg == "--gpu-layers" || arg == "--n-gpu-layers") {
53 params.n_gpu_layers = std::stoi(get_next_arg(i, argc, argv, arg, params));
54 } else if (arg == "--ignore-eos") {
55 params.ignore_eos = true;
56 } else if (arg == "-m" || arg == "--model") {
57 params.model = get_next_arg(i, argc, argv, arg, params);
58 } else if (arg == "-i" || arg == "--interactive") {
59 params.interactive = true;
60 } else if (arg == "-ip" || arg == "--interactive-port") {
61 params.interactive = true;
62 params.interactive_port = std::stoi(get_next_arg(i, argc, argv, arg, params));
63 } else if (arg == "-h" || arg == "--help") {
64 gpt_print_usage(argc, argv, params);
65 exit(0);
66 } else if (arg == "-f" || arg == "--file") {
67 get_next_arg(i, argc, argv, arg, params);
68 std::ifstream file(argv[i]);
69 if (!file) {
70 fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
71 break;
72 }
73 std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
74 if (params.prompt.back() == '\n') {
75 params.prompt.pop_back();
76 }
77 } else if (arg == "-tt" || arg == "--token_test") {
78 params.token_test = get_next_arg(i, argc, argv, arg, params);
79 }
80 else {
81 fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
82 gpt_print_usage(argc, argv, params);
83 exit(0);
84 }
85 }
86
87 return true;
88}
89
90void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
91 fprintf(stderr, "usage: %s [options]\n", argv[0]);
92 fprintf(stderr, "\n");
93 fprintf(stderr, "options:\n");
94 fprintf(stderr, " -h, --help show this help message and exit\n");
95 fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
96 fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
97 fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
98 fprintf(stderr, " prompt to start generation with (default: random)\n");
99 fprintf(stderr, " -f FNAME, --file FNAME\n");
100 fprintf(stderr, " load prompt from a file\n");
101 fprintf(stderr, " -tt TOKEN_TEST, --token_test TOKEN_TEST\n");
102 fprintf(stderr, " test tokenization\n");
103 fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
104 fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
105 fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
106 fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
107 fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled)\n", params.repeat_last_n);
108 fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.2f, 1.0 = disabled)\n", (double)params.repeat_penalty);
109 fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
110 fprintf(stderr, " -c N, --context N context / KV cache size (default: %d)\n", params.n_ctx);
111 fprintf(stderr, " --ignore-eos ignore EOS token during generation\n");
112 fprintf(stderr, " -ngl N, --gpu-layers N number of layers to offload to GPU on supported models (default: %d)\n", params.n_gpu_layers);
113 fprintf(stderr, " -m FNAME, --model FNAME\n");
114 fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
115 fprintf(stderr, "\n");
116}
117
118std::string gpt_random_prompt(std::mt19937 & rng) {
119 const int r = rng() % 10;
120 switch (r) {
121 case 0: return "So";
122 case 1: return "Once upon a time";
123 case 2: return "When";
124 case 3: return "The";
125 case 4: return "After";
126 case 5: return "If";
127 case 6: return "import";
128 case 7: return "He";
129 case 8: return "She";
130 case 9: return "They";
131 }
132
133 return "The";
134}
135
136std::string trim(const std::string & s) {
137 std::regex e("^\\s+|\\s+$");
138 return std::regex_replace(s, e, "");
139}
140
141std::string replace(const std::string & s, const std::string & from, const std::string & to) {
142 std::string result = s;
143 size_t pos = 0;
144 while ((pos = result.find(from, pos)) != std::string::npos) {
145 result.replace(pos, from.length(), to);
146 pos += to.length();
147 }
148 return result;
149}
150
151void gpt_vocab::add_special_token(const std::string & token) {
152 special_tokens.push_back(token);
153}
154
155std::map<std::string, int32_t> json_parse(const std::string & fname) {
156 std::map<std::string, int32_t> result;
157
158 // read file into string
159 std::string json;
160 {
161 std::ifstream ifs(fname);
162 if (!ifs) {
163 fprintf(stderr, "Failed to open %s\n", fname.c_str());
164 exit(1);
165 }
166
167 json = std::string((std::istreambuf_iterator<char>(ifs)),
168 (std::istreambuf_iterator<char>()));
169 }
170
171 if (json[0] != '{') {
172 return result;
173 }
174
175 // parse json
176 {
177 bool has_key = false;
178 bool in_token = false;
179
180 std::string str_key = "";
181 std::string str_val = "";
182
183 int n = json.size();
184 for (int i = 1; i < n; ++i) {
185 if (!in_token) {
186 if (json[i] == ' ') continue;
187 if (json[i] == '"') {
188 in_token = true;
189 continue;
190 }
191 } else {
192 if (json[i] == '\\' && i+1 < n) {
193 if (has_key == false) {
194 str_key += json[i];
195 } else {
196 str_val += json[i];
197 }
198 ++i;
199 } else if (json[i] == '"') {
200 if (has_key == false) {
201 has_key = true;
202 ++i;
203 while (json[i] == ' ') ++i;
204 ++i; // :
205 while (json[i] == ' ') ++i;
206 if (json[i] != '\"') {
207 while (json[i] != ',' && json[i] != '}') {
208 str_val += json[i++];
209 }
210 has_key = false;
211 } else {
212 in_token = true;
213 continue;
214 }
215 } else {
216 has_key = false;
217 }
218
219 str_key = ::replace(str_key, "\\u0120", " " ); // \u0120 -> space
220 str_key = ::replace(str_key, "\\u010a", "\n"); // \u010a -> new line
221 str_key = ::replace(str_key, "\\\"", "\""); // \\\" -> "
222
223 try {
224 result[str_key] = std::stoi(str_val);
225 } catch (...) {
226 //fprintf(stderr, "%s: ignoring key '%s' with value '%s'\n", fname.c_str(), str_key.c_str(), str_val.c_str());
227
228 }
229 str_key = "";
230 str_val = "";
231 in_token = false;
232 continue;
233 }
234 if (has_key == false) {
235 str_key += json[i];
236 } else {
237 str_val += json[i];
238 }
239 }
240 }
241 }
242
243 return result;
244}
245
246void gpt_split_words(std::string str, std::vector<std::string>& words) {
247 const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
248 const std::regex re(pattern);
249 std::smatch m;
250
251 while (std::regex_search(str, m, re)) {
252 for (auto x : m) {
253 words.push_back(x);
254 }
255 str = m.suffix();
256 }
257}
258
259std::vector<gpt_vocab::id> gpt_tokenize(const gpt_vocab & vocab, const std::string & text) {
260 std::vector<std::string> words;
261
262 // first split the text into words
263 {
264 std::string str = text;
265
266 // Generate the subpattern from the special_tokens vector if it's not empty
267 if (!vocab.special_tokens.empty()) {
268 const std::regex escape(R"([\[\\\^\$\.\|\?\*\+\(\)\{\}])");
269 std::string special_tokens_subpattern;
270 for (const auto & token : vocab.special_tokens) {
271 if (!special_tokens_subpattern.empty()) {
272 special_tokens_subpattern += "|";
273 }
274 special_tokens_subpattern += std::regex_replace(token, escape, R"(\$&)");
275 }
276
277 std::regex re(special_tokens_subpattern);
278 std::smatch m;
279 // Split the text by special tokens.
280 while (std::regex_search(str, m, re)) {
281 // Split the substrings in-between special tokens into words.
282 gpt_split_words(m.prefix(), words);
283 // Add matched special tokens as words.
284 for (auto x : m) {
285 words.push_back(x);
286 }
287 str = m.suffix();
288 }
289 // Remaining text without special tokens will be handled below.
290 }
291
292 gpt_split_words(str, words);
293 }
294
295 // find the longest token that forms each word in words:
296 std::vector<gpt_vocab::id> tokens;
297 for (const auto & word : words) {
298 for (int i = 0; i < (int) word.size(); ){
299 for (int j = word.size() - 1; j >= i; j--){
300 auto cand = word.substr(i, j-i+1);
301 auto it = vocab.token_to_id.find(cand);
302 if (it != vocab.token_to_id.end()){ // word.substr(i, j-i+1) in vocab
303 tokens.push_back(it->second);
304 i = j + 1;
305 break;
306 }
307 else if (j == i){ // word.substr(i, 1) has no matching
308 fprintf(stderr, "%s: unknown token '%s'\n", __func__, word.substr(i, 1).data());
309 i++;
310 }
311 }
312 }
313 }
314
315 return tokens;
316}
317
318static std::vector<gpt_vocab::id> parse_tokens_from_string(const std::string& input, char delimiter) {
319 std::vector<gpt_vocab::id> output;
320 std::stringstream ss(input);
321 std::string token;
322
323 while (std::getline(ss, token, delimiter)) {
324 output.push_back(std::stoi(token));
325 }
326
327 return output;
328}
329
330static std::map<std::string, std::vector<gpt_vocab::id>> extract_tests_from_file(const std::string & fpath_test){
331 if (fpath_test.empty()){
332 fprintf(stderr, "%s : No test file found.\n", __func__);
333 return std::map<std::string, std::vector<gpt_vocab::id>>();
334 }
335
336 std::map<std::string, std::vector<gpt_vocab::id>> tests;
337
338 auto fin = std::ifstream(fpath_test, std::ios_base::in);
339 const char * delimeter = " => ";
340 const char del_tok = ',';
341 std::string line;
342 while (std::getline(fin, line)) {
343 size_t delimiterPos = line.find(delimeter);
344 if (delimiterPos != std::string::npos) {
345 std::string text = line.substr(0, delimiterPos);
346 std::string s_tokens = line.substr(delimiterPos + std::strlen(delimeter));
347 tests[text] = parse_tokens_from_string(s_tokens, del_tok);
348 }
349 }
350 return tests;
351}
352
353void test_gpt_tokenizer(gpt_vocab & vocab, const std::string & fpath_test){
354 std::map<std::string, std::vector<gpt_vocab::id>> tests = extract_tests_from_file(fpath_test);
355
356 size_t n_fails = 0;
357
358 for (const auto & test : tests) {
359 std::vector<gpt_vocab::id> tokens = gpt_tokenize(vocab, test.first);
360
361 if (tokens != test.second){
362 n_fails++;
363
364 // print out failure cases
365 fprintf(stderr, "%s : failed test: '%s'\n", __func__, test.first.c_str());
366 fprintf(stderr, "%s : tokens in hf: ", __func__);
367 for (const auto & t : test.second) {
368 fprintf(stderr, "%s(%d), ", vocab.id_to_token[t].c_str(), t);
369 }
370 fprintf(stderr, "\n");
371 fprintf(stderr, "%s : tokens in ggml: ", __func__);
372 for (const auto & t : tokens) {
373 fprintf(stderr, "%s(%d), ", vocab.id_to_token[t].c_str(), t);
374 }
375 fprintf(stderr, "\n");
376 }
377 }
378
379 fprintf(stderr, "%s : %zu tests failed out of %zu tests.\n", __func__, n_fails, tests.size());
380}
381
382bool gpt_vocab_init(const std::string & fname, gpt_vocab & vocab) {
383 printf("%s: loading vocab from '%s'\n", __func__, fname.c_str());
384
385 vocab.token_to_id = ::json_parse(fname);
386
387 for (const auto & kv : vocab.token_to_id) {
388 vocab.id_to_token[kv.second] = kv.first;
389 }
390
391 printf("%s: vocab size = %d\n", __func__, (int) vocab.token_to_id.size());
392
393 // print the vocabulary
394 //for (auto kv : vocab.token_to_id) {
395 // printf("'%s' -> %d\n", kv.first.data(), kv.second);
396 //}
397
398 return true;
399}
400
401gpt_vocab::id gpt_sample_top_k_top_p(
402 const gpt_vocab & vocab,
403 const float * logits,
404 int top_k,
405 double top_p,
406 double temp,
407 std::mt19937 & rng) {
408 int n_logits = vocab.id_to_token.size();
409 top_k = std::min(top_k, n_logits);
410
411 std::vector<std::pair<double, gpt_vocab::id>> logits_id;
412 logits_id.reserve(n_logits);
413
414 {
415 const double scale = 1.0/temp;
416 for (int i = 0; i < n_logits; ++i) {
417 logits_id.push_back(std::make_pair(logits[i]*scale, i));
418 }
419 }
420
421 // find the top K tokens
422 std::partial_sort(
423 logits_id.begin(),
424 logits_id.begin() + top_k, logits_id.end(),
425 [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
426 return a.first > b.first;
427 });
428
429 logits_id.resize(top_k);
430
431 double maxl = -INFINITY;
432 for (const auto & kv : logits_id) {
433 maxl = std::max(maxl, kv.first);
434 }
435
436 // compute probs for the top K tokens
437 std::vector<double> probs;
438 probs.reserve(logits_id.size());
439
440 double sum = 0.0;
441 for (const auto & kv : logits_id) {
442 double p = exp(kv.first - maxl);
443 probs.push_back(p);
444 sum += p;
445 }
446
447 // normalize the probs
448 for (auto & p : probs) {
449 p /= sum;
450 }
451
452 if (top_p < 1.0f) {
453 double cumsum = 0.0f;
454 for (int i = 0; i < top_k; i++) {
455 cumsum += probs[i];
456 if (cumsum >= top_p) {
457 top_k = i + 1;
458 probs.resize(top_k);
459 logits_id.resize(top_k);
460 break;
461 }
462 }
463
464 cumsum = 1.0/cumsum;
465 for (int i = 0; i < (int) probs.size(); i++) {
466 probs[i] *= cumsum;
467 }
468 }
469
470 //printf("\n");
471 //for (int i = 0; i < (int) probs.size(); i++) {
472 // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
473 //}
474 //exit(0);
475
476 std::discrete_distribution<> dist(probs.begin(), probs.end());
477 int idx = dist(rng);
478
479 return logits_id[idx].second;
480}
481
482gpt_vocab::id gpt_sample_top_k_top_p_repeat(
483 const gpt_vocab & vocab,
484 const float * logits,
485 const int32_t * last_n_tokens_data,
486 size_t last_n_tokens_data_size,
487 int top_k,
488 double top_p,
489 double temp,
490 int repeat_last_n,
491 float repeat_penalty,
492 std::mt19937 & rng) {
493
494 int n_logits = vocab.id_to_token.size();
495 top_k = std::min(top_k, n_logits);
496
497 const auto * plogits = logits;
498
499 const auto last_n_tokens = std::vector<int32_t>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_data_size);
500
501 if (temp <= 0) {
502 // select the token with the highest logit directly
503 float max_logit = plogits[0];
504 gpt_vocab::id max_id = 0;
505
506 for (int i = 1; i < n_logits; ++i) {
507 if (plogits[i] > max_logit) {
508 max_logit = plogits[i];
509 max_id = i;
510 }
511 }
512 return max_id;
513 }
514
515
516 std::vector<std::pair<double, gpt_vocab::id>> logits_id;
517 logits_id.reserve(n_logits);
518
519 {
520 const float scale = 1.0f/temp;
521 for (int i = 0; i < n_logits; ++i) {
522 // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
523 // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
524 if (repeat_last_n > 0 && std::find(last_n_tokens.end()-repeat_last_n, last_n_tokens.end(), i) != last_n_tokens.end()) {
525 // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
526 if (plogits[i] < 0.0f) {
527 logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
528 } else {
529 logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
530 }
531 } else {
532 logits_id.push_back(std::make_pair(plogits[i]*scale, i));
533 }
534 }
535 }
536
537 // find the top K tokens
538 std::partial_sort(
539 logits_id.begin(),
540 logits_id.begin() + top_k, logits_id.end(),
541 [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
542 return a.first > b.first;
543 });
544
545 logits_id.resize(top_k);
546
547 double maxl = -INFINITY;
548 for (const auto & kv : logits_id) {
549 maxl = std::max(maxl, kv.first);
550 }
551
552 // compute probs for the top K tokens
553 std::vector<double> probs;
554 probs.reserve(logits_id.size());
555
556 double sum = 0.0;
557 for (const auto & kv : logits_id) {
558 double p = exp(kv.first - maxl);
559 probs.push_back(p);
560 sum += p;
561 }
562
563 // normalize the probs
564 for (auto & p : probs) {
565 p /= sum;
566 }
567
568 if (top_p < 1.0f) {
569 double cumsum = 0.0f;
570 for (int i = 0; i < top_k; i++) {
571 cumsum += probs[i];
572 if (cumsum >= top_p) {
573 top_k = i + 1;
574 probs.resize(top_k);
575 logits_id.resize(top_k);
576 break;
577 }
578 }
579
580 cumsum = 1.0/cumsum;
581 for (int i = 0; i < (int) probs.size(); i++) {
582 probs[i] *= cumsum;
583 }
584 }
585
586// printf("\n");
587// for (int i = 0; i < (int) probs.size(); i++) {
588// for (int i = 0; i < 10; i++) {
589// printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
590// }
591
592 std::discrete_distribution<> dist(probs.begin(), probs.end());
593 int idx = dist(rng);
594
595 return logits_id[idx].second;
596
597}
598
599void high_pass_filter(std::vector<float> & data, float cutoff, float sample_rate) {
600 const float rc = 1.0f / (2.0f * M_PI * cutoff);
601 const float dt = 1.0f / sample_rate;
602 const float alpha = dt / (rc + dt);
603
604 float y = data[0];
605
606 for (size_t i = 1; i < data.size(); i++) {
607 y = alpha * (y + data[i] - data[i - 1]);
608 data[i] = y;
609 }
610}
611
612bool vad_simple(std::vector<float> & pcmf32, int sample_rate, int last_ms, float vad_thold, float freq_thold, bool verbose) {
613 const int n_samples = pcmf32.size();
614 const int n_samples_last = (sample_rate * last_ms) / 1000;
615
616 if (n_samples_last >= n_samples) {
617 // not enough samples - assume no speech
618 return false;
619 }
620
621 if (freq_thold > 0.0f) {
622 high_pass_filter(pcmf32, freq_thold, sample_rate);
623 }
624
625 float energy_all = 0.0f;
626 float energy_last = 0.0f;
627
628 for (int i = 0; i < n_samples; i++) {
629 energy_all += fabsf(pcmf32[i]);
630
631 if (i >= n_samples - n_samples_last) {
632 energy_last += fabsf(pcmf32[i]);
633 }
634 }
635
636 energy_all /= n_samples;
637 energy_last /= n_samples_last;
638
639 if (verbose) {
640 fprintf(stderr, "%s: energy_all: %f, energy_last: %f, vad_thold: %f, freq_thold: %f\n", __func__, energy_all, energy_last, vad_thold, freq_thold);
641 }
642
643 if (energy_last > vad_thold*energy_all) {
644 return false;
645 }
646
647 return true;
648}
649
650float similarity(const std::string & s0, const std::string & s1) {
651 const size_t len0 = s0.size() + 1;
652 const size_t len1 = s1.size() + 1;
653
654 std::vector<int> col(len1, 0);
655 std::vector<int> prevCol(len1, 0);
656
657 for (size_t i = 0; i < len1; i++) {
658 prevCol[i] = i;
659 }
660
661 for (size_t i = 0; i < len0; i++) {
662 col[0] = i;
663 for (size_t j = 1; j < len1; j++) {
664 col[j] = std::min(std::min(1 + col[j - 1], 1 + prevCol[j]), prevCol[j - 1] + (i > 0 && s0[i - 1] == s1[j - 1] ? 0 : 1));
665 }
666 col.swap(prevCol);
667 }
668
669 const float dist = prevCol[len1 - 1];
670
671 return 1.0f - (dist / std::max(s0.size(), s1.size()));
672}
673
674bool is_file_exist(const char * filename) {
675 std::ifstream infile(filename);
676 return infile.good();
677}