summaryrefslogtreecommitdiff
path: root/compiler/mir2loco/src/mir2loco.cpp
blob: fc1f6933b25b09f33237710fc22cdf524451f702 (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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*
 * 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 "mir2loco.h"

#include "mir/ops/AddOp.h"
#include "mir/ops/AvgPool2DOp.h"
#include "mir/ops/ConcatOp.h"
#include "mir/ops/ConstantOp.h"
#include "mir/ops/Conv2DOp.h"
#include "mir/ops/Deconv2DOp.h"
#include "mir/ops/DepthwiseConv2DOp.h"
#include "mir/ops/DivOp.h"
#include "mir/ops/FullyConnectedOp.h"
#include "mir/ops/MaxPool2DOp.h"
#include "mir/ops/MulOp.h"
#include "mir/ops/ReluOp.h"
#include "mir/ops/ReshapeOp.h"
#include "mir/ops/SoftmaxOp.h"
#include "mir/ops/SubOp.h"
#include "mir/ops/TransposeOp.h"

#include "mir/ShapeRange.h"

#include <cassert>
#include <cstring>
#include <stdex/Memory.h>

namespace mir2loco
{
namespace
{
template <class NodeType> void setupShape(const mir::Shape &shape, NodeType *node)
{
  node->rank(shape.rank());
  for (int32_t i = 0; i < shape.rank(); i++)
  {
    node->dim(i) = static_cast<uint32_t>(shape.dim(i));
  }
}

std::unique_ptr<loco::TensorShape> make_tensor_shape(const mir::Shape &shape)
{
  auto res = stdex::make_unique<loco::TensorShape>();
  setupShape(shape, res.get());
  return std::move(res);
}

void setupPad(const std::vector<std::int32_t> &padding_before,
              const std::vector<std::int32_t> &padding_after, loco::Padding2D *pad)
{
  assert(padding_before.size() == 2 && padding_after.size() == 2);
  pad->top(padding_before[0]);
  pad->left(padding_before[1]);
  pad->bottom(padding_after[0]);
  pad->right(padding_after[1]);
}

void setupWindow(const std::vector<std::int32_t> &window_size, loco::Window<2> *window)
{
  assert(window_size.size() == 2);
  window->vertical(window_size[0]);
  window->horizontal(window_size[1]);
}

void setupStride(const std::vector<std::int32_t> &strides, loco::Stride<2> *stride)
{
  assert(strides.size() == 2);
  stride->vertical(strides[0]);
  stride->horizontal(strides[1]);
}

loco::Permutation<loco::Domain::Feature> createFeaturePermutation(mir::DataFormat format)
{
  loco::Permutation<loco::Domain::Feature> perm;
  if (format == mir::DataFormat::NHWC)
  {
    perm.axis(loco::FeatureAxis::Count) = 0;
    perm.axis(loco::FeatureAxis::Height) = 1;
    perm.axis(loco::FeatureAxis::Width) = 2;
    perm.axis(loco::FeatureAxis::Depth) = 3;
  }
  else
  {
    assert(format == mir::DataFormat::NCHW);
    perm.axis(loco::FeatureAxis::Count) = 0;
    perm.axis(loco::FeatureAxis::Depth) = 1;
    perm.axis(loco::FeatureAxis::Height) = 2;
    perm.axis(loco::FeatureAxis::Width) = 3;
  }
  return perm;
}

std::unique_ptr<loco::FeatureEncoder> createFeatureEncoder(mir::DataFormat data_format)
{
  auto perm = createFeaturePermutation(data_format);
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::Feature>>(perm);
}

std::unique_ptr<loco::FeatureDecoder> createFeatureDecoder(mir::DataFormat data_format)
{
  auto perm = createFeaturePermutation(data_format);
  return stdex::make_unique<loco::PermutingDecoder<loco::Domain::Feature>>(perm);
}

std::unique_ptr<loco::FilterEncoder> createOHWIFilterEncoder()
{
  loco::Permutation<loco::Domain::Filter> perm;
  perm.axis(loco::FilterAxis::Count) = 0;
  perm.axis(loco::FilterAxis::Height) = 1;
  perm.axis(loco::FilterAxis::Width) = 2;
  perm.axis(loco::FilterAxis::Depth) = 3;
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::Filter>>(perm);
}

std::unique_ptr<loco::FilterEncoder> createHWOIFilterEncoder()
{
  loco::Permutation<loco::Domain::Filter> perm;
  perm.axis(loco::FilterAxis::Height) = 0;
  perm.axis(loco::FilterAxis::Width) = 1;
  perm.axis(loco::FilterAxis::Count) = 2;
  perm.axis(loco::FilterAxis::Depth) = 3;
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::Filter>>(perm);
}

std::unique_ptr<loco::DepthwiseFilterEncoder> createHWIMDepthwiseFilterEncoder()
{
  loco::Permutation<loco::Domain::DepthwiseFilter> perm;
  perm.axis(loco::DepthwiseFilterAxis::Height) = 0;
  perm.axis(loco::DepthwiseFilterAxis::Width) = 1;
  perm.axis(loco::DepthwiseFilterAxis::Depth) = 2;
  perm.axis(loco::DepthwiseFilterAxis::Multiplier) = 3;
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::DepthwiseFilter>>(perm);
}

std::unique_ptr<loco::DepthwiseFilterEncoder> createIHWMDepthwiseFilterEncoder()
{
  loco::Permutation<loco::Domain::DepthwiseFilter> perm;
  perm.axis(loco::DepthwiseFilterAxis::Depth) = 0;
  perm.axis(loco::DepthwiseFilterAxis::Height) = 1;
  perm.axis(loco::DepthwiseFilterAxis::Width) = 2;
  perm.axis(loco::DepthwiseFilterAxis::Multiplier) = 3;
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::DepthwiseFilter>>(perm);
}

std::unique_ptr<loco::MatrixEncoder> createHWMatrixEncoder()
{
  loco::Permutation<loco::Domain::Matrix> perm;
  perm.axis(loco::MatrixAxis::Height) = 0;
  perm.axis(loco::MatrixAxis::Width) = 1;
  return stdex::make_unique<loco::PermutingEncoder<loco::Domain::Matrix>>(perm);
}

std::unique_ptr<loco::MatrixDecoder> createHWMatrixDecoder()
{
  loco::Permutation<loco::Domain::Matrix> perm;
  perm.axis(loco::MatrixAxis::Height) = 0;
  perm.axis(loco::MatrixAxis::Width) = 1;
  return stdex::make_unique<loco::PermutingDecoder<loco::Domain::Matrix>>(perm);
}

loco::DataType convertDataType(mir::DataType data_type)
{
  switch (data_type)
  {
    case mir::DataType::UNKNOWN:
      return loco::DataType::Unknown;
    case mir::DataType::FLOAT32:
      return loco::DataType::FLOAT32;
    case mir::DataType::FLOAT64:
      return loco::DataType::FLOAT64;
    case mir::DataType::INT32:
      return loco::DataType::S32;
    case mir::DataType::INT64:
      return loco::DataType::S64;
    default:
      break;
  }
  throw std::runtime_error("Unsupported data type");
}

loco::Node *createBroadcastIfNeeded(loco::Node *node, const mir::Shape &shape,
                                    const mir::Shape &out_shape)
{
  auto graph = node->graph();

  if (shape == out_shape)
    return node; // not needed

  int32_t out_rank = out_shape.rank();
  int32_t rank_diff = out_rank - shape.rank();
  // Create Broadcast
  auto *broadcast = graph->nodes()->create<loco::TensorBroadcast>();
  // Create Reshape for equal ranks
  if (shape.rank() != out_rank)
  {
    auto *reshape = graph->nodes()->create<loco::FixedReshape>();
    reshape->input(node);
    reshape->rank(out_rank);
    broadcast->input(reshape);
    // Set reshape dims
    for (int32_t dim = 0; dim < out_rank; dim++)
    {
      if (dim < rank_diff)
        reshape->dim(dim) = 1;
      else
        reshape->dim(dim) = shape.dim(dim - rank_diff);
    }
  }
  else
  {
    broadcast->input(node);
  }
  // Flag if no one dim isn't equal
  bool compatible_shapes = true;
  for (int32_t dim = 0; dim < out_rank; dim++)
  {
    // Set broadcast mapping
    if (dim < rank_diff || (shape.dim(dim - rank_diff) == 1 && out_shape.dim(dim) != 1))
      broadcast->mapping()->dim(dim) = out_shape.dim(dim);
    // Check compatibility
    if (dim >= rank_diff && shape.dim(dim - rank_diff) != 1 &&
        shape.dim(dim - rank_diff) != out_shape.dim(dim))
      compatible_shapes = false;
  }
  // Check compatibility
  if (!compatible_shapes)
    throw std::runtime_error("Not compatible shapes for broadcasting!");

  return broadcast;
}

template <typename NodeType>
NodeType *createEltwiseBinary(const mir::ops::BinaryElementwiseOp &op, loco::Node *lhs,
                              loco::Node *rhs)
{
  auto graph = lhs->graph();

  const auto &lhs_shape = op.getInput(0)->getShape();
  const auto &rhs_shape = op.getInput(1)->getShape();
  const auto &out_shape = op.getOutputShape(0);
  // Create Broadcast if it's needed
  auto lhs_node = createBroadcastIfNeeded(lhs, lhs_shape, out_shape);
  auto rhs_node = createBroadcastIfNeeded(rhs, rhs_shape, out_shape);
  // Create Node
  auto result = graph->nodes()->create<NodeType>();
  result->lhs(lhs_node);
  result->rhs(rhs_node);
  return result;
}
} // namespace

void Transformer::visit(mir::ops::AddOp &op)
{
  // Get Input
  auto lhs = _mir2loco_map.at(op.getInput(0));
  auto rhs = _mir2loco_map.at(op.getInput(1));
  auto result = createEltwiseBinary<loco::EltwiseAdd>(op, lhs, rhs);
  // Not set Shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), result);
}

void Transformer::visit(mir::ops::AvgPool2DOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));

  auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
  encoded_input->input(input);
  encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

  auto *avg_pool_node = _loco_graph->nodes()->create<loco::AvgPool2D>();
  avg_pool_node->ifm(encoded_input);
  avg_pool_node->convention(op.getIncludePad() ? loco::AvgPool2D::Convention::Full
                                               : loco::AvgPool2D::Convention::Valid);
  setupWindow(op.getWindowSize(), avg_pool_node->window());
  setupStride(op.getStrides(), avg_pool_node->stride());
  setupPad(op.getPaddingBefore(), op.getPaddingAfter(), avg_pool_node->pad());

  auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
  output->input(avg_pool_node);
  output->decoder(createFeatureDecoder(op.getDataFormat()));

  _mir2loco_map.emplace(op.getOutput(0), output);
}

