1 | /* Copyright 2015 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_STRING_TO_HASH_BUCKET_FAST_OP_H_ |
17 | #define TENSORFLOW_CORE_KERNELS_STRING_TO_HASH_BUCKET_FAST_OP_H_ |
18 | |
19 | #include <string> |
20 | |
21 | #include "tensorflow/core/framework/op_kernel.h" |
22 | #include "tensorflow/core/framework/tensor.h" |
23 | #include "tensorflow/core/lib/core/errors.h" |
24 | #include "tensorflow/core/lib/core/status.h" |
25 | #include "tensorflow/core/platform/macros.h" |
26 | |
27 | namespace tensorflow { |
28 | |
29 | template <uint64 hash(StringPiece)> |
30 | class StringToHashBucketOp : public OpKernel { |
31 | public: |
32 | explicit StringToHashBucketOp(OpKernelConstruction* ctx) : OpKernel(ctx) { |
33 | OP_REQUIRES_OK(ctx, ctx->GetAttr("num_buckets" , &num_buckets_)); |
34 | } |
35 | |
36 | void Compute(OpKernelContext* context) override { |
37 | const Tensor* input_tensor; |
38 | OP_REQUIRES_OK(context, context->input("input" , &input_tensor)); |
39 | const auto& input_flat = input_tensor->flat<tstring>(); |
40 | |
41 | Tensor* output_tensor = nullptr; |
42 | OP_REQUIRES_OK(context, |
43 | context->allocate_output("output" , input_tensor->shape(), |
44 | &output_tensor)); |
45 | auto output_flat = output_tensor->flat<int64_t>(); |
46 | |
47 | typedef decltype(input_flat.size()) Index; |
48 | for (Index i = 0; i < input_flat.size(); ++i) { |
49 | const uint64 input_hash = hash(input_flat(i)); |
50 | const uint64 bucket_id = input_hash % num_buckets_; |
51 | // The number of buckets is always in the positive range of int64 so is |
52 | // the resulting bucket_id. Casting the bucket_id from uint64 to int64 is |
53 | // safe. |
54 | output_flat(i) = static_cast<int64_t>(bucket_id); |
55 | } |
56 | } |
57 | |
58 | private: |
59 | int64_t num_buckets_; |
60 | |
61 | TF_DISALLOW_COPY_AND_ASSIGN(StringToHashBucketOp); |
62 | }; |
63 | |
64 | } // namespace tensorflow |
65 | |
66 | #endif // TENSORFLOW_CORE_KERNELS_STRING_TO_HASH_BUCKET_FAST_OP_H_ |
67 | |