You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

208 lines
7.9 KiB

  1. // Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "decoder/ctc_prefix_beam_search.h"
  15. #include <algorithm>
  16. #include <tuple>
  17. #include <unordered_map>
  18. #include <utility>
  19. #include "utils/wn_utils.h"
  20. namespace wenet {
  21. CtcPrefixBeamSearch::CtcPrefixBeamSearch(
  22. const CtcPrefixBeamSearchOptions& opts,
  23. const std::shared_ptr<ContextGraph>& context_graph)
  24. : opts_(opts), context_graph_(context_graph) {
  25. Reset();
  26. }
  27. void CtcPrefixBeamSearch::Reset() {
  28. hypotheses_.clear();
  29. likelihood_.clear();
  30. cur_hyps_.clear();
  31. viterbi_likelihood_.clear();
  32. times_.clear();
  33. outputs_.clear();
  34. abs_time_step_ = 0;
  35. PrefixScore prefix_score;
  36. prefix_score.s = 0.0;
  37. prefix_score.ns = -kFloatMax;
  38. prefix_score.v_s = 0.0;
  39. prefix_score.v_ns = 0.0;
  40. std::vector<int> empty;
  41. cur_hyps_[empty] = prefix_score;
  42. outputs_.emplace_back(empty);
  43. hypotheses_.emplace_back(empty);
  44. likelihood_.emplace_back(prefix_score.total_score());
  45. times_.emplace_back(empty);
  46. }
  47. static bool PrefixScoreCompare(
  48. const std::pair<std::vector<int>, PrefixScore>& a,
  49. const std::pair<std::vector<int>, PrefixScore>& b) {
  50. return a.second.total_score() > b.second.total_score();
  51. }
  52. void CtcPrefixBeamSearch::UpdateHypotheses(
  53. const std::vector<std::pair<std::vector<int>, PrefixScore>>& hpys) {
  54. cur_hyps_.clear();
  55. outputs_.clear();
  56. hypotheses_.clear();
  57. likelihood_.clear();
  58. viterbi_likelihood_.clear();
  59. times_.clear();
  60. for (auto& item : hpys) {
  61. cur_hyps_[item.first] = item.second;
  62. hypotheses_.emplace_back(item.first);
  63. outputs_.emplace_back(std::move(item.first));
  64. likelihood_.emplace_back(item.second.total_score());
  65. viterbi_likelihood_.emplace_back(item.second.viterbi_score());
  66. times_.emplace_back(item.second.times());
  67. }
  68. }
  69. // Please refer https://robin1001.github.io/2020/12/11/ctc-search
  70. // for how CTC prefix beam search works, and there is a simple graph demo in
  71. // it.
  72. void CtcPrefixBeamSearch::Search(const std::vector<std::vector<float>>& logp) {
  73. if (logp.size() == 0) return;
  74. int first_beam_size =
  75. std::min(static_cast<int>(logp[0].size()), opts_.first_beam_size);
  76. for (int t = 0; t < logp.size(); ++t, ++abs_time_step_) {
  77. const std::vector<float>& logp_t = logp[t];
  78. std::unordered_map<std::vector<int>, PrefixScore, PrefixHash> next_hyps;
  79. // 1. First beam prune, only select topk candidates
  80. std::vector<float> topk_score;
  81. std::vector<int32_t> topk_index;
  82. TopK(logp_t, first_beam_size, &topk_score, &topk_index);
  83. // 2. Token passing
  84. for (int i = 0; i < topk_index.size(); ++i) {
  85. int id = topk_index[i];
  86. auto prob = topk_score[i];
  87. for (const auto& it : cur_hyps_) {
  88. const std::vector<int>& prefix = it.first;
  89. const PrefixScore& prefix_score = it.second;
  90. // If prefix doesn't exist in next_hyps, next_hyps[prefix] will insert
  91. // PrefixScore(-inf, -inf) by default, since the default constructor
  92. // of PrefixScore will set fields s(blank ending score) and
  93. // ns(none blank ending score) to -inf, respectively.
  94. if (id == opts_.blank) {
  95. // Case 0: *a + ε => *a
  96. PrefixScore& next_score = next_hyps[prefix];
  97. next_score.s = LogAdd(next_score.s, prefix_score.score() + prob);
  98. next_score.v_s = prefix_score.viterbi_score() + prob;
  99. next_score.times_s = prefix_score.times();
  100. // Prefix not changed, copy the context from prefix.
  101. if (context_graph_ && !next_score.has_context) {
  102. next_score.CopyContext(prefix_score);
  103. next_score.has_context = true;
  104. }
  105. } else if (!prefix.empty() && id == prefix.back()) {
  106. // Case 1: *a + a => *a
  107. PrefixScore& next_score1 = next_hyps[prefix];
  108. next_score1.ns = LogAdd(next_score1.ns, prefix_score.ns + prob);
  109. if (next_score1.v_ns < prefix_score.v_ns + prob) {
  110. next_score1.v_ns = prefix_score.v_ns + prob;
  111. if (next_score1.cur_token_prob < prob) {
  112. next_score1.cur_token_prob = prob;
  113. next_score1.times_ns = prefix_score.times_ns;
  114. CHECK_GT(next_score1.times_ns.size(), 0);
  115. next_score1.times_ns.back() = abs_time_step_;
  116. }
  117. }
  118. if (context_graph_ && !next_score1.has_context) {
  119. next_score1.CopyContext(prefix_score);
  120. next_score1.has_context = true;
  121. }
  122. // Case 2: *aε + a => *aa
  123. std::vector<int> new_prefix(prefix);
  124. new_prefix.emplace_back(id);
  125. PrefixScore& next_score2 = next_hyps[new_prefix];
  126. next_score2.ns = LogAdd(next_score2.ns, prefix_score.s + prob);
  127. if (next_score2.v_ns < prefix_score.v_s + prob) {
  128. next_score2.v_ns = prefix_score.v_s + prob;
  129. next_score2.cur_token_prob = prob;
  130. next_score2.times_ns = prefix_score.times_s;
  131. next_score2.times_ns.emplace_back(abs_time_step_);
  132. }
  133. if (context_graph_ && !next_score2.has_context) {
  134. // Prefix changed, calculate the context score.
  135. next_score2.UpdateContext(context_graph_, prefix_score, id);
  136. next_score2.has_context = true;
  137. }
  138. } else {
  139. // Case 3: *a + b => *ab, *aε + b => *ab
  140. std::vector<int> new_prefix(prefix);
  141. new_prefix.emplace_back(id);
  142. PrefixScore& next_score = next_hyps[new_prefix];
  143. next_score.ns = LogAdd(next_score.ns, prefix_score.score() + prob);
  144. if (next_score.v_ns < prefix_score.viterbi_score() + prob) {
  145. next_score.v_ns = prefix_score.viterbi_score() + prob;
  146. next_score.cur_token_prob = prob;
  147. next_score.times_ns = prefix_score.times();
  148. next_score.times_ns.emplace_back(abs_time_step_);
  149. }
  150. if (context_graph_ && !next_score.has_context) {
  151. // Calculate the context score.
  152. next_score.UpdateContext(context_graph_, prefix_score, id);
  153. next_score.has_context = true;
  154. }
  155. }
  156. }
  157. }
  158. // 3. Second beam prune, only keep top n best paths
  159. std::vector<std::pair<std::vector<int>, PrefixScore>> arr(next_hyps.begin(),
  160. next_hyps.end());
  161. int second_beam_size =
  162. std::min(static_cast<int>(arr.size()), opts_.second_beam_size);
  163. std::nth_element(arr.begin(), arr.begin() + second_beam_size, arr.end(),
  164. PrefixScoreCompare);
  165. arr.resize(second_beam_size);
  166. std::sort(arr.begin(), arr.end(), PrefixScoreCompare);
  167. // 4. Update cur_hyps_ and get new result
  168. UpdateHypotheses(arr);
  169. }
  170. }
  171. void CtcPrefixBeamSearch::FinalizeSearch() {
  172. if (context_graph_ == nullptr) return;
  173. CHECK_EQ(hypotheses_.size(), cur_hyps_.size());
  174. CHECK_EQ(hypotheses_.size(), likelihood_.size());
  175. // We should backoff the context score/state when the context is
  176. // not fully matched at the last time.
  177. for (const auto& prefix : hypotheses_) {
  178. PrefixScore& prefix_score = cur_hyps_[prefix];
  179. if (prefix_score.context_state != 0) {
  180. prefix_score.UpdateContext(context_graph_, prefix_score, -1);
  181. }
  182. }
  183. std::vector<std::pair<std::vector<int>, PrefixScore>> arr(cur_hyps_.begin(),
  184. cur_hyps_.end());
  185. std::sort(arr.begin(), arr.end(), PrefixScoreCompare);
  186. // Update cur_hyps_ and get new result
  187. UpdateHypotheses(arr);
  188. }
  189. } // namespace wenet