void Transformer::visit(mir::ops::ConcatOp &op)
{
  if (op.getNumInputs() < 2)
    throw std::runtime_error("Not enough tensors for concatenation!");

  loco::Node *last_concat = nullptr;

  for (std::size_t i = 1; i < op.getNumInputs(); i++)
  {
    loco::Node *lhs = last_concat;
    if (lhs == nullptr)
    {
      mir::Operation::Output *mir_lhs = op.getInput(i - 1);
      lhs = _mir2loco_map.at(mir_lhs);
    }
    mir::Operation::Output *mir_rhs = op.getInput(i);
    loco::Node *rhs = _mir2loco_map.at(mir_rhs);
    // Create TensorConcat
    auto concat_node = _loco_graph->nodes()->create<loco::TensorConcat>();
    // Set inputs
    concat_node->lhs(lhs);
    concat_node->rhs(rhs);
    // Set axis
    concat_node->axis(op.getAxis());
    // Set last concat
    last_concat = concat_node;
  }
  // Not set Shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), last_concat);
}

void Transformer::visit(mir::ops::ConstantOp &op)
{
  auto const_node = _loco_graph->nodes()->create<loco::ConstGen>();
  // Not set Input
  // Set Shape
  const auto &out_shape = op.getOutputShape(0);
  setupShape(out_shape, const_node);
  // Copy value
  const auto &value = op.getValue();
  const_node->dtype(convertDataType(value.getElementType()));
  // TODO Support other data types
  switch (const_node->dtype())
  {
    case loco::DataType::FLOAT32:
    {
      const_node->size<loco::DataType::FLOAT32>(out_shape.numElements());
      float &const_float = const_node->at<loco::DataType::FLOAT32>(0);
      char *loco_ptr = reinterpret_cast<char *>(&const_float);
      char *mir_ptr = value.at(mir::Index(out_shape.rank()));
      std::memcpy(loco_ptr, mir_ptr, out_shape.numElements() * sizeof(float));
      break;
    }
    case loco::DataType::FLOAT64:
    {
      // TODO Change that when loco support other DataTypeImpl
      const_node->dtype(loco::DataType::FLOAT32);
      const_node->size<loco::DataType::FLOAT32>(out_shape.numElements());
      float &const_float = const_node->at<loco::DataType::FLOAT32>(0);
      char *mir_ptr = value.at(mir::Index(out_shape.rank()));
      double *mir_double = reinterpret_cast<double *>(mir_ptr);
      float *loco_float = &const_float;
      for (const mir::Index &idx : mir::ShapeRange(out_shape))
      {
        *loco_float = static_cast<float>(*mir_double);
        loco_float++;
        mir_double++;
      }
      break;
    }
    case loco::DataType::S32:
    {
      const_node->size<loco::DataType::S32>(out_shape.numElements());
      int32_t &const_int32 = const_node->at<loco::DataType::S32>(0);
      char *loco_ptr = reinterpret_cast<char *>(&const_int32);
      char *mir_ptr = value.at(mir::Index(out_shape.rank()));
      std::memcpy(loco_ptr, mir_ptr, out_shape.numElements() * sizeof(int32_t));
      break;
    }
    case loco::DataType::S64:
    {
      // TODO Change that when loco support other DataTypeImpl
      const_node->dtype(loco::DataType::S32);
      const_node->size<loco::DataType::S32>(out_shape.numElements());
      int32_t &const_int32 = const_node->at<loco::DataType::S32>(0);
      char *mir_ptr = value.at(mir::Index(out_shape.rank()));
      int64_t *mir_int64 = reinterpret_cast<int64_t *>(mir_ptr);
      int32_t *loco_int32 = &const_int32;
      for (const mir::Index &idx : mir::ShapeRange(out_shape))
      {
        *loco_int32 = static_cast<float>(*mir_int64);
        loco_int32++;
        mir_int64++;
      }
      break;
    }
    default:
      std::runtime_error("Unsupported data type");
  }
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), const_node);
}

