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.

81 lines
2.4 KiB

  1. // Copyright (c) 2021 Mobvoi Inc (Zhendong Peng)
  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 "wn_utils.h"
  15. #include <algorithm>
  16. #include <cmath>
  17. #include <cstdint>
  18. #include <queue>
  19. #include <utility>
  20. #include <vector>
  21. namespace wenet {
  22. float LogAdd(float x, float y) {
  23. static float num_min = -std::numeric_limits<float>::max();
  24. if (x <= num_min) return y;
  25. if (y <= num_min) return x;
  26. float xmax = std::max(x, y);
  27. return std::log(std::exp(x - xmax) + std::exp(y - xmax)) + xmax;
  28. }
  29. template <typename T>
  30. struct ValueComp {
  31. bool operator()(const std::pair<T, int32_t>& lhs,
  32. const std::pair<T, int32_t>& rhs) const {
  33. return lhs.first > rhs.first ||
  34. (lhs.first == rhs.first && lhs.second < rhs.second);
  35. }
  36. };
  37. // We refer the pytorch topk implementation
  38. // https://github.com/pytorch/pytorch/blob/master/caffe2/operators/top_k.cc
  39. template <typename T>
  40. void TopK(const std::vector<T>& data, int32_t k, std::vector<T>* values,
  41. std::vector<int>* indices) {
  42. std::vector<std::pair<T, int32_t>> heap_data;
  43. int n = data.size();
  44. for (int32_t i = 0; i < k && i < n; ++i) {
  45. heap_data.emplace_back(data[i], i);
  46. }
  47. std::priority_queue<std::pair<T, int32_t>, std::vector<std::pair<T, int32_t>>,
  48. ValueComp<T>>
  49. pq(ValueComp<T>(), std::move(heap_data));
  50. for (int32_t i = k; i < n; ++i) {
  51. if (pq.top().first < data[i]) {
  52. pq.pop();
  53. pq.emplace(data[i], i);
  54. }
  55. }
  56. values->resize(std::min(k, n));
  57. indices->resize(std::min(k, n));
  58. int32_t cur = values->size() - 1;
  59. while (!pq.empty()) {
  60. const auto& item = pq.top();
  61. (*values)[cur] = item.first;
  62. (*indices)[cur] = item.second;
  63. pq.pop();
  64. cur -= 1;
  65. }
  66. }
  67. template void TopK<float>(const std::vector<float>& data, int32_t k,
  68. std::vector<float>* values,
  69. std::vector<int>* indices);
  70. } // namespace wenet