Home | History | Annotate | Download | only in adding_an_op
      1 /* Copyright 2015 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/framework/op.h"
     17 #include "tensorflow/core/framework/op_kernel.h"
     18 #include "tensorflow/core/framework/shape_inference.h"
     19 
     20 using namespace tensorflow;  // NOLINT(build/namespaces)
     21 
     22 REGISTER_OP("ZeroOut")
     23     .Input("to_zero: int32")
     24     .Output("zeroed: int32")
     25     .SetShapeFn([](shape_inference::InferenceContext* c) {
     26       c->set_output(0, c->input(0));
     27       return Status::OK();
     28     })
     29     .Doc(R"doc(
     30 Zeros out all but the first value of a Tensor.
     31 
     32 zeroed: A Tensor whose first value is identical to `to_zero`, and 0
     33   otherwise.
     34 )doc");
     35 
     36 class ZeroOutOp : public OpKernel {
     37  public:
     38   explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) {}
     39 
     40   void Compute(OpKernelContext* context) override {
     41     // Grab the input tensor
     42     const Tensor& input_tensor = context->input(0);
     43     auto input = input_tensor.flat<int32>();
     44 
     45     // Create an output tensor
     46     Tensor* output_tensor = nullptr;
     47     OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
     48                                                      &output_tensor));
     49     auto output = output_tensor->template flat<int32>();
     50 
     51     // Set all but the first element of the output tensor to 0.
     52     const int N = input.size();
     53     for (int i = 1; i < N; i++) {
     54       output(i) = 0;
     55     }
     56 
     57     // Preserve the first input value.
     58     if (N > 0) output(0) = input(0);
     59   }
     60 };
     61 
     62 REGISTER_KERNEL_BUILDER(Name("ZeroOut").Device(DEVICE_CPU), ZeroOutOp);
     63