1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved. 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 ==============================================================================*/ 15 // LINT.IfChange 16 17 #ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ 18 #define TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ 19 20 #include <cmath> 21 #include <limits> 22 23 namespace tensorflow { 24 namespace ctc { 25 26 template <class T> kLogZero()27constexpr T kLogZero() { 28 return -std::numeric_limits<T>::infinity(); // NOLINT 29 } 30 31 // Add logarithmic probabilities using: 32 // ln(a + b) = ln(a) + ln(1 + exp(ln(b) - ln(a))) 33 // The two inputs are assumed to be log probabilities. 34 // (GravesTh) Eq. 7.18 35 template <typename T> LogSumExp(T log_prob_1,T log_prob_2)36inline T LogSumExp(T log_prob_1, T log_prob_2) { 37 // const T kLogZero = -std::numeric_limits<T>::infinity(); 38 // Always have 'b' be the smaller number to avoid the exponential from 39 // blowing up. 40 if (log_prob_1 == kLogZero<T>()) { 41 return log_prob_2; 42 } else if (log_prob_2 == kLogZero<T>()) { 43 return log_prob_1; 44 } else { 45 return (log_prob_1 > log_prob_2) 46 ? log_prob_1 + log1pf(expf(log_prob_2 - log_prob_1)) 47 : log_prob_2 + log1pf(expf(log_prob_1 - log_prob_2)); 48 } 49 } 50 51 } // namespace ctc 52 } // namespace tensorflow 53 54 #endif // TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ 55 // LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_loss_util.h) 56