common.cpp 27 KB

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