• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2022 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 #ifndef TENSORFLOW_CORE_KERNELS_STATELESS_RANDOM_OPS_V2_UTIL_H_
17 #define TENSORFLOW_CORE_KERNELS_STATELESS_RANDOM_OPS_V2_UTIL_H_
18 
19 // Utilities for V2 stateless random ops' (non-XLA) kernels.
20 
21 #include <string>
22 
23 #include "tensorflow/core/framework/op_kernel.h"
24 #include "tensorflow/core/kernels/stateless_random_ops_v2.h"
25 
26 namespace tensorflow {
27 
28 template <typename T>
GetScalar(const Tensor & tensor,int input_idx,T * result)29 Status GetScalar(const Tensor& tensor, int input_idx, T* result) {
30   auto dtype = DataTypeToEnum<T>::v();
31   if (tensor.dims() != 0) {
32     return errors::InvalidArgument("input ", std::to_string(input_idx),
33                                    " (0-based) must have shape [], not ",
34                                    tensor.shape().DebugString());
35   }
36   if (tensor.dtype() != dtype) {
37     return errors::InvalidArgument("dtype of input ", std::to_string(input_idx),
38                                    " (0-based) must be ", DataTypeString(dtype),
39                                    ", not ", DataTypeString(tensor.dtype()));
40   }
41   *result = tensor.flat<T>()(0);
42   return OkStatus();
43 }
44 
45 inline StatusOr<std::tuple<Tensor, Tensor, Algorithm> >
GetKeyCounterAlgFromInputs(OpKernelContext * ctx,int key_input_idx,int counter_input_idx,int alg_input_idx)46 GetKeyCounterAlgFromInputs(OpKernelContext* ctx, int key_input_idx,
47                            int counter_input_idx, int alg_input_idx) {
48   const Tensor& key_t = ctx->input(key_input_idx);
49   const Tensor& counter_t = ctx->input(counter_input_idx);
50   const Tensor& alg_t = ctx->input(alg_input_idx);
51 
52   int alg_id;
53   TF_RETURN_IF_ERROR(GetScalar(alg_t, alg_input_idx, &alg_id));
54   Algorithm alg = Algorithm(alg_id);
55   if (alg == RNG_ALG_AUTO_SELECT) {
56     alg = RNG_ALG_PHILOX;
57   }
58 
59   TF_RETURN_IF_ERROR(
60       CheckKeyCounterShape(alg, key_t.shape(), counter_t.shape()));
61   return std::make_tuple(key_t, counter_t, alg);
62 }
63 
64 }  // end namespace tensorflow
65 
66 #endif  // TENSORFLOW_CORE_KERNELS_STATELESS_RANDOM_OPS_V2_UTIL_H_
67