aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/tf2xla/kernels/sequence_ops.cc
blob: bc3d0bf5dfe9e5af8e50a25e27db7148e05e0cfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// XLA-specific sequence and range Ops.

#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"

namespace tensorflow {
namespace {

template <typename T>
Status GetValue(int index, XlaOpKernelContext* ctx, T* value) {
  xla::Literal literal;
  TF_RETURN_IF_ERROR(ctx->ConstantInput(index, &literal));
  *value = literal.Get<T>({});
  return Status::OK();
}

Status GetIntValue(int index, XlaOpKernelContext* ctx, int64* value) {
  xla::Literal literal;
  TF_RETURN_IF_ERROR(ctx->ConstantInput(index, &literal));
  switch (literal.shape().element_type()) {
    case xla::S32:
      *value = literal.Get<int32>({});
      break;
    case xla::S64:
      *value = literal.Get<int64>({});
      break;
    default:
      return errors::InvalidArgument("Invalid argument type for argument",
                                     index);
  }
  return Status::OK();
}

// The type-specific part of the implementation of Range.
template <typename T>
Status CreateRangeTensor(const xla::LiteralSlice& start_literal,
                         const xla::LiteralSlice& limit_literal,
                         const xla::LiteralSlice& delta_literal,
                         Tensor* output) {
  T start = start_literal.Get<T>({});
  T limit = limit_literal.Get<T>({});
  T delta = delta_literal.Get<T>({});

  if (delta == 0) {
    return errors::InvalidArgument("Requires delta != 0: ", delta);
  }
  if (delta > 0) {
    if (start > limit) {
      return errors::InvalidArgument(
          "Requires start <= limit when delta > 0: ", start, "/", limit);
    }
  } else {
    if (start < limit) {
      return errors::InvalidArgument(
          "Requires start >= limit when delta < 0: ", start, "/", limit);
    }
  }
  int64 size =
      (std::is_integral<T>::value
           ? ((std::abs(limit - start) + std::abs(delta) - 1) / std::abs(delta))
           : std::ceil(std::abs((limit - start) / delta)));

  *output = Tensor(DataTypeToEnum<T>::v(), TensorShape({size}));
  auto flat = output->flat<T>();
  T val = start;
  for (int64 i = 0; i < size; ++i) {
    flat(i) = val;
    val += delta;
  }
  return Status::OK();
}

class RangeOp : public XlaOpKernel {
 public:
  explicit RangeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape start_in_shape = ctx->InputShape(0);
    const TensorShape limit_in_shape = ctx->InputShape(1);
    const TensorShape delta_in_shape = ctx->InputShape(2);
    OP_REQUIRES(ctx, IsLegacyScalar(start_in_shape),
                errors::InvalidArgument("start must be a scalar, not shape ",
                                        start_in_shape.DebugString()));
    OP_REQUIRES(ctx, IsLegacyScalar(limit_in_shape),
                errors::InvalidArgument("limit must be a scalar, not shape ",
                                        limit_in_shape.DebugString()));
    OP_REQUIRES(ctx, IsLegacyScalar(delta_in_shape),
                errors::InvalidArgument("delta must be a scalar, not shape ",
                                        delta_in_shape.DebugString()));
    xla::Literal start, limit, delta;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(0, &start));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &limit));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &delta));

    DataType type = input_type(0);
    Tensor output;
    Status status;
    switch (type) {
      case DT_INT32:
        status = CreateRangeTensor<int32>(start, limit, delta, &output);
        break;
      case DT_INT64:
        status = CreateRangeTensor<int64>(start, limit, delta, &output);
        break;
      case DT_FLOAT:
        status = CreateRangeTensor<float>(start, limit, delta, &output);
        break;
      case DT_DOUBLE:
        status = CreateRangeTensor<double>(start, limit, delta, &output);
        break;
      default:
        status = errors::InvalidArgument("Invalid type for Range ",
                                         DataTypeString(type));
    }
    OP_REQUIRES_OK(ctx, status);
    ctx->SetConstantOutput(0, output);
  }
};

REGISTER_XLA_OP(Name("Range")
                    .CompileTimeConstInput("start")
                    .CompileTimeConstInput("limit")
                    .CompileTimeConstInput("delta"),
                RangeOp);

class LinSpaceOp : public XlaOpKernel {
 public:
  explicit LinSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape start_in_shape = ctx->InputShape(0);
    const TensorShape stop_in_shape = ctx->InputShape(1);
    const TensorShape num_in_shape = ctx->InputShape(2);
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape),
                errors::InvalidArgument("start must be a scalar, not shape ",
                                        start_in_shape.DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(stop_in_shape),
                errors::InvalidArgument("stop must be a scalar, not shape ",
                                        stop_in_shape.DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(num_in_shape),
                errors::InvalidArgument("num must be a scalar, not shape ",
                                        num_in_shape.DebugString()));

    DataType type = ctx->input_type(0);

    int64 num;
    OP_REQUIRES_OK(ctx, GetIntValue(2, ctx, &num));
    OP_REQUIRES(ctx, num > 0,
                errors::InvalidArgument("Requires num > 0: ", num));
    Tensor out_constant(type, TensorShape({num}));

    switch (type) {
      case DT_FLOAT: {
        float start, stop;
        OP_REQUIRES_OK(ctx, GetValue(0, ctx, &start));
        OP_REQUIRES_OK(ctx, GetValue(1, ctx, &stop));
        auto flat = out_constant.flat<float>();
        if (num == 1) {
          flat(0) = start;
        } else {
          const float step = (stop - start) / (num - 1);
          for (int64 i = 0; i < num; ++i) {
            flat(i) = start + step * i;
          }
        }
        break;
      }
      case DT_DOUBLE: {
        double start, stop;
        OP_REQUIRES_OK(ctx, GetValue(0, ctx, &start));
        OP_REQUIRES_OK(ctx, GetValue(1, ctx, &stop));
        auto flat = out_constant.flat<double>();
        if (num == 1) {
          flat(0) = start;
        } else {
          const double step = (stop - start) / (num - 1);
          for (int64 i = 0; i < num; ++i) {
            flat(i) = start + step * i;
          }
        }
        break;
      }

      default:
        ctx->SetStatus(errors::InvalidArgument("Invalid argument type ",
                                               DataTypeString(type)));
        return;
    }
    ctx->SetConstantOutput(0, out_constant);
  }
};

REGISTER_XLA_OP(Name("LinSpace")
                    .CompileTimeConstInput("start")
                    .CompileTimeConstInput("stop")
                    .CompileTimeConstInput("num"),
                LinSpaceOp);

}  // namespace
}  // namespace tensorflow