void Transformer::visit(mir::ops::Conv2DOp &op)
{
  mir::Operation::Output *mir_input = op.getInput(0);
  mir::Operation::Output *mir_filter = op.getInput(1);

  loco::Node *input = _mir2loco_map.at(mir_input);
  loco::Node *filter = _mir2loco_map.at(mir_filter);

  // loco does not have grouped Conv2D operation. Try to translate into something else.
  if (op.getNumGroups() != 1)
  {
    const std::int32_t group_size = mir_filter->getShape().dim(3);
    const std::int32_t num_in_channels = group_size * op.getNumGroups();
    const std::int32_t num_out_channels = mir_filter->getShape().dim(0);

    // If the size of the group is 1, translate the operation into DepthwiseConv2D. Limit ourselves
    // with the case of 'multiplier' == 1 for now.
    if (group_size == 1 && (num_out_channels == num_in_channels))
    {
      // [O, H, W, I / group] == [I, H, W, M].
      auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
      encoded_input->input(input);
      encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

      auto *encoded_filter = _loco_graph->nodes()->create<loco::DepthwiseFilterEncode>();
      encoded_filter->input(filter);
      encoded_filter->encoder(createIHWMDepthwiseFilterEncoder());

      auto *dw_conv2d_node = _loco_graph->nodes()->create<loco::DepthwiseConv2D>();
      dw_conv2d_node->ifm(encoded_input);
      dw_conv2d_node->ker(encoded_filter);
      setupStride(op.getStrides(), dw_conv2d_node->stride());
      setupPad(op.getPaddingBefore(), op.getPaddingAfter(), dw_conv2d_node->pad());

      auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
      output->input(dw_conv2d_node);
      output->decoder(createFeatureDecoder(op.getDataFormat()));

      _mir2loco_map.emplace(op.getOutput(0), output);
    }
    else
    {
      // There are few things we can do here:
      // 1) If group_size == 1, reshape the kernel [O, H, W, I / group] == [I * M, H, W, 1] ->
      //    [I, M, H, W] and use DepthwiseConv2D.
      // 2) Split the operation into smaller Conv2Ds.
      // 3) Replicate the filter along 'O' axis 'num_groups' times, zero out some elements, and use
      //    ordinary Conv2D.
      throw std::runtime_error("Grouped Conv2D operation is not fully supported.");
    }
  }
  else
  {
    auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
    encoded_input->input(input);
    encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

    auto *encoded_filter = _loco_graph->nodes()->create<loco::FilterEncode>();
    encoded_filter->input(filter);
    encoded_filter->encoder(createOHWIFilterEncoder());

    auto *conv2d_node = _loco_graph->nodes()->create<loco::Conv2D>();
    conv2d_node->ifm(encoded_input);
    conv2d_node->ker(encoded_filter);
    setupStride(op.getStrides(), conv2d_node->stride());
    setupPad(op.getPaddingBefore(), op.getPaddingAfter(), conv2d_node->pad());

    auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
    output->input(conv2d_node);
    output->decoder(createFeatureDecoder(op.getDataFormat()));

    _mir2loco_map.emplace(op.getOutput(0), output);
  }
}

