1 /* Copyright 2017 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/compiler/tf2xla/type_util.h" 17 #include "tensorflow/compiler/tf2xla/xla_helpers.h" 18 #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" 19 #include "tensorflow/compiler/tf2xla/xla_op_registry.h" 20 #include "tensorflow/compiler/xla/primitive_util.h" 21 #include "tensorflow/core/framework/kernel_def_builder.h" 22 23 namespace tensorflow { 24 namespace { 25 26 class CastOp : public XlaOpKernel { 27 public: CastOp(OpKernelConstruction * ctx)28 explicit CastOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { 29 OP_REQUIRES_OK(ctx, ctx->GetAttr("SrcT", &src_dtype_)); 30 OP_REQUIRES_OK(ctx, ctx->GetAttr("DstT", &dst_dtype_)); 31 OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(src_dtype_, &src_type_)); 32 OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dst_dtype_, &dst_type_)); 33 } 34 Compile(XlaOpKernelContext * ctx)35 void Compile(XlaOpKernelContext* ctx) override { 36 xla::ComputationBuilder* builder = ctx->builder(); 37 xla::ComputationDataHandle input = ctx->Input(0); 38 xla::ComputationDataHandle output; 39 40 if (src_dtype_ == dst_dtype_) { 41 output = input; 42 } else if (dst_dtype_ == DT_BOOL) { 43 output = builder->Ne(input, XlaHelpers::Zero(builder, src_dtype_)); 44 } else if (xla::primitive_util::IsComplexType(src_type_) && 45 !xla::primitive_util::IsComplexType(dst_type_)) { 46 // As in cast_op.h, we replicate the numpy behavior of truncating the 47 // imaginary part. 48 output = builder->ConvertElementType(builder->Real(input), dst_type_); 49 } else { 50 output = builder->ConvertElementType(input, dst_type_); 51 } 52 53 ctx->SetOutput(0, output); 54 } 55 56 protected: 57 DataType src_dtype_, dst_dtype_; 58 xla::PrimitiveType src_type_, dst_type_; 59 60 TF_DISALLOW_COPY_AND_ASSIGN(CastOp); 61 }; 62 63 REGISTER_XLA_OP(Name("Cast"), CastOp); 64 65 } // anonymous namespace 66 } // namespace tensorflow 67