1 | /* Copyright 2018 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 | #include "tensorflow/core/kernels/host_constant_op.h" |
17 | |
18 | #include "tensorflow/core/framework/allocator.h" |
19 | #include "tensorflow/core/framework/op_kernel.h" |
20 | #include "tensorflow/core/framework/types.h" |
21 | #include "tensorflow/core/lib/core/status.h" |
22 | #include "tensorflow/core/platform/logging.h" |
23 | #include "tensorflow/core/platform/macros.h" |
24 | |
25 | namespace tensorflow { |
26 | |
27 | _HostConstantOp::_HostConstantOp(OpKernelConstruction* ctx) |
28 | : OpKernel(ctx), tensor_(ctx->output_type(0)) { |
29 | const TensorProto* proto = nullptr; |
30 | AllocatorAttributes alloc_attr; |
31 | alloc_attr.set_on_host(true); |
32 | OP_REQUIRES_OK(ctx, ctx->GetAttr("value" , &proto)); |
33 | OP_REQUIRES_OK( |
34 | ctx, ctx->device()->MakeTensorFromProto(*proto, alloc_attr, &tensor_)); |
35 | OP_REQUIRES( |
36 | ctx, ctx->output_type(0) == tensor_.dtype(), |
37 | errors::InvalidArgument("Type mismatch between value (" , |
38 | DataTypeString(tensor_.dtype()), ") and dtype (" , |
39 | DataTypeString(ctx->output_type(0)), ")" )); |
40 | } |
41 | |
42 | void _HostConstantOp::Compute(OpKernelContext* ctx) { |
43 | ctx->set_output(0, tensor_); |
44 | } |
45 | |
46 | // A special DEVICE_DEFAULT kernel for int32. |
47 | // TODO(b/25387198): Also enable int32 in device memory. This kernel |
48 | // registration requires all int32 inputs and outputs to be in host memory. |
49 | REGISTER_KERNEL_BUILDER(Name("Const" ) |
50 | .Device(DEVICE_DEFAULT) |
51 | .HostMemory("output" ) |
52 | .TypeConstraint<int32>("dtype" ), |
53 | _HostConstantOp); |
54 | |
55 | // HostConst: forced to generate output on the host. |
56 | REGISTER_KERNEL_BUILDER(Name("HostConst" ).Device(DEVICE_CPU), _HostConstantOp); |
57 | REGISTER_KERNEL_BUILDER( |
58 | Name("HostConst" ).Device(DEVICE_DEFAULT).HostMemory("output" ), |
59 | _HostConstantOp); |
60 | |
61 | } // end namespace tensorflow |
62 | |
63 | |