void Transformer::visit(mir::ops::DeConv2DOp &op)
{
  mir::Operation::Output *mir_input = op.getInput(0);
  mir::Operation::Output *mir_filter = op.getInput(1);

  loco::Node *input = _mir2loco_map.at(mir_input);
  loco::Node *filter = _mir2loco_map.at(mir_filter);

  auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
  encoded_input->input(input);
  encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

  auto *encoded_filter = _loco_graph->nodes()->create<loco::FilterEncode>();
  encoded_filter->input(filter);
  encoded_filter->encoder(createHWOIFilterEncoder());

  auto *tr_conv2d_node = _loco_graph->nodes()->create<loco::TransposedConv2D>();
  tr_conv2d_node->ifm(encoded_input);
  tr_conv2d_node->ker(encoded_filter);
  setupStride(op.getStrides(), tr_conv2d_node->stride());
  if (op.getPaddingType() == mir::ops::PaddingType::Explicit)
    setupPad(op.getPaddingBefore(), op.getPaddingAfter(), tr_conv2d_node->pad());
  else
    throw std::runtime_error("Not supported non explicit paddings on loco!");

  auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
  output->input(tr_conv2d_node);
  output->decoder(createFeatureDecoder(op.getDataFormat()));

  _mir2loco_map.emplace(op.getOutput(0), output);
}

