unity_lib.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. #include "unity_lib.h"
  2. #include <algorithm>
  3. struct ggml_cgraph * unity_text_encoder(
  4. fairseq2_model & model,
  5. struct ggml_tensor * text_input) {
  6. ggml_context* ctx0 = model.ctx;
  7. ggml_cgraph* gf = ggml_new_graph(ctx0);
  8. ggml_tensor* seqs = TransformerEmbeddingFrontend_forward(model, "text_encoder_frontend", text_input);
  9. ggml_tensor* encoder_output = StandardTransformerEncoder_forward(
  10. model,
  11. "text_encoder",
  12. seqs,
  13. nullptr // TODO: handle padding mask
  14. );
  15. encoder_output = ggml_dup(model.ctx, encoder_output);
  16. ggml_build_forward_expand(gf, encoder_output);
  17. return gf;
  18. }
  19. struct ggml_cgraph * unity_speech_encoder(
  20. fairseq2_model& model,
  21. struct ggml_tensor * speech_input) {
  22. ggml_context* ctx0 = model.ctx;
  23. ggml_cgraph* gf = ggml_new_graph(ctx0);
  24. ggml_tensor* seqs = StandardConformerEncoder_forward(model, "speech_encoder", speech_input, nullptr);
  25. seqs = ggml_dup(model.ctx, seqs);
  26. ggml_build_forward_expand(gf, seqs);
  27. return gf;
  28. }
  29. Hypothesis* unity_decode(
  30. fairseq2_model& model,
  31. const SequenceGeneratorOptions& opts,
  32. int tgt_lang_idx,
  33. ggml_tensor* encoder_output,
  34. int n_threads
  35. ) {
  36. SequenceGeneratorJob job = {
  37. opts,
  38. /*prefix_seq*/ nullptr,
  39. /*pad_idx*/model.vocab.token_to_id["<pad>"],
  40. /*unk_idx*/model.vocab.token_to_id["<unk>"],
  41. /*bos_idx*/model.vocab.token_to_id["<s>"],
  42. /*eos_idx*/model.vocab.token_to_id["</s>"],
  43. /*num_threads*/n_threads,
  44. };
  45. int prefix_seq_len = model.hparams["multilingual"] ? 2 : 1;
  46. FORCE_ALLOC(prefix_seq, model.ctx, ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, prefix_seq_len));
  47. ((int *)prefix_seq->data)[0] = job.eos_idx;
  48. if (model.hparams["multilingual"] != 0) {
  49. ((int *)prefix_seq->data)[1] = tgt_lang_idx;
  50. }
  51. job.prefix_seq = prefix_seq;
  52. return generate_sequence(model, job, encoder_output, nullptr, model.ctx, n_threads);
  53. }
  54. extern "C" fairseq2_model unity_init_model(const char* model_path) {
  55. fairseq2_model model;
  56. load_fairseq2_ggml_file(model, model_path);
  57. return model;
  58. }
  59. // struct as return - transcription, CE score, LID
  60. extern "C" Result unity_eval_speech(fairseq2_model& model, std::vector<float>& data, SequenceGeneratorOptions opts, std::string tgt_lang, int n_threads) {
  61. Result result;
  62. // The ctx_size_mb mostly depends of input length and model dim.
  63. int ctx_size_mb = opts.mem_mb;
  64. auto encoder_buf = std::vector<uint8_t>(8 * 1024 * 1024); // this is only for tensor metadata, it can be small
  65. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  66. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  67. int tgt_lang_idx;
  68. if (tgt_lang == "unk") {
  69. tgt_lang_idx = model.vocab.token_to_id["<unk>"];
  70. } else {
  71. auto tgt_lang_ptr = model.vocab.token_to_id.find("__" + tgt_lang + "__");
  72. if (tgt_lang_ptr == model.vocab.token_to_id.end()) {
  73. std::cerr << "Unknown language " << tgt_lang << "\n";
  74. result.err = 1;
  75. return result;
  76. }
  77. tgt_lang_idx = tgt_lang_ptr->second;
  78. }
  79. // Reset the ggml_context
  80. model.ctx = ctx_from_buffer(encoder_buf);
  81. ggml_set_no_alloc(model.ctx, true);
  82. ggml_tensor* seqs = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, data.size(), 1);
  83. seqs->data = data.data();
  84. // Audio encoder
  85. ggml_cgraph* gf = unity_speech_encoder(model, seqs);
  86. ggml_allocr_alloc_graph(fwd_alloc, gf);
  87. ggml_graph_compute_with_ctx(model.ctx, gf, n_threads);
  88. // encoder_output is valid until we call `ggml_allocr_reset(fwd_alloc)`
  89. ggml_tensor* encoder_output = gf->nodes[gf->n_nodes - 1];
  90. // Beam search decoding
  91. const Hypothesis* hypo = unity_decode(model, opts, tgt_lang_idx, encoder_output, n_threads);
  92. // Drop language and bos token.
  93. ggml_tensor* tokens = ggml_slice(model.ctx, hypo[0].seq, 0, 2, 0);
  94. // Collect result string
  95. char result_str[4096];
  96. std::pair<std::vector<std::string>, std::vector<float>> p = fairseq2_spm_detokenize(&model, tokens, hypo[0].step_scores, (char*)&result_str);
  97. std::vector<std::string> result_tokens = p.first;
  98. std::vector<float> word_scores = p.second;
  99. std::unordered_map<std::string, float> lid_scores;
  100. std::vector<int> lang_ids;
  101. for (const auto& kv : model.vocab.token_to_id) {
  102. if (kv.first.substr(0, 2) == "__" && kv.first.substr(kv.first.size() - 2) == "__") {
  103. lang_ids.push_back(kv.second);
  104. }
  105. }
  106. std::sort(lang_ids.begin(), lang_ids.end());
  107. for (size_t i = 0; i < lang_ids.size(); ++i) {
  108. lid_scores[model.vocab.id_to_token[lang_ids[i]].text] = ggml_get_f32_1d(hypo[0].lid_scores, i);
  109. }
  110. result.transcription = result_tokens;
  111. result.word_confidence_scores = word_scores;
  112. result.lid_scores = lid_scores;
  113. result.err = 0;
  114. ggml_free(model.ctx);
  115. ggml_allocr_reset(fwd_alloc);
  116. return result;
  117. }
  118. extern "C" Result unity_eval_text(fairseq2_model& model, const std::string& text, SequenceGeneratorOptions opts, std::string tgt_lang, int n_threads) {
  119. Result result;
  120. // The ctx_size_mb mostly depends of input length and model dim.
  121. int ctx_size_mb = opts.mem_mb;
  122. auto encoder_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  123. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  124. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  125. int tgt_lang_idx;
  126. if (model.hparams["multilingual"] != 0) {
  127. auto tgt_lang_ptr = model.vocab.token_to_id.find("__" + tgt_lang + "__");
  128. if (tgt_lang_ptr == model.vocab.token_to_id.end()) {
  129. std::cerr << "Unknown language " << tgt_lang << "\n";
  130. result.err = 1;
  131. return result;
  132. }
  133. tgt_lang_idx = tgt_lang_ptr->second;
  134. }
  135. // tokenize the input text
  136. model.ctx = ctx_from_buffer(encoder_buf);
  137. ggml_set_no_alloc(model.ctx, false);
  138. ggml_tensor* tokens = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, 64);
  139. ggml_set_no_alloc(model.ctx, true);
  140. fairseq2_spm_tokenize(&model, text.c_str(), tokens);
  141. // Text encoder
  142. ggml_cgraph* gf = unity_text_encoder(model, tokens);
  143. ggml_allocr_alloc_graph(fwd_alloc, gf);
  144. ggml_graph_compute_with_ctx(model.ctx, gf, n_threads);
  145. ggml_tensor* encoder_output = gf->nodes[gf->n_nodes - 1];
  146. // Beam search decoding
  147. const Hypothesis* hypo = unity_decode(model, opts, tgt_lang_idx, encoder_output, n_threads);
  148. // Drop language and bos token.
  149. ggml_tensor* tgt_tokens = ggml_slice(model.ctx, hypo[0].seq, 0, 2, 0);
  150. // Collect result string
  151. char result_str[4096];
  152. std::pair<std::vector<std::string>, std::vector<float>> p = fairseq2_spm_detokenize(&model, tgt_tokens, hypo[0].step_scores, (char*)&result_str);
  153. std::vector<std::string> result_tokens = p.first;
  154. std::vector<float> word_scores = p.second;
  155. std::unordered_map<std::string, float> lid_scores;
  156. if (model.hparams["multilingual"] != 0) {
  157. std::vector<int> lang_ids;
  158. for (const auto& kv : model.vocab.token_to_id) {
  159. if (kv.first.substr(0, 2) == "__" && kv.first.substr(kv.first.size() - 2) == "__") {
  160. lang_ids.push_back(kv.second);
  161. }
  162. }
  163. std::sort(lang_ids.begin(), lang_ids.end());
  164. for (size_t i = 0; i < lang_ids.size(); ++i) {
  165. lid_scores[model.vocab.id_to_token[lang_ids[i]].text] = ggml_get_f32_1d(hypo[0].lid_scores, i);
  166. }
  167. result.lid_scores = lid_scores;
  168. }
  169. result.transcription = result_tokens;
  170. result.word_confidence_scores = word_scores;
  171. result.err = 0;
  172. ggml_free(model.ctx);
  173. ggml_allocr_reset(fwd_alloc);
  174. return result;
  175. }