unity.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #include "ggml/ggml.h"
  2. #include "ggml/ggml-alloc.h"
  3. #include "math.h"
  4. #include "model_loader.h"
  5. #include "fairseq2.h"
  6. #include <thread>
  7. #include <cassert>
  8. #include <cmath>
  9. #include <cstdio>
  10. #include <cstring>
  11. #include <fstream>
  12. #include <map>
  13. #include <string>
  14. #include <vector>
  15. #include <iostream>
  16. #include <sndfile.h>
  17. #include <cstdlib>
  18. #include "ggml-alloc.h"
  19. struct unity_params {
  20. int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
  21. std::string model = "seamlessM4T_medium.ggml"; // model path
  22. std::string tgt_lang = "eng";
  23. std::vector<std::string> files = {};
  24. bool text = false;
  25. SequenceGeneratorOptions opts = {
  26. /*beam_size*/ 5,
  27. /*min_seq_len*/ 1,
  28. /*soft_max_seq_len_a*/ 1,
  29. /*soft_max_seq_len_b*/ 200,
  30. /*hard_max_seq_len*/ 1000,
  31. /*len_penalty*/ 1.0,
  32. /*unk_penalty*/ 0.0,
  33. /*normalize_scores*/ true,
  34. };
  35. };
  36. void unity_print_usage(int /*argc*/, char ** argv, const unity_params & params) {
  37. fprintf(stderr, "usage: %s [options] file1 file2 ...\n", argv[0]);
  38. fprintf(stderr, "\n");
  39. fprintf(stderr, "options:\n");
  40. fprintf(stderr, " -h, --help show this help message and exit\n");
  41. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  42. fprintf(stderr, " -m FNAME, --model FNAME\n");
  43. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  44. fprintf(stderr, " --text text output\n");
  45. fprintf(stderr, " --beam-size beam size (default: %d)\n", params.opts.beam_size);
  46. fprintf(stderr, "\n");
  47. }
  48. std::string get_next_arg(int& i, int argc, char** argv, const std::string& flag, unity_params& params) {
  49. if (i + 1 < argc && argv[i + 1][0] != '-') {
  50. return argv[++i];
  51. } else {
  52. fprintf(stderr, "error: %s requires one argument.\n", flag.c_str());
  53. unity_print_usage(argc, argv, params);
  54. exit(0);
  55. }
  56. }
  57. bool unity_params_parse(int argc, char ** argv, unity_params & params) {
  58. for (int i = 1; i < argc; i++) {
  59. std::string arg = argv[i];
  60. if (arg == "-h" || arg == "--help") {
  61. unity_print_usage(argc, argv, params);
  62. } else if (arg == "-t" || arg == "--threads") {
  63. params.n_threads = std::stoi(get_next_arg(i, argc, argv, arg, params));
  64. } else if (arg == "-m" || arg == "--model") {
  65. params.model = get_next_arg(i, argc, argv, arg, params);
  66. } else if (arg == "-l" || arg == "--tgt-lang") {
  67. params.tgt_lang = get_next_arg(i, argc, argv, arg, params);
  68. } else if (arg == "--text") {
  69. params.text = true;
  70. } else if (arg == "-b" || arg == "--beam-size") {
  71. params.opts.beam_size = std::stoi(get_next_arg(i, argc, argv, arg, params));
  72. } else {
  73. params.files.push_back(std::string(arg));
  74. }
  75. }
  76. return true;
  77. }
  78. struct ggml_cgraph * unity_speech_encoder(
  79. fairseq2_model& model,
  80. struct ggml_tensor * speech_input) {
  81. ggml_context* ctx0 = model.ctx;
  82. ggml_cgraph* gf = ggml_new_graph(ctx0);
  83. ggml_tensor* seqs = StandardConformerEncoder_forward(model, "speech_encoder", speech_input, nullptr);
  84. seqs = ggml_dup(model.ctx, seqs);
  85. ggml_build_forward_expand(gf, seqs);
  86. return gf;
  87. }
  88. Hypothesis* unity_decode(
  89. fairseq2_model& model,
  90. const SequenceGeneratorOptions& opts,
  91. int tgt_lang_idx,
  92. ggml_tensor* encoder_output,
  93. int n_threads
  94. ) {
  95. SequenceGeneratorJob job = {
  96. opts,
  97. /*prefix_seq*/ nullptr,
  98. /*pad_idx*/model.vocab.token_to_id["<pad>"],
  99. /*unk_idx*/model.vocab.token_to_id["<unk>"],
  100. /*bos_idx*/model.vocab.token_to_id["<s>"],
  101. /*eos_idx*/model.vocab.token_to_id["</s>"],
  102. /*num_threads*/n_threads,
  103. };
  104. FORCE_ALLOC(prefix_seq, model.ctx, ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, 2));
  105. ((int *)prefix_seq->data)[0] = job.eos_idx;
  106. ((int *)prefix_seq->data)[1] = tgt_lang_idx;
  107. job.prefix_seq = prefix_seq;
  108. return generate_sequence(model, job, encoder_output, nullptr, model.ctx);
  109. }
  110. int main(int argc, char ** argv) {
  111. unity_params params;
  112. if (unity_params_parse(argc, argv, params) == false) {
  113. return 1;
  114. }
  115. fairseq2_model model;
  116. // load the model
  117. if (load_fairseq2_ggml_file(model, params.model.c_str())) {
  118. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  119. return 1;
  120. }
  121. // The ctx_size_mb mostly depends of input length and model dim.
  122. int ctx_size_mb = 128;
  123. auto encoder_buf = std::vector<uint8_t>(128 * 1024 * 1024);
  124. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  125. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  126. char result_str[4096];
  127. std::string input;
  128. bool interactive = params.files.size() == 0;
  129. auto next_file = params.files.begin();
  130. while (true) {
  131. if (interactive) {
  132. std::cout << "\nEnter audio_path and tgt_lang, separated by space (or 'exit' to quit):\n";
  133. std::getline(std::cin, input);
  134. if (input == "exit") {
  135. break;
  136. }
  137. } else {
  138. if (next_file == params.files.end()) break;
  139. input = *(next_file++);
  140. }
  141. std::istringstream iss(input);
  142. std::string audio_path;
  143. std::string tgt_lang = params.tgt_lang;
  144. iss >> audio_path >> tgt_lang;
  145. if (audio_path == "-") {
  146. audio_path = "/proc/self/fd/0";
  147. }
  148. std::cerr << "Translating (Transcribing) " << audio_path << " to " << tgt_lang << "\n";
  149. SF_INFO info;
  150. SNDFILE* sndfile = sf_open(audio_path.c_str(), SFM_READ, &info);
  151. if (!sndfile) {
  152. std::cerr << "Could not open file\n";
  153. if (interactive) continue;
  154. else return 1;
  155. }
  156. auto tgt_lang_ptr = model.vocab.token_to_id.find("__" + tgt_lang + "__");
  157. if (tgt_lang_ptr == model.vocab.token_to_id.end()) {
  158. std::cerr << "Unknown language " << tgt_lang << "\n";
  159. if (interactive) continue;
  160. else return 2;
  161. }
  162. int tgt_lang_idx = tgt_lang_ptr->second;
  163. // Reset the ggml_context
  164. model.ctx = ctx_from_buffer(encoder_buf);
  165. ggml_set_no_alloc(model.ctx, false);
  166. ggml_tensor* seqs = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, info.frames, info.channels);
  167. ggml_set_no_alloc(model.ctx, true);
  168. // Load audio input
  169. sf_readf_float(sndfile, (float*)seqs->data, info.frames);
  170. // Audio encoder
  171. ggml_cgraph* gf = unity_speech_encoder(model, seqs);
  172. ggml_allocr_alloc_graph(fwd_alloc, gf);
  173. ggml_graph_compute_with_ctx(model.ctx, gf, params.n_threads);
  174. // encoder_output is valid until we call `ggml_allocr_reset(fwd_alloc)`
  175. ggml_tensor* encoder_output = gf->nodes[gf->n_nodes - 1];
  176. // Beam search decoding
  177. const Hypothesis* result = unity_decode(model, params.opts, tgt_lang_idx, encoder_output, params.n_threads);
  178. // Drop language and bos token.
  179. ggml_tensor* tokens = ggml_slice(model.ctx, result[0].seq, 0, 2, 0);
  180. // Collect result string
  181. int n = fairseq2_spm_detokenize(&model, tokens, (char*)&result_str);
  182. std::cout << std::string((char*)&result_str, n) << std::endl;
  183. ggml_free(model.ctx);
  184. ggml_allocr_reset(fwd_alloc);
  185. }
  186. return 0;
  187. }