Home | History | Annotate | Download | only in common_runtime
      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 #include "tensorflow/core/common_runtime/function_testlib.h"
     16 
     17 #include "tensorflow/core/common_runtime/device.h"
     18 #include "tensorflow/core/framework/common_shape_fns.h"
     19 #include "tensorflow/core/framework/node_def.pb.h"
     20 #include "tensorflow/core/framework/node_def_builder.h"
     21 #include "tensorflow/core/framework/op_kernel.h"
     22 
     23 namespace tensorflow {
     24 namespace test {
     25 namespace function {
     26 
     27 typedef FunctionDefHelper FDH;
     28 
     29 class FindDeviceOpKernel : public OpKernel {
     30  public:
     31   explicit FindDeviceOpKernel(OpKernelConstruction* ctx) : OpKernel(ctx) {}
     32   void Compute(OpKernelContext* ctx) override {
     33     Tensor* device_tensor = nullptr;
     34     OP_REQUIRES_OK(ctx, ctx->allocate_output("device_name", TensorShape{},
     35                                              &device_tensor));
     36     device_tensor->scalar<string>()() =
     37         ctx->function_library()->device()->name();
     38   }
     39 };
     40 
     41 REGISTER_KERNEL_BUILDER(Name("FindDeviceOp").Device(tensorflow::DEVICE_CPU),
     42                         FindDeviceOpKernel);
     43 REGISTER_OP("FindDeviceOp")
     44     .Output("device_name: string")
     45     .SetShapeFn(shape_inference::UnknownShape);
     46 
     47 FunctionDef FindDevice() {
     48   return FDH::Define(
     49       // Name
     50       "FindDevice",
     51       // Args
     52       {},
     53       // Return values
     54       {"device_name: string"},
     55       // Attr def
     56       {},
     57       // Nodes
     58       {{{"device_name"}, "FindDeviceOp", {}, {}}});
     59 }
     60 
     61 void BlockingOpState::AwaitState(int awaiting_state) {
     62   mutex_lock ml(mu_);
     63   while (state_ != awaiting_state) {
     64     cv_.wait(ml);
     65   }
     66 }
     67 
     68 void BlockingOpState::MoveToState(int expected_current, int next) {
     69   mutex_lock ml(mu_);
     70   CHECK_EQ(expected_current, state_);
     71   state_ = next;
     72   cv_.notify_all();
     73 }
     74 
     75 BlockingOpState* blocking_op_state = nullptr;
     76 
     77 // BlockingOp blocks on the global <blocking_op_state's> state,
     78 // and also updates it when it is unblocked and finishing computation.
     79 class BlockingOp : public OpKernel {
     80  public:
     81   explicit BlockingOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
     82   void Compute(OpKernelContext* ctx) override {
     83     blocking_op_state->MoveToState(0, 1);
     84     blocking_op_state->AwaitState(2);
     85     blocking_op_state->MoveToState(2, 3);
     86 
     87     Tensor* out = nullptr;
     88     const Tensor& in = ctx->input(0);
     89     OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in.shape(), &out));
     90     out->flat<float>() = in.flat<float>();
     91   }
     92 };
     93 REGISTER_KERNEL_BUILDER(Name("BlockingOp").Device(DEVICE_CPU), BlockingOp);
     94 REGISTER_OP("BlockingOp")
     95     .Input("x: float")
     96     .Output("y: float")
     97     .Doc("")
     98     .SetShapeFn(shape_inference::UnknownShape);
     99 
    100 FunctionDef BlockingOpFn() {
    101   return FDH::Define(
    102       // Name
    103       "BlockingOpFn",
    104       // Args
    105       {"x: float"},
    106       // Return values
    107       {"y: float"},
    108       // Attr def
    109       {},
    110       // Nodes
    111       {{{"y"}, "BlockingOp", {"x"}, {}}});
    112 }
    113 
    114 // TODO(phawkins): replace with C++ API for calling functions, when that exists.
    115 Output Call(Scope* scope, const string& op_name, const string& fn_name,
    116             gtl::ArraySlice<Input> inputs) {
    117   NodeDef def;
    118   NodeDefBuilder builder(op_name, fn_name, scope->graph()->op_registry());
    119   for (const Input& input : inputs) {
    120     builder.Input(input.node()->name(), input.index(),
    121                   input.node()->output_type(input.index()));
    122   }
    123   TF_CHECK_OK(builder.Finalize(&def));
    124   Status status;
    125   Node* n = scope->graph()->AddNode(def, &status);
    126   TF_CHECK_OK(status);
    127   TF_CHECK_OK(scope->DoShapeInference(n));
    128   for (int i = 0; i < inputs.size(); ++i) {
    129     scope->graph()->AddEdge(inputs[i].node(), inputs[i].index(), n, i);
    130   }
    131   return Output(n);
    132 }
    133 
    134 }  // namespace function
    135 }  // namespace test
    136 }  // namespace tensorflow
    137