scan_ops.cc revision b89251c6300b9941d06071543e5c4974d0db1984
1/* Copyright 2017 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 <vector>
17
18#include "tensorflow/compiler/tf2xla/shape_util.h"
19#include "tensorflow/compiler/tf2xla/type_util.h"
20#include "tensorflow/compiler/tf2xla/xla_helpers.h"
21#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
22#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
23#include "tensorflow/compiler/xla/literal_util.h"
24#include "tensorflow/core/framework/op_kernel.h"
25#include "tensorflow/core/framework/partial_tensor_shape.h"
26#include "tensorflow/core/framework/register_types.h"
27#include "tensorflow/core/framework/tensor.h"
28#include "tensorflow/core/framework/tensor_types.h"
29#include "tensorflow/core/framework/types.h"
30#include "tensorflow/core/kernels/bounds_check.h"
31#include "tensorflow/core/kernels/concat_lib.h"
32#include "tensorflow/core/lib/core/status.h"
33#include "tensorflow/core/platform/types.h"
34
35namespace tensorflow {
36namespace {
37
38class ScanOp : public XlaOpKernel {
39 public:
40  ScanOp(OpKernelConstruction* ctx, bool sum) : XlaOpKernel(ctx), sum_(sum) {
41    OP_REQUIRES_OK(ctx, ctx->GetAttr("reverse", &reverse_));
42    OP_REQUIRES_OK(ctx, ctx->GetAttr("exclusive", &exclusive_));
43  }
44
45  void Compile(XlaOpKernelContext* ctx) override {
46    const TensorShape input_shape = ctx->InputShape(0);
47    const TensorShape tensor_axis_shape = ctx->InputShape(1);
48
49    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_axis_shape),
50                errors::InvalidArgument("ScanOp: axis must be a scalar, not ",
51                                        tensor_axis_shape.DebugString()));
52
53    int64 axis;
54    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &axis));
55    if (axis < 0) {
56      axis += input_shape.dims();
57    }
58    OP_REQUIRES(
59        ctx, FastBoundsCheck(axis, input_shape.dims()),
60        errors::InvalidArgument("ScanOp: Expected scan axis in the range [",
61                                -input_shape.dims(), ", ", input_shape.dims(),
62                                "), but got ", axis));
63
64    DataType dtype = ctx->input_type(0);
65
66    if (input_shape.num_elements() == 0) {
67      // Exit early if there is nothing to compute.
68      ctx->SetOutput(0, ctx->Input(0));
69      return;
70    }
71
72    xla::ComputationBuilder* builder = ctx->builder();
73
74    std::vector<int64> window_strides(input_shape.dims(), 1);
75    std::vector<int64> window_dims(input_shape.dims(), 1);
76    window_dims[axis] = input_shape.dim_size(axis);
77
78    std::vector<std::pair<int64, int64>> padding(input_shape.dims(), {0, 0});
79    padding[axis].first = input_shape.dim_size(axis) - 1;
80    // In exclusive mode, add an extra padding element so there is a complete
81    // window of padding before the data starts.
82    if (exclusive_) {
83      ++padding[axis].first;
84    }
85    if (reverse_) {
86      std::swap(padding[axis].first, padding[axis].second);
87    }
88
89    xla::ComputationDataHandle input = ctx->Input(0);
90    xla::ComputationDataHandle init;
91    const xla::Computation* reducer;
92    if (sum_) {
93      init = XlaHelpers::Zero(builder, dtype);
94      reducer = ctx->GetOrCreateAdd(dtype);
95    } else {
96      init = XlaHelpers::One(builder, dtype);
97      reducer = ctx->GetOrCreateMul(dtype);
98    }
99    auto output = builder->ReduceWindowWithGeneralPadding(
100        ctx->Input(0), init, *reducer, window_dims, window_strides, padding);
101
102    // In exclusive mode, we have computed an extra element containing the sum
103    // of all the input elements. Slice off this extra "last" element.
104    if (exclusive_) {
105      if (reverse_) {
106        output = builder->SliceInDim(output, 1, input_shape.dim_size(axis) + 1,
107                                     1, axis);
108
109      } else {
110        output =
111            builder->SliceInDim(output, 0, input_shape.dim_size(axis), 1, axis);
112      }
113    }
114    ctx->SetOutput(0, output);
115  }
116
117 private:
118  const bool sum_;  // True=cumulative sum. False=cumulative product.
119  bool reverse_;
120  bool exclusive_;
121};
122
123class CumsumOp : public ScanOp {
124 public:
125  explicit CumsumOp(OpKernelConstruction* ctx) : ScanOp(ctx, /*sum=*/true) {}
126};
127// TODO(phawkins): implement non-float windowed reductions in XLA and remove the
128// type constraint.
129REGISTER_XLA_OP(Name("Cumsum").TypeConstraint("T", DT_FLOAT), CumsumOp);
130
131class CumprodOp : public ScanOp {
132 public:
133  explicit CumprodOp(OpKernelConstruction* ctx) : ScanOp(ctx, /*sum=*/false) {}
134};
135// TODO(phawkins): implement non-float windowed reductions in XLA and remove the
136// type constraint.
137REGISTER_XLA_OP(Name("Cumprod").TypeConstraint("T", DT_FLOAT), CumprodOp);
138
139}  // anonymous namespace
140}  // namespace tensorflow
141