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 | // Kernels of the StatelessShuffle op. |
17 | |
18 | #include <tuple> |
19 | |
20 | #include "tensorflow/core/framework/register_types.h" |
21 | #include "tensorflow/core/kernels/random_ops_util.h" |
22 | #include "tensorflow/core/kernels/shuffle_common.h" |
23 | #include "tensorflow/core/kernels/stateless_random_ops_v2_util.h" |
24 | |
25 | namespace tensorflow { |
26 | |
27 | template <typename T> |
28 | class StatelessShuffleOp : public OpKernel { |
29 | public: |
30 | explicit StatelessShuffleOp(OpKernelConstruction* ctx) |
31 | : OpKernel(ctx) {} |
32 | |
33 | void Compute(OpKernelContext* ctx) override { |
34 | const Tensor& input = ctx->input(0); |
35 | OP_REQUIRES_VALUE(auto key_counter_alg, ctx, |
36 | GetKeyCounterAlgFromInputs(ctx, 1, 2, 3)); |
37 | auto key_t = std::get<0>(key_counter_alg); |
38 | auto counter_t = std::get<1>(key_counter_alg); |
39 | auto alg = std::get<2>(key_counter_alg); |
40 | |
41 | if (alg != RNG_ALG_PHILOX) { |
42 | OP_REQUIRES(ctx, false, |
43 | errors::InvalidArgument("Unsupported algorithm id: " , alg)); |
44 | } |
45 | |
46 | auto rng = GetPhiloxRandomFromCounterKeyMem(counter_t.flat<uint64>().data(), |
47 | key_t.flat<uint64>().data()); |
48 | auto get_rng = [rng](auto num_samples) { return rng; }; |
49 | OP_REQUIRES_OK(ctx, |
50 | RandomShuffle<T>(ctx, input, /*output_idx=*/0, get_rng)); |
51 | } |
52 | }; |
53 | |
54 | #define REGISTER(T) \ |
55 | REGISTER_KERNEL_BUILDER(Name("StatelessShuffle") \ |
56 | .Device(DEVICE_CPU) \ |
57 | .TypeConstraint<T>("T"), \ |
58 | StatelessShuffleOp<T>); |
59 | |
60 | TF_CALL_ALL_TYPES(REGISTER) |
61 | |
62 | #undef REGISTER |
63 | |
64 | } // namespace tensorflow |
65 | |