Home | History | Annotate | Download | only in kernels
      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/core/framework/kernel_def_builder.h"
     21 #include "tensorflow/core/framework/node_def.pb.h"
     22 
     23 namespace tensorflow {
     24 namespace {
     25 
     26 const char* const kGradientOp = "SymbolicGradient";
     27 
     28 // Implementations of _ListToArray and _ArrayToList for functions.
     29 class PassOn : public XlaOpKernel {
     30  public:
     31   explicit PassOn(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
     32     OP_REQUIRES(ctx, ctx->num_inputs() == ctx->num_outputs(),
     33                 errors::Internal("#inputs != #outputs : ", ctx->num_inputs(),
     34                                  " vs. ", ctx->num_outputs()));
     35     for (int i = 0; i < ctx->num_inputs(); ++i) {
     36       OP_REQUIRES(
     37           ctx, input_type(i) == output_type(i),
     38           errors::Internal("Input and output types for position ", i,
     39                            " do not match: ", DataTypeString(input_type(i)),
     40                            " vs. ", DataTypeString(output_type(i))));
     41     }
     42   }
     43 
     44   void Compile(XlaOpKernelContext* ctx) override {
     45     for (int i = 0; i < ctx->num_inputs(); ++i) {
     46       ctx->SetOutput(i, ctx->Input(i));
     47     }
     48   }
     49 };
     50 
     51 REGISTER_XLA_OP(Name("_ListToArray"), PassOn);
     52 REGISTER_XLA_OP(Name("_ArrayToList"), PassOn);
     53 
     54 // TODO(phawkins): this is an almost exact copy of the SymbolicGradientOp
     55 // implementation from regular Tensorflow. Once XLA has been open sourced
     56 // merge the two implementations. (Note: this implementation propagates the
     57 // step_resource_manager).
     58 class SymbolicGradientOp : public AsyncOpKernel {
     59  public:
     60   explicit SymbolicGradientOp(OpKernelConstruction* ctx)
     61       : AsyncOpKernel(ctx), handle_(-1) {}
     62 
     63   ~SymbolicGradientOp() override {}
     64 
     65   void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
     66     FunctionLibraryRuntime* lib = ctx->function_library();
     67     OP_REQUIRES_ASYNC(ctx, lib != nullptr,
     68                       errors::Internal("No function library is provided."),
     69                       done);
     70 
     71     OP_REQUIRES_OK_ASYNC(
     72         ctx, lib->Instantiate(kGradientOp, AttrSlice(&def().attr()), &handle_),
     73         done);
     74 
     75     FunctionLibraryRuntime::Options opts;
     76     opts.step_id = ctx->step_id();
     77     opts.runner = ctx->runner();
     78     opts.step_container = ctx->step_container();
     79     std::vector<Tensor> args;
     80     args.reserve(ctx->num_inputs());
     81     for (int i = 0; i < ctx->num_inputs(); ++i) {
     82       args.push_back(ctx->input(i));
     83     }
     84     std::vector<Tensor>* rets = new std::vector<Tensor>;
     85     lib->Run(
     86         opts, handle_, args, rets, [ctx, done, rets](const Status& status) {
     87           if (!status.ok()) {
     88             ctx->SetStatus(status);
     89           } else if (rets->size() != ctx->num_outputs()) {
     90             ctx->SetStatus(errors::InvalidArgument(
     91                 "SymGrad expects to return ", ctx->num_outputs(),
     92                 " tensor(s), but get ", rets->size(), " tensor(s) instead."));
     93           } else {
     94             for (size_t i = 0; i < rets->size(); ++i) {
     95               ctx->set_output(i, (*rets)[i]);
     96             }
     97           }
     98           delete rets;
     99           done();
    100         });
    101   }
    102 
    103  private:
    104   FunctionLibraryRuntime::Handle handle_;
    105 
    106   TF_DISALLOW_COPY_AND_ASSIGN(SymbolicGradientOp);
    107 };
    108 
    109 REGISTER_XLA_OP(Name(kGradientOp), SymbolicGradientOp);
    110 
    111 }  // namespace
    112 }  // namespace tensorflow
    113