unity_lib.cpp 7.9 KB

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