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 16 // See docs in ../ops/array_ops.cc 17 18 #ifndef TENSORFLOW_KERNELS_ONE_HOT_OP_H_ 19 #define TENSORFLOW_KERNELS_ONE_HOT_OP_H_ 20 // Generator definition for OneHotOp, must be compilable by nvcc. 21 22 #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" 23 #include "tensorflow/core/framework/tensor_types.h" 24 #include "tensorflow/core/platform/types.h" 25 26 namespace tensorflow { 27 28 namespace generator { 29 30 template <typename T, typename TI> 31 class OneGenerator { 32 public: 33 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE 34 OneGenerator(const typename TTypes<TI>::ConstMatrix& indices, 35 const typename TTypes<T>::ConstScalar& on_value, 36 const typename TTypes<T>::ConstScalar& off_value) 37 : indices_(indices), on_value_(on_value), off_value_(off_value) {} 38 39 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T 40 operator()(const Eigen::array<Eigen::DenseIndex, 3>& pre_depth_suff) const { 41 return (indices_(pre_depth_suff[0], pre_depth_suff[2]) == pre_depth_suff[1]) 42 ? on_value_() 43 : off_value_(); 44 } 45 46 private: 47 const typename TTypes<TI>::ConstMatrix indices_; 48 const typename TTypes<T>::ConstScalar on_value_; 49 const typename TTypes<T>::ConstScalar off_value_; 50 }; 51 52 } // namespace generator 53 54 namespace functor { 55 56 template <typename Device, typename T, typename TI> 57 struct OneHot { 58 EIGEN_ALWAYS_INLINE static void Compute( 59 const Device& d, const typename TTypes<TI>::ConstMatrix& indices, 60 const typename TTypes<T>::ConstScalar& on_value, 61 const typename TTypes<T>::ConstScalar& off_value, 62 typename TTypes<T, 3>::Tensor* output) { 63 generator::OneGenerator<T, TI> generator(indices, on_value, off_value); 64 output->device(d) = output->generate(generator); 65 } 66 }; 67 68 } // namespace functor 69 70 } // namespace tensorflow 71 72 #endif // TENSORFLOW_KERNELS_ONE_HOT_OP_H_ 73