aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/tf2xla/kernels/transpose_op.cc
blob: 6b303b31d43ce2249a87f25723caf34f84c8387d (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
/* 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 Transpose Op. This is very different to the Eigen
// version in third_party/tensorflow because XLA's reshape neatly
// handles all transposes, while Eigen needs a restricted DoTranspose
// helper.

#include "tensorflow/core/kernels/transpose_op.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#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/client/xla_builder.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/bounds_check.h"

namespace tensorflow {
namespace {

class TransposeOp : public XlaOpKernel {
 public:
  explicit TransposeOp(OpKernelConstruction* ctx, bool conjugate = false)
      : XlaOpKernel(ctx), conjugate_(conjugate) {}

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape input_shape = ctx->InputShape(0);
    const TensorShape perm_tensor_shape = ctx->InputShape(1);

    // Preliminary validation of sizes.
    OP_REQUIRES(ctx, TensorShapeUtils::IsVector(perm_tensor_shape),
                errors::InvalidArgument("perm must be a vector, not ",
                                        perm_tensor_shape.DebugString()));

    const int dims = input_shape.dims();
    OP_REQUIRES(ctx, dims == perm_tensor_shape.num_elements(),
                errors::InvalidArgument("transpose expects a vector of size ",
                                        input_shape.dims(),
                                        ". But input(1) is a vector of size ",
                                        perm_tensor_shape.num_elements()));

    xla::Literal literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInputReshaped(1, {dims}, &literal));

    std::vector<int32> perm(dims);
    std::copy(literal.data<int32>().begin(), literal.data<int32>().end(),
              perm.begin());

    std::vector<int64> transposed_order;
    // Check whether permutation is a permutation of integers of [0 .. dims).
    absl::InlinedVector<bool, 8> bits(dims);
    bool is_identity = true;
    for (int i = 0; i < dims; ++i) {
      const int32 d = perm[i];
      OP_REQUIRES(
          ctx, 0 <= d && d < dims,
          errors::InvalidArgument(d, " is out of range [0 .. ", dims, ")"));
      bits[d] = true;
      transposed_order.push_back(d);
      if (d != i) {
        is_identity = false;
      }
    }
    for (int i = 0; i < dims; ++i) {
      OP_REQUIRES(
          ctx, bits[i],
          errors::InvalidArgument(i, " is missing from 'perm' argument."));
    }

    xla::XlaOp transposed;
    // 0-D, 1-D, and identity transposes do nothing.
    if (dims <= 1 || is_identity) {
      transposed = ctx->Input(0);
    } else {
      transposed = xla::Transpose(ctx->Input(0), transposed_order);
    }

    // Conjugate the transposed result if this is ConjugateTransposeOp.
    if (conjugate_) {
      ctx->SetOutput(0, xla::Conj(transposed));
    } else {
      ctx->SetOutput(0, transposed);
    }
  }

 private:
  const bool conjugate_;
};

class ConjugateTransposeOp : public TransposeOp {
 public:
  explicit ConjugateTransposeOp(OpKernelConstruction* ctx)
      : TransposeOp(ctx, /*conjugate=*/true) {}
};

REGISTER_XLA_OP(Name("Transpose").CompileTimeConstInput("perm"), TransposeOp);

REGISTER_XLA_OP(Name("ConjugateTranspose").CompileTimeConstInput("perm"),
                ConjugateTransposeOp);

// InvertPermutation frequently forms part of the gradient of Transpose.
//
// inv = InvertPermutationOp(T<int32> p) takes a permutation of
// integers 0, 1, ..., n - 1 and returns the inverted
// permutation of p. I.e., inv[p[i]] == i, for i in [0 .. n).
//
// REQUIRES: input is a vector of int32.
// REQUIRES: input is a permutation of 0, 1, ..., n-1.

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

  void Compile(XlaOpKernelContext* ctx) override {
    OP_REQUIRES(ctx,
                FastBoundsCheck(ctx->InputShape(0).num_elements(),
                                std::numeric_limits<int32>::max()),
                errors::InvalidArgument("permutation of nonnegative int32s "
                                        "must have <= int32 max elements"));

    std::vector<int64> perm;
    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(0, &perm));

    int size = perm.size();

    std::vector<int32> output(size);
    std::fill_n(output.data(), size, -1);
    for (int i = 0; i < size; ++i) {
      const int64 d = perm[i];
      OP_REQUIRES(ctx, FastBoundsCheck(d, size),
                  errors::InvalidArgument(d, " is not between 0 and ", size));
      OP_REQUIRES(ctx, output[d] == -1,
                  errors::InvalidArgument(d, " is duplicated in the input."));
      output[d] = i;
    }

    ctx->SetOutput(0, xla::ConstantR1<int32>(ctx->builder(), output));
  }
};

REGISTER_XLA_OP(Name("InvertPermutation")
                    .TypeConstraint("T", DT_INT32)
                    .CompileTimeConstInput("x"),
                InvertPermutationOp);

}  // namespace
}  // namespace tensorflow