summaryrefslogtreecommitdiff
path: root/compiler/loco/src/tensorflow.test.cpp
blob: f534aee7bba6e66916c6f374fa0a8ef70ff105df (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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
 * 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.
 */

/**
 * @brief This file includes various tests that shows how to encode TensorFlow models using loco.
 *
 * @note All the python examples below assume TensorFlow v1.13
 */
#include "loco.h"

#include <gtest/gtest.h>

#include <stdex/Memory.h>

using stdex::make_unique;

namespace
{

loco::Permutation<loco::Domain::Feature> make_NHWC_permutation(void)
{
  loco::Permutation<loco::Domain::Feature> NHWC;

  NHWC.axis(loco::FeatureAxis::Count) = 0;
  NHWC.axis(loco::FeatureAxis::Height) = 1;
  NHWC.axis(loco::FeatureAxis::Width) = 2;
  NHWC.axis(loco::FeatureAxis::Depth) = 3;

  return NHWC;
}

/**
 * @brief Create a HxWxIxO (or HxWxCxN) permutation which tf.nn.conv2d uses
 *
 * Reference: [tf.nn.conv2d](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d)
 * > Given an input tensor of shape [batch, in_height, in_width, in_channels] and a filter /
 * > kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], ...
 *
 * NOTE "HWIO" is borrowed from TensorFlow Lite Converter
 *
 * https://github.com/tensorflow/tensorflow/blob/v1.13.1/tensorflow/lite/toco/model.h#L169
 */
loco::Permutation<loco::Domain::Filter> make_HWIO_permutation(void)
{
  loco::Permutation<loco::Domain::Filter> HWIO;

  HWIO.axis(loco::FilterAxis::Height) = 0; // H
  HWIO.axis(loco::FilterAxis::Width) = 1;  // W
  HWIO.axis(loco::FilterAxis::Depth) = 2;  // I, a.k.a. C
  HWIO.axis(loco::FilterAxis::Count) = 3;  // O, a.k.a. N

  return HWIO;
}

} // nemaspace

#if 0
>>> MaxPool_Float_000 testcase

MaxPool_Float_000 test guarantees that loco is expressive enough to encode the following example.

Python:
```
import tensorflow as tf
value = tf.placeholder(dtype=tf.float32, shape=[1, 16, 16, 2], name="value")
maxpool = tf.nn.max_pool(value, [1, 3, 3, 1], [1, 1, 1, 1], 'VALID', name="maxpool")
tf.get_default_graph().as_graph_def()
```

The above code produces the following TensorFlow GraphDef:

node {
  name: "value"
  op: "Placeholder"
  attr {
    key: "dtype"
    value { type: DT_FLOAT }
  }
  attr {
    key: "shape"
    value {
      shape {
        dim { size: 1 }
        dim { size: 16 }
        dim { size: 16 }
        dim { size: 2 }
      }
    }
  }
}
node {
  name: "maxpool"
  op: "MaxPool"
  input: "Placeholder"
  attr {
    key: "T"
    value { type: DT_FLOAT }
  }
  attr {
    key: "data_format"
    value { s: "NHWC" }
  }
  attr {
    key: "ksize"
    value { list { i: 1 i: 3 i: 3 i: 1 } }
  }
  attr {
    key: "padding"
    value { s: "VALID" }
  }
  attr {
    key: "strides"
    value { list { i: 1 i: 1 i: 1 i: 1 } }
  }
}

Below test guarantees that loco is expressive enough to encode this example.
#endif
TEST(TensorFlowTest, MaxPool_Float_000)
{
  auto g = loco::make_graph();

  // The first "value" node corresponds to the following "Pull" node.
  //
  // %value = Pull(dtype: FLOAT32, shape: [1, 16, 16, 2])
  auto value = g->nodes()->create<loco::Pull>();

  value->dtype(loco::DataType::FLOAT32);
  value->shape({1, 16, 16, 2});

  // The next "maxpool" node corresponds to a sequence of the following loco nodes:
  //  - "FeatureEncode"
  //  - "MaxPool2D
  //  - "FeatureDecode"
  //
  // "maxpool.data_format" is 'NHWC' which corresponds to the following permutation
  //   Count  <-> 0
  //   Height <-> 1
  //   Width  <-> 2
  //   Depth  <-> 3
  loco::Permutation<loco::Domain::Feature> NHWC;

  NHWC.axis(loco::FeatureAxis::Count) = 0;
  NHWC.axis(loco::FeatureAxis::Height) = 1;
  NHWC.axis(loco::FeatureAxis::Width) = 2;
  NHWC.axis(loco::FeatureAxis::Depth) = 3;

  auto encoder = make_unique<loco::PermutingEncoder<loco::Domain::Feature>>();

  encoder->perm(NHWC);

  auto decoder = make_unique<loco::PermutingDecoder<loco::Domain::Feature>>();

  decoder->perm(NHWC);

  // %node_0 = FeatureEncode(%value, perm { Count = 0, Height = 1, Width = 2, Depth = 3 })
  auto node_0 = g->nodes()->create<loco::FeatureEncode>();

  node_0->input(value);
  node_0->encoder(std::move(encoder));

  // %node_1 = MaxPool(%node_0, window.H: 3, window.W: 3, stride.H: 1, stride.W : 1)
  auto node_1 = g->nodes()->create<loco::MaxPool2D>();

  node_1->ifm(node_0);

  // From "ksize" attributes
  node_1->window()->horizontal(3);
  node_1->window()->vertical(3);

  // From "strides" attributes
  node_1->stride()->horizontal(1);
  node_1->stride()->vertical(1);

  // %output = FeatureDecode(%node_1, perm { Count = 0, Height = 1, Width = 2, Depth = 3 })
  auto output = g->nodes()->create<loco::FeatureDecode>();

  output->input(node_1);
  output->decoder(std::move(decoder));

  // %push = Push(%output)
  auto push = g->nodes()->create<loco::Push>();

  push->from(output);

  //
  // Mark network-level input/output
  //
  auto input_0 = g->inputs()->create();
  loco::link(input_0, value);

  auto output_0 = g->outputs()->create();
  loco::link(output_0, push);

  // NOTE This example SHOULD BE valid.
  ASSERT_TRUE(loco::valid(g.get()));
}

#if 0
>>> Conv2D_Float_000 testcase

Conv2D_Float_000 test guarantees that loco is expressive enough to encode the following example.

Python:
```
import tensorflow as tf
inp = tf.placeholder(dtype=tf.float32, shape=[1, 16, 16, 2], name="inp")
ker = tf.constant(value=[1.0], dtype=tf.float32, shape=[7, 1, 2, 4], name="ker")
conv2d = tf.nn.conv2d(input=inp, filter=ker, strides=[1, 1, 1, 1], padding='VALID', name="conv2d")
tf.get_default_graph().as_graph_def()
```

TensorFlow GraphDef:
```
node {
  name: "inp"
  op: "Placeholder"
  attr {
    key: "dtype"
    value { type: DT_FLOAT }
  }
  attr {
    key: "shape"
    value {
      shape {
        dim { size: 1 }
        dim { size: 16 }
        dim { size: 16 }
        dim { size: 2 }
      }
    }
  }
}
node {
  name: "ker"
  op: "Const"
  attr {
    key: "dtype"
    value { type: DT_FLOAT }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_FLOAT
        tensor_shape {
          dim { size: 7 }
          dim { size: 1 }
          dim { size: 2 }
          dim { size: 4 }
        }
        float_val: 1.0
      }
    }
  }
}
node {
  name: "conv2d"
  op: "Conv2D"
  input: "inp"
  input: "ker"
  attr {
    key: "T"
    value { type: DT_FLOAT }
  }
  attr {
    key: "data_format"
    value { s: "NHWC" }
  }
  attr {
    key: "dilations"
    value { list { i: 1 i: 1 i: 1 i: 1 } }
  }
  attr {
    key: "padding"
    value { s: "VALID" }
  }
  attr {
    key: "strides"
    value { list { i: 1 i: 1 i: 1 i: 1 } }
  }
}
```
#endif
TEST(TensorFlowTest, Conv2D_Float_000)
{
  auto g = loco::make_graph();

  // The first "inp" node corresponds to "Pull"
  auto inp = g->nodes()->create<loco::Pull>();
  {
    inp->dtype(loco::DataType::FLOAT32);
    inp->shape({1, 16, 16, 2});
  }

  // The seoncd "ker" node corresponds to "ConstGen"
  auto ker = g->nodes()->create<loco::ConstGen>();
  {
    ker->dtype(loco::DataType::FLOAT32);
    // 'I' denotes IFM DEPTH, and 'O' denotes OFM DEPTH
    ker->shape({7 /*H*/, 1 /*W*/, 2 /*I*/, 3 /*O*/});
    ker->size<loco::DataType::FLOAT32>(7 * 1 * 2 * 3);
    for (uint32_t n = 0; n < 7 * 1 * 2 * 3; ++n)
    {
      // NOTE TensorFlow uses the last value to fill unspecified region
      ker->at<loco::DataType::FLOAT32>(n) = 1.0f;
    }
  }

  // The next "conv2d" node is decomposed into the following loco nodes
  //  - "FeatureEncode"
  //  - "FilterEncode"
  //  - "Conv2D"
  //  - "FeatureDecode"
  auto encoded_ifm = g->nodes()->create<loco::FeatureEncode>();
  {
    // From "conv2d.data_format" attribute
    auto encoder = make_unique<loco::PermutingEncoder<loco::Domain::Feature>>();
    encoder->perm(make_NHWC_permutation());

    encoded_ifm->input(inp);
    encoded_ifm->encoder(std::move(encoder));
  }

  auto encoded_ker = g->nodes()->create<loco::FilterEncode>();
  {
    // From "tf.nn.conv2d" specification
    auto encoder = make_unique<loco::PermutingEncoder<loco::Domain::Filter>>();
    encoder->perm(make_HWIO_permutation());

    encoded_ker->input(ker);
    encoded_ker->encoder(std::move(encoder));
  }

  auto conv2d = g->nodes()->create<loco::Conv2D>();
  {
    conv2d->ifm(encoded_ifm);
    conv2d->ker(encoded_ker);

    // From "stride" attribute
    conv2d->stride()->horizontal(1);
    conv2d->stride()->vertical(1);
  }

  // "decoded_ofm" corresponds to the output of "conv2d" node.
  auto decoded_ofm = g->nodes()->create<loco::FeatureDecode>();
  {
    // From "conv2d.data_format" attribute
    auto decoder = make_unique<loco::PermutingDecoder<loco::Domain::Feature>>();
    decoder->perm(make_NHWC_permutation());

    decoded_ofm->input(conv2d);
    decoded_ofm->decoder(std::move(decoder));
  }

  // Makr "conv2d" as a network-level output with Push
  auto push = g->nodes()->create<loco::Push>();
  {
    push->from(decoded_ofm);
  }

  //
  // Mark network-level input/output
  //
  auto input_0 = g->inputs()->create();
  loco::link(input_0, inp);

  auto output_0 = g->outputs()->create();
  loco::link(output_0, push);

  // NOTE This example SHOULD BE valid.
  ASSERT_TRUE(loco::valid(g.get()));
}