aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/toco/graph_transformations/convert_trivial_transpose_to_reshape.cc
blob: 5a36a90b3841504d6f018832777e50bac95218d7 (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
/* 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.
==============================================================================*/
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

namespace {

bool TransposeAffectsMemoryOrder(std::vector<int> perm,
                                 std::vector<int> in_shape) {
  CHECK_EQ(perm.size(), in_shape.size());
  // See what the ordering of the non-unary columns are before and after
  // transpose permutation. If the major indices stay in the same order (not
  // just the shape) then the flat buffer representation shouldn't change.
  std::vector<int> old_major_index_ordering;
  std::vector<int> new_major_index_ordering;
  for (int i = 0; i < in_shape.size(); i++) {
    if (in_shape[i] != 1) {
      old_major_index_ordering.push_back(i);
    }

    if (in_shape[perm[i]] != 1) {
      new_major_index_ordering.push_back(perm[i]);
    }
  }

  CHECK_EQ(new_major_index_ordering.size(), old_major_index_ordering.size());

  return old_major_index_ordering != new_major_index_ordering;
}

}  // namespace

bool ConvertTrivialTransposeToReshape::Run(Model* model, std::size_t op_index) {
  auto transpose_it = model->operators.begin() + op_index;
  if (transpose_it->get()->type != OperatorType::kTranspose) {
    return false;
  }
  TransposeOperator* transpose_op =
      static_cast<TransposeOperator*>(transpose_it->get());

  const auto& input_array = model->GetArray(transpose_op->inputs[0]);
  const auto& output_array = model->GetArray(transpose_op->outputs[0]);
  if (!input_array.has_shape() || !output_array.has_shape()) {
    // Yield until PropagateFixedSizes has been run on this op.
    return false;
  }
  // Note: We can assume we have error checked inputs in PropagateFixedSizes.

  // Check that the permutation has propogated.
  std::vector<int> const& perm = transpose_op->perm;
  if (perm.empty()) {
    return false;
  }

  // This transpose is trivial if non-unitary dimensions remain in the same
  // order.
  std::vector<int> const& input_dims = input_array.shape().dims();
  std::vector<int> const& output_dims = output_array.shape().dims();

  if (TransposeAffectsMemoryOrder(perm, input_dims)) {
    return false;
  }

  // This transpose is trivial. Replace it with a Reshape op.
  auto* reshape_op = new TensorFlowReshapeOperator;

  // Copy input and output
  reshape_op->inputs.push_back(transpose_op->inputs[0]);
  reshape_op->outputs = transpose_op->outputs;

  // Create a new input array for the shape input
  string perm_array_name = transpose_op->inputs[1];
  string shape_array_name = toco::AvailableArrayName(*model, perm_array_name);
  Array& shape_array = model->GetOrCreateArray(shape_array_name);
  *(shape_array.mutable_shape()->mutable_dims()) = {
      1, static_cast<int>(output_dims.size())};
  reshape_op->inputs.push_back(shape_array_name);
  shape_array.data_type = ArrayDataType::kInt32;
  auto& shape_buffer = shape_array.GetMutableBuffer<ArrayDataType::kInt32>();
  shape_buffer.data = output_dims;

  // Delete perm array if unused
  if (IsDiscardableArray(*model, perm_array_name) &&
      CountOpsWithInput(*model, perm_array_name) == 1) {
    model->EraseArray(perm_array_name);
  }

  // Replace the operator in the graph.
  const auto reshape_it = model->operators.emplace(transpose_it, reshape_op);
  transpose_it = reshape_it + 1;
  CHECK_EQ(transpose_it->get(), transpose_op);
  model->operators.erase(transpose_it);

  return true;
}

}  // namespace toco