void Transformer::visit(mir::ops::DepthwiseConv2DOp &op)
{
  mir::Operation::Output *mir_input = op.getInput(0);
  mir::Operation::Output *mir_filter = op.getInput(1);

  loco::Node *input = _mir2loco_map.at(mir_input);
  loco::Node *filter = _mir2loco_map.at(mir_filter);

  auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
  encoded_input->input(input);
  encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

  auto *encoded_filter = _loco_graph->nodes()->create<loco::DepthwiseFilterEncode>();
  encoded_filter->input(filter);
  encoded_filter->encoder(createHWIMDepthwiseFilterEncoder());

  auto *dw_conv2d_node = _loco_graph->nodes()->create<loco::DepthwiseConv2D>();
  dw_conv2d_node->ifm(encoded_input);
  dw_conv2d_node->ker(encoded_filter);
  setupStride(op.getStrides(), dw_conv2d_node->stride());
  setupPad(op.getPaddingBefore(), op.getPaddingAfter(), dw_conv2d_node->pad());

  auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
  output->input(dw_conv2d_node);
  output->decoder(createFeatureDecoder(op.getDataFormat()));

  _mir2loco_map.emplace(op.getOutput(0), output);
}

void Transformer::visit(mir::ops::DivOp &op)
{
  // Get Input
  loco::Node *lhs = _mir2loco_map.at(op.getInput(0));
  loco::Node *rhs = _mir2loco_map.at(op.getInput(1));
  auto result = createEltwiseBinary<loco::EltwiseDiv>(op, lhs, rhs);
  // Not set Shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), result);
}

