aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/toco/graph_transformations/resolve_multiply_by_zero.cc
blob: ac94f453213068e33a7abe3de1d47a774245194e (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
/* 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 <iterator>
#include <memory>
#include <string>
#include <unordered_map>
#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"

namespace toco {

namespace {

template <typename T>
bool AreAllBufferElementsZero(const std::vector<T>& buffer_data) {
  for (auto x : buffer_data) {
    if (x != 0) {
      return false;
    }
  }
  return true;
}

template <ArrayDataType Type>
void FillArrayWithZeros(Array* array) {
  CHECK(array->data_type == Type);
  std::vector<DataType<Type>>& data = array->GetMutableBuffer<Type>().data;
  data.resize(RequiredBufferSizeForShape(array->shape()));
  for (size_t i = 0; i < data.size(); i++) {
    data[i] = 0;
  }
}

}  // namespace

// Removes a multiplication by array of constant zeros by making the output
// array an array of constant zeros and removing the input arrays if they are no
// longer needed.
::tensorflow::Status ResolveMultiplyByZero::Run(Model* model,
                                                std::size_t op_index,
                                                bool* modified) {
  *modified = false;
  const auto mul_it = model->operators.begin() + op_index;
  auto* mul_op = mul_it->get();
  if (mul_op->type != OperatorType::kMul) {
    return ::tensorflow::Status::OK();
  }
  const auto& output_array_name = mul_op->outputs[0];
  auto& output_array = model->GetArray(output_array_name);

  if (!IsDiscardableArray(*model, output_array_name)) {
    return ::tensorflow::Status::OK();
  }

  if (output_array.data_type == ArrayDataType::kNone) {
    // Yield until the output type has been set by PropagateArrayDataTypes
    return ::tensorflow::Status::OK();
  }

  // Yield if the output shape is not known yet.
  if (!output_array.has_shape()) {
    return ::tensorflow::Status::OK();
  }

  // This transformation only handles the case where one operand is all 0's and
  // the other is non-constant. Other cases are handled by constant propagation
  // or the trivial binary removal pass.
  const bool is_input_constant[2] = {
      IsConstantParameterArray(*model, mul_op->inputs[0]),
      IsConstantParameterArray(*model, mul_op->inputs[1]),
  };
  if (!is_input_constant[0] && !is_input_constant[1]) {
    // Neither input is constant, so nothing we can resolve here.
    return ::tensorflow::Status::OK();
  }
  if (is_input_constant[0] && is_input_constant[1]) {
    // Both inputs are constants. That's a job for constants propagation, not
    // for us to handle here.
    return ::tensorflow::Status::OK();
  }
  const int index_of_constant_input = is_input_constant[0] ? 0 : 1;
  const int index_of_variable_input = is_input_constant[0] ? 1 : 0;
  CHECK(is_input_constant[index_of_constant_input]);
  CHECK(!is_input_constant[index_of_variable_input]);

  const auto& constant_input_array =
      model->GetArray(mul_op->inputs[index_of_constant_input]);

  CHECK(constant_input_array.data_type == output_array.data_type);
  switch (output_array.data_type) {
    case ArrayDataType::kFloat: {
      const auto& constant_input_data =
          constant_input_array.GetBuffer<ArrayDataType::kFloat>().data;
      if (!AreAllBufferElementsZero<DataType<ArrayDataType::kFloat>>(
              constant_input_data)) {
        return ::tensorflow::Status::OK();
      }
      FillArrayWithZeros<ArrayDataType::kFloat>(&output_array);
    } break;
    case ArrayDataType::kUint8: {
      const auto& constant_input_data =
          constant_input_array.GetBuffer<ArrayDataType::kUint8>().data;
      if (!AreAllBufferElementsZero<DataType<ArrayDataType::kUint8>>(
              constant_input_data)) {
        return ::tensorflow::Status::OK();
      }
      FillArrayWithZeros<ArrayDataType::kUint8>(&output_array);
    } break;
    case ArrayDataType::kInt32: {
      const auto& constant_input_data =
          constant_input_array.GetBuffer<ArrayDataType::kInt32>().data;
      if (!AreAllBufferElementsZero<DataType<ArrayDataType::kInt32>>(
              constant_input_data)) {
        return ::tensorflow::Status::OK();
      }
      FillArrayWithZeros<ArrayDataType::kInt32>(&output_array);
    } break;
    case ArrayDataType::kInt64: {
      const auto& constant_input_data =
          constant_input_array.GetBuffer<ArrayDataType::kInt64>().data;
      if (!AreAllBufferElementsZero<DataType<ArrayDataType::kInt64>>(
              constant_input_data)) {
        return ::tensorflow::Status::OK();
      }
      FillArrayWithZeros<ArrayDataType::kInt64>(&output_array);
    } break;
    default:
      AddMessageF(
          "Cannot resolve multiply by 0 because of unsupported data type\n");
      return ::tensorflow::Status::OK();
  }

  // Erase input arrays to the multiply if no longer used
  DeleteArrayIfUsedOnce(mul_op->inputs[0], model);
  DeleteArrayIfUsedOnce(mul_op->inputs[1], model);

  // Erase the multiply operator.
  model->operators.erase(mul_it);

  *modified = true;
  return ::tensorflow::Status::OK();
}

}  // namespace toco