1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations 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
20using namespace tensorflow;  // NOLINT(build/namespaces)
21
22REGISTER_OP("ZeroOut")
23    .Attr("preserve_index: int = 0")
24    .Input("to_zero: int32")
25    .Output("zeroed: int32")
26    .SetShapeFn([](shape_inference::InferenceContext* c) {
27      c->set_output(0, c->input(0));
28      return Status::OK();
29    });
30
31class ZeroOutOp : public OpKernel {
32 public:
33  explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) {
34    // Get the index of the value to preserve
35    OP_REQUIRES_OK(context,
36                   context->GetAttr("preserve_index", &preserve_index_));
37    // Check that preserve\_index is positive
38    OP_REQUIRES(context, preserve_index_ >= 0,
39                errors::InvalidArgument("Need preserve_index >= 0, got ",
40                                        preserve_index_));
41  }
42
43  void Compute(OpKernelContext* context) override {
44    // Grab the input tensor
45    const Tensor& input_tensor = context->input(0);
46    auto input = input_tensor.flat<int32>();
47
48    // Check that preserve_index is in range
49    OP_REQUIRES(context, preserve_index_ < input.dimension(0),
50                errors::InvalidArgument("preserve_index out of range"));
51
52    // Create an output tensor
53    Tensor* output_tensor = nullptr;
54    OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(),
55                                                     &output_tensor));
56    auto output = output_tensor->template flat<int32>();
57
58    // Set all the elements of the output tensor to 0
59    const int N = input.size();
60    for (int i = 0; i < N; i++) {
61      output(i) = 0;
62    }
63
64    // Preserve the requested input value
65    output(preserve_index_) = input(preserve_index_);
66  }
67
68 private:
69  int preserve_index_;
70};
71
72REGISTER_KERNEL_BUILDER(Name("ZeroOut").Device(DEVICE_CPU), ZeroOutOp);
73