unity.cpp 7.8 KB

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