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.

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