summaryrefslogtreecommitdiff
path: root/compiler/moco/support/src/TFShapeInferenceHelper.cpp
blob: 13e514a7822e37df6f9ec4d83d59c801b2f41430 (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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 "moco/Support/TFShapeInferenceHelper.h"

#include <loco/Service/ShapeInference.h>

#include <oops/InternalExn.h>

#include <cassert>

namespace
{

// TODO Use codes in loco and remove duplicate broadcast_shape() and related
/**
 * @brief Create a higher-rank TensorShape following NumPy broadcasting semantics
 *
 * HOW TO USE:
 *
 *   auto expanded_tensor_shape = expand(tensor_shape).to(N);
 */
class TensorShapeExpander
{
public:
  TensorShapeExpander(const loco::TensorShape &shape) : _shape{shape}
  {
    // DO NOTHING
  }

public:
  loco::TensorShape to(uint32_t output_rank)
  {
    auto const &input_shape = _shape;
    uint32_t const input_rank = input_shape.rank();

    assert(input_rank <= output_rank && "Cannot shrink rank");
    uint32_t const axis_shift = output_rank - input_rank;

    loco::TensorShape output_shape;

    output_shape.rank(output_rank);
    for (uint32_t axis = 0; axis < output_rank; ++axis)
    {
      output_shape.dim(axis) = (axis < axis_shift) ? 1 : input_shape.dim(axis - axis_shift);
    }

    return output_shape;
  }

private:
  const loco::TensorShape _shape;
};

/**
 * @breif  Expand shape x and y to same rank by align right and filling with 1
 */
void expand_rank(loco::TensorShape &x, loco::TensorShape &y)
{
  auto x_rank = x.rank();
  auto y_rank = y.rank();

  if (x_rank == y_rank)
    return;

  TensorShapeExpander x_exp(x);
  TensorShapeExpander y_exp(y);

  auto xy_rank = std::max(x_rank, y_rank);

  x = x_rank > y_rank ? x : x_exp.to(xy_rank);
  y = y_rank > x_rank ? y : y_exp.to(xy_rank);
}

/**
 * @breif  Returns shape of expanded dimension of input x and y having same rank
 */
loco::TensorShape expand_dimension(const loco::TensorShape &x, const loco::TensorShape &y)
{
  assert(x.rank() == y.rank());

  auto rank = x.rank();

  loco::TensorShape output_shape;

  output_shape.rank(rank);
  for (uint32_t axis = 0; axis < rank; ++axis)
  {
    assert(x.dim(axis).known() && y.dim(axis).known());

    auto x_dim = x.dim(axis).value();
    auto y_dim = y.dim(axis).value();

    // each dimension of x and y should be same or one must be 1 if different
    if (!((x_dim == y_dim) || (x_dim == 1 || y_dim == 1)))
    {
      // TODO may need to refine message
      INTERNAL_EXN("ShapeInference: Input shapes don't match");
    }

    output_shape.dim(axis) = std::max(x_dim, y_dim);
  }

  return output_shape;
}

} // namespace

namespace moco
{

loco::TensorShape broadcast_shape(const loco::TensorShape &x, const loco::TensorShape &y)
{
  auto x_match = x;
  auto y_match = y;

  expand_rank(x_match, y_match);

  auto output_shape = expand_dimension(x_match, y_match);

  return output_shape;
}

} // namespace moco

namespace moco
{

loco::NodeShape node_shape(const loco::Node *node)
{
  loco::NodeShape nodeshape; // default domain is Unknown

  if (loco::shape_known(node))
  {
    nodeshape = loco::shape_get(node);
  }

  return nodeshape;
}

bool node_shape(const loco::Node *node, loco::NodeShape &nodeshape)
{
  nodeshape = node_shape(node);
  return (nodeshape.domain() != loco::Domain::Unknown);
}

loco::TensorShape as_tensor_shape(const loco::FeatureShape &feature_shape,
                                  const TFDataLayout &data_layout)
{
  loco::TensorShape tensor_shape;

  tensor_shape.rank(4);
  if (data_layout == "NHWC")
  {
    tensor_shape.dim(0) = feature_shape.count();
    tensor_shape.dim(1) = feature_shape.height();
    tensor_shape.dim(2) = feature_shape.width();
    tensor_shape.dim(3) = feature_shape.depth();
  }
  else if (data_layout == "NCHW")
  {
    tensor_shape.dim(0) = feature_shape.count();
    tensor_shape.dim(1) = feature_shape.depth();
    tensor_shape.dim(2) = feature_shape.height();
    tensor_shape.dim(3) = feature_shape.width();
  }
  else
  {
    // TODO support for other data_layout if needed
    INTERNAL_EXN_V("ShapeInference: Unknown data_format", data_layout);
  }

  return tensor_shape;
}

loco::FeatureShape as_feature_shape(const loco::NodeShape &nodeshape,
                                    const TFDataLayout &data_layout)
{
  if (nodeshape.domain() == loco::Domain::Feature)
    return nodeshape.as<loco::FeatureShape>();

  loco::FeatureShape feature_shape;

  // only convert from tensor to feature
  if (nodeshape.domain() != loco::Domain::Tensor)
  {
    INTERNAL_EXN("ShapeInference: Invalid shape information");
  }

  loco::TensorShape tensor_shape = nodeshape.as<loco::TensorShape>();

  if (tensor_shape.rank() != 4)
  {
    INTERNAL_EXN("ShapeInference: Rank is not 4");
  }

  if (data_layout == "NHWC")
  {
    feature_shape.count() = tensor_shape.dim(0);
    feature_shape.height() = tensor_shape.dim(1);
    feature_shape.width() = tensor_shape.dim(2);
    feature_shape.depth() = tensor_shape.dim(3);
  }
  else if (data_layout == "NCHW")
  {
    feature_shape.count() = tensor_shape.dim(0);
    feature_shape.depth() = tensor_shape.dim(1);
    feature_shape.height() = tensor_shape.dim(2);
    feature_shape.width() = tensor_shape.dim(3);
  }
  else
  {
    // TODO support for other data_layout if needed
    INTERNAL_EXN_V("ShapeInference: Unknown data_format", data_layout);
  }

  return feature_shape;
}

} // namespace moco

namespace moco
{

PlaneShape make_plane_shape(const loco::FeatureShape &feature_shape)
{
  PlaneShape plane_shape;

  plane_shape.height = feature_shape.height();
  plane_shape.width = feature_shape.width();

  return plane_shape;
}

FeatureShapeUpdater update(loco::FeatureShape &feature_shape)
{
  return FeatureShapeUpdater{&feature_shape};
}

} // namespace moco

namespace
{

/**
 * @brief Class to represent TensorFlow "data_format" attr.
 */
enum class DataLayout
{
  NHWC,
  NCHW,
};

DataLayout as_data_layout(const std::string &tf_layout_str)
{
  if (tf_layout_str == "NHWC")
    return DataLayout::NHWC;
  else if (tf_layout_str == "NCHW")
    return DataLayout::NCHW;
  else
    /// @note data layout tag in TensorFlow is 'data_format'
    INTERNAL_EXN_V("ShapeInference: Unknown data_format", tf_layout_str);
}

} // namespace

namespace moco
{

loco::Stride<2> stride_of(const TFStrides &strides, const TFDataLayout &datalayout)
{
  loco::Stride<2> stride;

  auto data_layout = as_data_layout(datalayout);
  if (data_layout == DataLayout::NHWC)
  {
    stride.vertical(strides[1]);
    stride.horizontal(strides[2]);
  }
  else if (data_layout == DataLayout::NCHW)
  {
    stride.vertical(strides[2]);
    stride.horizontal(strides[3]);
  }
  else
  {
    // TODO add more datalayout supports if needed
    INTERNAL_EXN("ShapeInference: Unknown data_format");
  }

  return stride;
}

loco::Window<2> window_of(const TFKSize &ksize, const TFDataLayout &datalayout)
{
  loco::Window<2> window;

  auto data_layout = as_data_layout(datalayout);
  if (data_layout == DataLayout::NHWC)
  {
    window.vertical(ksize[1]);
    window.horizontal(ksize[2]);
  }
  else if (data_layout == DataLayout::NCHW)
  {
    window.vertical(ksize[2]);
    window.horizontal(ksize[3]);
  }
  else
  {
    // TODO add more datalayout supports if needed
    INTERNAL_EXN("ShapeInference: Unknown data_format");
  }

  return window;
}

loco::Window<2> window_of(const loco::TensorShape &shape, const TFDataLayout &datalayout)
{
  loco::Window<2> window;

  if (datalayout == "HWIO")
  {
    window.vertical(shape.dim(0).value());
    window.horizontal(shape.dim(1).value());
  }
  else if (datalayout == "HWCM")
  {
    window.vertical(shape.dim(0).value());
    window.horizontal(shape.dim(1).value());
  }
  else
  {
    // TODO add more datalayout supports if needed
    INTERNAL_EXN_V("ShapeInference: Unknown data_format", datalayout);
  }

  return window;
}

} // namespace moco