void Transformer::visit(mir::ops::FullyConnectedOp &op)
{
  mir::Operation::Output *mir_lhs = op.getInput(0);
  mir::Operation::Output *mir_rhs = op.getInput(1);
  // Check 2D shape
  assert(op.getInput(0)->getShape().rank() == 2);
  assert(op.getInput(1)->getShape().rank() == 2);

  loco::Node *lhs = _mir2loco_map.at(mir_lhs);
  loco::Node *rhs = _mir2loco_map.at(mir_rhs);

  auto *encoded_lhs = _loco_graph->nodes()->create<loco::MatrixEncode>();
  encoded_lhs->input(lhs);
  encoded_lhs->encoder(createHWMatrixEncoder());

  auto *encoded_rhs = _loco_graph->nodes()->create<loco::MatrixEncode>();
  encoded_rhs->input(rhs);
  encoded_rhs->encoder(createHWMatrixEncoder());

  auto *mat_mul = _loco_graph->nodes()->create<loco::MatMul>();
  mat_mul->lhs(encoded_lhs);
  mat_mul->rhs(encoded_rhs);

  auto *output = _loco_graph->nodes()->create<loco::MatrixDecode>();
  output->input(mat_mul);
  output->decoder(createHWMatrixDecoder());

  _mir2loco_map.emplace(op.getOutput(0), output);
}

void Transformer::visit(mir::ops::InputOp &op)
{
  mir::Operation::Output *mir_output = op.getOutput(0);

  loco::GraphInput *graph_input = _loco_graph->inputs()->create();
  graph_input->name(mir_output->getName());
  graph_input->dtype(convertDataType(mir_output->getElementType()));

  auto *pull_node = _loco_graph->nodes()->create<loco::Pull>();
  setupShape(mir_output->getShape(), pull_node);

  loco::link(graph_input, pull_node);

  _mir2loco_map.emplace(mir_output, pull_node);
}

