1 /* Copyright 2019 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 // XLA-specific Empty Op. 17 18 #include "tensorflow/compiler/tf2xla/type_util.h" 19 #include "tensorflow/compiler/tf2xla/xla_helpers.h" 20 #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" 21 #include "tensorflow/compiler/tf2xla/xla_op_registry.h" 22 #include "tensorflow/compiler/xla/client/lib/constants.h" 23 #include "tensorflow/compiler/xla/client/xla_builder.h" 24 #include "tensorflow/core/framework/kernel_def_builder.h" 25 #include "tensorflow/core/framework/register_types.h" 26 #include "tensorflow/core/framework/tensor_shape.h" 27 28 namespace tensorflow { 29 namespace { 30 31 class EmptyOp : public XlaOpKernel { 32 public: EmptyOp(OpKernelConstruction * ctx)33 explicit EmptyOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { 34 OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); 35 OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype_, &type_)); 36 OP_REQUIRES_OK(ctx, ctx->GetAttr("init", &init_)); 37 } 38 Compile(XlaOpKernelContext * ctx)39 void Compile(XlaOpKernelContext* ctx) override { 40 // The output of this Op is a tensor of shape 'shape' with each 41 // element set to the default value of 'dtype'. If 'init' is false then 42 // the result values may be left undefined, though we don't do that here. 43 const TensorShape shape_shape = ctx->InputShape("shape"); 44 OP_REQUIRES( 45 ctx, TensorShapeUtils::IsVector(shape_shape), 46 errors::InvalidArgument("shape must be a vector of int32, got shape ", 47 shape_shape.DebugString())); 48 49 std::vector<int64> shape; 50 OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector("shape", &shape)); 51 52 auto default_value = xla::Zero(ctx->builder(), type_); 53 auto result = xla::Broadcast(default_value, shape); 54 ctx->SetOutput(0, result); 55 } 56 57 private: 58 DataType dtype_; 59 xla::PrimitiveType type_; 60 bool init_; 61 }; 62 63 REGISTER_XLA_OP(Name("Empty").CompileTimeConstantInput("shape"), EmptyOp); 64 65 } // namespace 66 } // namespace tensorflow 67