unity_lib.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. FORCE_ALLOC(prefix_seq, model.ctx, ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, 2));
  46. ((int *)prefix_seq->data)[0] = job.eos_idx;
  47. if (model.hparams["multilingual"] != 0) {
  48. ((int *)prefix_seq->data)[1] = tgt_lang_idx;
  49. }
  50. job.prefix_seq = prefix_seq;
  51. return generate_sequence(model, job, encoder_output, nullptr, model.ctx, n_threads);
  52. }
  53. extern "C" fairseq2_model unity_init_model(const char* model_path) {
  54. fairseq2_model model;
  55. load_fairseq2_ggml_file(model, model_path);
  56. return model;
  57. }
  58. // struct as return - transcription, CE score, LID
  59. extern "C" Result unity_eval_speech(fairseq2_model& model, std::vector<float>& data, SequenceGeneratorOptions opts, std::string tgt_lang, int n_threads) {
  60. Result result;
  61. // The ctx_size_mb mostly depends of input length and model dim.
  62. int ctx_size_mb = opts.mem_mb;
  63. auto encoder_buf = std::vector<uint8_t>(8 * 1024 * 1024); // this is only for tensor metadata, it can be small
  64. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  65. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  66. int tgt_lang_idx;
  67. if (tgt_lang == "unk") {
  68. tgt_lang_idx = model.vocab.token_to_id["<unk>"];
  69. } else {
  70. auto tgt_lang_ptr = model.vocab.token_to_id.find("__" + tgt_lang + "__");
  71. if (tgt_lang_ptr == model.vocab.token_to_id.end()) {
  72. std::cerr << "Unknown language " << tgt_lang << "\n";
  73. result.err = 1;
  74. return result;
  75. }
  76. tgt_lang_idx = tgt_lang_ptr->second;
  77. }
  78. // Reset the ggml_context
  79. model.ctx = ctx_from_buffer(encoder_buf);
  80. ggml_set_no_alloc(model.ctx, true);
  81. ggml_tensor* seqs = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, data.size(), 1);
  82. seqs->data = data.data();
  83. // Audio encoder
  84. ggml_cgraph* gf = unity_speech_encoder(model, seqs);
  85. ggml_allocr_alloc_graph(fwd_alloc, gf);
  86. ggml_graph_compute_with_ctx(model.ctx, gf, n_threads);
  87. // encoder_output is valid until we call `ggml_allocr_reset(fwd_alloc)`
  88. ggml_tensor* encoder_output = gf->nodes[gf->n_nodes - 1];
  89. // Beam search decoding
  90. const Hypothesis* hypo = unity_decode(model, opts, tgt_lang_idx, encoder_output, n_threads);
  91. // Drop language and bos token.
  92. ggml_tensor* tokens = ggml_slice(model.ctx, hypo[0].seq, 0, 2, 0);
  93. // Collect result string
  94. char result_str[4096];
  95. std::pair<std::vector<std::string>, std::vector<float>> p = fairseq2_spm_detokenize(&model, tokens, hypo[0].step_scores, (char*)&result_str);
  96. std::vector<std::string> result_tokens = p.first;
  97. std::vector<float> word_scores = p.second;
  98. std::unordered_map<std::string, float> lid_scores;
  99. std::vector<int> lang_ids;
  100. for (const auto& kv : model.vocab.token_to_id) {
  101. if (kv.first.substr(0, 2) == "__" && kv.first.substr(kv.first.size() - 2) == "__") {
  102. lang_ids.push_back(kv.second);
  103. }
  104. }
  105. std::sort(lang_ids.begin(), lang_ids.end());
  106. for (size_t i = 0; i < lang_ids.size(); ++i) {
  107. lid_scores[model.vocab.id_to_token[lang_ids[i]].text] = ggml_get_f32_1d(hypo[0].lid_scores, i);
  108. }
  109. result.transcription = result_tokens;
  110. result.word_confidence_scores = word_scores;
  111. result.lid_scores = lid_scores;
  112. result.err = 0;
  113. ggml_free(model.ctx);
  114. ggml_allocr_reset(fwd_alloc);
  115. return result;
  116. }
  117. extern "C" Result unity_eval_text(fairseq2_model& model, const std::string& text, SequenceGeneratorOptions opts, std::string tgt_lang, int n_threads) {
  118. Result result;
  119. // The ctx_size_mb mostly depends of input length and model dim.
  120. int ctx_size_mb = opts.mem_mb;
  121. auto encoder_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  122. auto encoder_fwd_buf = std::vector<uint8_t>(ctx_size_mb * 1024 * 1024);
  123. ggml_allocr* fwd_alloc = ggml_allocr_new(encoder_fwd_buf.data(), encoder_fwd_buf.capacity(), 8);
  124. int tgt_lang_idx;
  125. if (model.hparams["multilingual"] != 0) {
  126. auto tgt_lang_ptr = model.vocab.token_to_id.find("__" + tgt_lang + "__");
  127. if (tgt_lang_ptr == model.vocab.token_to_id.end()) {
  128. std::cerr << "Unknown language " << tgt_lang << "\n";
  129. result.err = 1;
  130. return result;
  131. }
  132. tgt_lang_idx = tgt_lang_ptr->second;
  133. }
  134. // tokenize the input text
  135. model.ctx = ctx_from_buffer(encoder_buf);
  136. ggml_set_no_alloc(model.ctx, false);
  137. ggml_tensor* tokens = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, 64);
  138. ggml_set_no_alloc(model.ctx, true);
  139. fairseq2_spm_tokenize(&model, text.c_str(), tokens);
  140. // Text encoder
  141. ggml_cgraph* gf = unity_text_encoder(model, tokens);
  142. ggml_allocr_alloc_graph(fwd_alloc, gf);
  143. ggml_graph_compute_with_ctx(model.ctx, gf, n_threads);
  144. ggml_tensor* encoder_output = gf->nodes[gf->n_nodes - 1];
  145. // Beam search decoding
  146. const Hypothesis* hypo = unity_decode(model, opts, tgt_lang_idx, encoder_output, n_threads);
  147. // Drop language and bos token.
  148. ggml_tensor* tgt_tokens = ggml_slice(model.ctx, hypo[0].seq, 0, 2, 0);
  149. // Collect result string
  150. char result_str[4096];
  151. std::pair<std::vector<std::string>, std::vector<float>> p = fairseq2_spm_detokenize(&model, tgt_tokens, hypo[0].step_scores, (char*)&result_str);
  152. std::vector<std::string> result_tokens = p.first;
  153. std::vector<float> word_scores = p.second;
  154. std::unordered_map<std::string, float> lid_scores;
  155. std::vector<int> lang_ids;
  156. for (const auto& kv : model.vocab.token_to_id) {
  157. if (kv.first.substr(0, 2) == "__" && kv.first.substr(kv.first.size() - 2) == "__") {
  158. lang_ids.push_back(kv.second);
  159. }
  160. }
  161. std::sort(lang_ids.begin(), lang_ids.end());
  162. for (size_t i = 0; i < lang_ids.size(); ++i) {
  163. lid_scores[model.vocab.id_to_token[lang_ids[i]].text] = ggml_get_f32_1d(hypo[0].lid_scores, i);
  164. }
  165. result.transcription = result_tokens;
  166. result.word_confidence_scores = word_scores;
  167. result.lid_scores = lid_scores;
  168. result.err = 0;
  169. ggml_free(model.ctx);
  170. ggml_allocr_reset(fwd_alloc);
  171. return result;
  172. }