void Transformer::visit(mir::ops::MaxPool2DOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));

  auto *encoded_input = _loco_graph->nodes()->create<loco::FeatureEncode>();
  encoded_input->input(input);
  encoded_input->encoder(createFeatureEncoder(op.getDataFormat()));

  auto max_pool_node = _loco_graph->nodes()->create<loco::MaxPool2D>();
  max_pool_node->ifm(encoded_input);
  setupWindow(op.getWindowSize(), max_pool_node->window());
  setupStride(op.getStrides(), max_pool_node->stride());
  setupPad(op.getPaddingBefore(), op.getPaddingAfter(), max_pool_node->pad());

  auto *output = _loco_graph->nodes()->create<loco::FeatureDecode>();
  output->input(max_pool_node);
  output->decoder(createFeatureDecoder(op.getDataFormat()));

  _mir2loco_map.emplace(op.getOutput(0), output);
}

void Transformer::visit(mir::ops::MulOp &op)
{
  // Get Input
  loco::Node *lhs = _mir2loco_map.at(op.getInput(0));
  loco::Node *rhs = _mir2loco_map.at(op.getInput(1));
  auto result = createEltwiseBinary<loco::EltwiseMul>(op, lhs, rhs);
  // Not set Shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), result);
}

void Transformer::visit(mir::ops::OutputOp &op)
{
  mir::Operation::Output *mir_input = op.getInput(0);
  loco::Node *input = _mir2loco_map.at(mir_input);

  loco::GraphOutput *graph_output = _loco_graph->outputs()->create();
  graph_output->name(mir_input->getName());
  graph_output->dtype(convertDataType(mir_input->getElementType()));
  graph_output->shape(make_tensor_shape(mir_input->getShape()));

  auto *push_node = _loco_graph->nodes()->create<loco::Push>();
  push_node->from(input);

  loco::link(graph_output, push_node);
}

void Transformer::visit(mir::ops::ReluOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));

  auto relu_node = _loco_graph->nodes()->create<loco::ReLU>();
  relu_node->input(input);
  // Not set shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), relu_node);
}

void Transformer::visit(mir::ops::ReshapeOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));

  auto reshape_node = _loco_graph->nodes()->create<loco::Reshape<loco::ReshapeType::Fixed>>();
  reshape_node->input(input);
  // Set Shape
  auto &out_shape = op.getOutputShape(0);
  setupShape(out_shape, reshape_node);
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), reshape_node);
}

void Transformer::visit(mir::ops::SoftmaxOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));

  auto softmax_node = _loco_graph->nodes()->create<loco::TensorSoftmax>();
  softmax_node->input(input);
  // Set Axis
  softmax_node->axis(op.getAxis());
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), softmax_node);
}

void Transformer::visit(mir::ops::SubOp &op)
{
  // Get Input
  loco::Node *lhs = _mir2loco_map.at(op.getInput(0));
  loco::Node *rhs = _mir2loco_map.at(op.getInput(1));
  auto result = createEltwiseBinary<loco::EltwiseSub>(op, lhs, rhs);
  // Not set Shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), result);
}

void Transformer::visit(mir::ops::TransposeOp &op)
{
  loco::Node *input = _mir2loco_map.at(op.getInput(0));
  const auto &axis_order = op.getAxisOrder();

  auto transpose_node = _loco_graph->nodes()->create<loco::TensorTranspose>();
  transpose_node->input(input);
  // Set axis order
  transpose_node->perm()->size(axis_order.size());
  for (size_t i = 0; i < axis_order.size(); i++)
    transpose_node->perm()->axis(i) = axis_order[i];
  // Not set shape
  // Add to map
  _mir2loco_map.emplace(op.getOutput(0), transpose_node);
}

void Transformer::visit_fallback(mir::Operation &op) { throw std::runtime_error("NYI operation"); }

std::unique_ptr<loco::Graph> Transformer::transform(mir::Graph *mir_graph)
{
  _mir2loco_map.clear();
  _loco_graph.reset();
  _loco_graph = loco::make_graph();

  // Transform Nodes
  mir_graph->accept(this);

  // validate graph
  assert(loco::valid(_loco_graph.get()));

  return std::move(_loco_graph);
}

} // namespace mir2loco