mlu_postprocess_pass.cc 23.6 KB
Newer Older
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
// Copyright (c) 2019 PaddlePaddle 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 "lite/core/mir/mlu_postprocess_pass.h"
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "lite/core/mir/graph_visualize_pass.h"
#include "lite/core/mir/pass_registry.h"
#include "lite/operators/subgraph_op.h"

namespace paddle {
namespace lite {
namespace mir {

Node* MLUPostprocessPass::InsertCastBefore(const std::string& op_type,
                                           const std::string& cast_arg_name,
                                           SSAGraph* graph,
                                           Node* cur_node,
                                           Node* inst_node,
                                           const Type* cast_type) {
  // create the arg node
  auto* cast_arg = graph->NewArgumentNode(cast_arg_name);
  cast_arg->AsArg().type = cast_type;
  inst_node->AsStmt().op()->scope()->Var(cast_arg_name);

  // create the stmt node
  auto* cast_inst = graph->NewInstructNode();
  // create op
  auto cast_op = LiteOpRegistry::Global().Create(op_type);
  CHECK(cast_op) << "create op [" << op_type << "] failed";
  cpp::OpDesc op_desc;
  op_desc.SetType(op_type);
  if (op_type == "cast") {
    op_desc.SetAttr<int>("in_dtype", 5);   // FP32
    op_desc.SetAttr<int>("out_dtype", 4);  // FP16
    op_desc.SetInput("X", {cur_node->AsArg().name});
    op_desc.SetOutput("Out", {cast_arg_name});
52
  } else if (op_type == "layout") {
53
    // NCHW -> NHWC
54
    op_desc.SetInput("Input", {cur_node->AsArg().name});
55 56 57 58 59 60 61 62
    op_desc.SetOutput("Out", {cast_arg_name});
  } else if (op_type == "io_copy") {
    op_desc.SetInput("Input", {cur_node->AsArg().name});
    op_desc.SetOutput("Out", {cast_arg_name});
  } else {
    CHECK(0) << "Unsupport cast type";
  }
  cast_op->Attach(op_desc, inst_node->AsStmt().op()->scope());
63 64

  auto v_places = graph->valid_places();
65
  // create kernels
66
  auto kernels = cast_op->CreateKernels(v_places);
67 68 69 70 71
  std::vector<std::unique_ptr<KernelBase>> selected_kernels;
  bool is_found = false;
  for (auto& kernel : kernels) {
    if (op_type == "cast") {
      const Type* in_arg_ty = kernel->GetInputDeclType("X");
72 73
      if (PrecisionCompatibleTo(*in_arg_ty, *cur_node->AsArg().type) &&
          DataLayoutCompatible(*in_arg_ty, *cur_node->AsArg().type)) {
74 75
        is_found = true;
      }
76 77 78 79
    } else if (op_type == "layout") {
      const Type* in_arg_ty = kernel->GetInputDeclType("Input");
      const Type* out_arg_ty = kernel->GetOutputDeclType("Out");
      if (DataLayoutCompatible(*in_arg_ty, *cur_node->AsArg().type) &&
J
jackzhang235 已提交
80 81 82
          DataLayoutCompatible(*out_arg_ty, *cast_type) &&
          //  for first conv
          PrecisionCompatibleTo(*in_arg_ty, *cur_node->AsArg().type)) {
83 84
        is_found = true;
      }
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    } else if (op_type == "io_copy") {
      const Type* in_arg_ty = kernel->GetInputDeclType("Input");
      const Type* out_arg_ty = kernel->GetOutputDeclType("Out");
      if (TargetCompatibleTo(*in_arg_ty, *cur_node->AsArg().type) &&
          TargetCompatibleTo(*out_arg_ty, *cast_type)) {
        is_found = true;
      }
    } else {
      CHECK(0) << "Unsupport cast type";
    }
    if (is_found) {
      selected_kernels.emplace_back(std::move(kernel));
      // we pick the kernel
      cast_inst->AsStmt(op_type, std::move(selected_kernels), cast_op);
      auto& stmt = cast_inst->AsStmt();
J
jackzhang235 已提交
100 101
      stmt.picked_kernel().SetContext(
          ContextScheduler::Global().NewContext(stmt.picked_kernel().target()));
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
      break;
    }
  }
  CHECK(is_found) << "Can't find a Cast kernel for Cast op: "
                  << cur_node->AsArg().name << "->" << op_type;
  // modify links
  DirectedLink(cur_node, cast_inst);
  DirectedLink(cast_inst, cast_arg);
  return cast_arg;
}

Node* MLUPostprocessPass::InsertCastAfter(const std::string& op_type,
                                          const std::string& cast_arg_name,
                                          SSAGraph* graph,
                                          Node* cur_node,
                                          Node* inst_node,
                                          const Type* cast_type) {
  // create the arg node
  auto* cast_arg = graph->NewArgumentNode(cast_arg_name);
  cast_arg->AsArg().type = cast_type;
  auto* var = inst_node->AsStmt().op()->scope()->Var(cast_arg_name);
  // for CastAfter manully set the tensor's type
J
jackzhang235 已提交
124
  var->GetMutable<paddle::lite::Tensor>();
125 126 127 128 129 130 131 132 133 134 135 136 137

  // create the stmt node
  auto* cast_inst = graph->NewInstructNode();
  // create op
  auto cast_op = LiteOpRegistry::Global().Create(op_type);
  CHECK(cast_op) << "create op [" << op_type << "] failed";
  cpp::OpDesc op_desc;
  op_desc.SetType(op_type);
  if (op_type == "cast") {
    op_desc.SetAttr<int>("in_dtype", 4);   // FP32
    op_desc.SetAttr<int>("out_dtype", 5);  // FP16
    op_desc.SetInput("X", {cast_arg_name});
    op_desc.SetOutput("Out", {cur_node->AsArg().name});
138
  } else if (op_type == "layout") {
139
    // NHWC -> NCHW
140
    op_desc.SetInput("Input", {cast_arg_name});
141 142 143 144 145 146 147 148 149 150
    op_desc.SetOutput("Out", {cur_node->AsArg().name});
  } else if (op_type == "io_copy") {
    op_desc.SetInput("Input", {cast_arg_name});
    op_desc.SetOutput("Out", {cur_node->AsArg().name});
  } else {
    CHECK(0) << "Unsupport cast type";
  }

  cast_op->Attach(op_desc, inst_node->AsStmt().op()->scope());

151
  auto v_places = graph->valid_places();
152
  // create kernels
153
  auto kernels = cast_op->CreateKernels(v_places);
154 155 156 157 158 159 160 161
  std::vector<std::unique_ptr<KernelBase>> selected_kernels;
  bool is_found = false;
  for (auto& kernel : kernels) {
    if (op_type == "cast") {
      const Type* in_arg_ty = kernel->GetInputDeclType("X");
      if (PrecisionCompatibleTo(*in_arg_ty, *cast_type)) {
        is_found = true;
      }
162 163 164 165
    } else if (op_type == "layout") {
      const Type* in_arg_ty = kernel->GetInputDeclType("Input");
      const Type* out_arg_ty = kernel->GetOutputDeclType("Out");
      if (DataLayoutCompatible(*in_arg_ty, *cast_type) &&
J
jackzhang235 已提交
166 167
          DataLayoutCompatible(*out_arg_ty, *cur_node->AsArg().type) &&
          PrecisionCompatibleTo(*in_arg_ty, *cast_type)) {
168 169
        is_found = true;
      }
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    } else if (op_type == "io_copy") {
      const Type* in_arg_ty = kernel->GetInputDeclType("Input");
      const Type* out_arg_ty = kernel->GetOutputDeclType("Out");
      if (TargetCompatibleTo(*in_arg_ty, *cast_type) &&
          TargetCompatibleTo(*out_arg_ty, *cur_node->AsArg().type)) {
        is_found = true;
      }
    } else {
      CHECK(0) << "Unsupport cast type";
    }
    if (is_found) {
      selected_kernels.emplace_back(std::move(kernel));
      // we pick the kernel
      cast_inst->AsStmt(op_type, std::move(selected_kernels), cast_op);
      auto& stmt = cast_inst->AsStmt();
J
jackzhang235 已提交
185 186
      stmt.picked_kernel().SetContext(
          ContextScheduler::Global().NewContext(stmt.picked_kernel().target()));
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
      break;
    }
  }
  CHECK(is_found) << "Can't find a Cast kernel for Cast op: "
                  << cur_node->AsArg().name << "->" << op_type;
  // modify links
  DirectedLink(cast_arg, cast_inst);
  DirectedLink(cast_inst, cur_node);
  return cast_arg;
}

void MLUPostprocessPass::InsertBefore(SSAGraph* graph,
                                      Node* head_node,
                                      Node* inst_node,
                                      const Type* inst_type) {
  const auto* head_type = head_node->AsArg().type;

  // break original link
  RemoveDirectedLink(head_node, inst_node);

  auto* cur_node = head_node;
  const auto name_prefix =
      head_node->AsArg().name + string_format("_%p", inst_node) + "/trans_";
J
jackzhang235 已提交
210 211 212 213
  bool is_first_conv_head =
      std::find(first_conv_nodes_.begin(),
                first_conv_nodes_.end(),
                head_node->AsArg().name) != first_conv_nodes_.end();
214

215 216
  // precision cast node
  if (head_type->precision() != inst_type->precision() && !is_first_conv_head) {
217
    cur_node = InsertCastBefore(
218 219
        "cast",
        name_prefix + "cast",
220 221 222 223
        graph,
        cur_node,
        inst_node,
        LiteType::GetTensorTy(
224
            head_type->target(), inst_type->precision(), head_type->layout()));
225 226
  }

227 228
  // layout cast node
  if (head_type->layout() != inst_type->layout()) {
229
    cur_node = InsertCastBefore(
230 231
        "layout",
        name_prefix + "layout",
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
        graph,
        cur_node,
        inst_node,
        LiteType::GetTensorTy(
            head_type->target(), inst_type->precision(), inst_type->layout()));
  }

  // io copy
  cur_node = InsertCastBefore(
      "io_copy",
      name_prefix + "io_copy",
      graph,
      cur_node,
      inst_node,
      LiteType::GetTensorTy(
          inst_type->target(), inst_type->precision(), inst_type->layout()));

  // connect cur_node to inst_node
  DirectedLink(cur_node, inst_node);

  // reset opdesc and update kernel information
  UpdateInputTo(inst_node->AsStmt().op()->mutable_op_info(),
                head_node->AsArg().name,
                cur_node->AsArg().name);
  // for subgraph op, modify the BlockDesc
  auto* sub_block_desc = dynamic_cast<paddle::lite::operators::SubgraphOp*>(
                             inst_node->AsStmt().op().get())
                             ->GetSubBlock();
  for (size_t i = 0; i < sub_block_desc->OpsSize(); ++i) {
    auto* sub_block_op_desc = sub_block_desc->GetOp<cpp::OpDesc>(i);
    UpdateInputTo(
        sub_block_op_desc, head_node->AsArg().name, cur_node->AsArg().name);
  }

  // recreate the op
  RecreateOp(inst_node, graph);

  graph->CheckValid();
}

void MLUPostprocessPass::GetSubgraphOpArgType(Node* inst_node,
                                              const Type** arg_type,
                                              SSAGraph* graph) {
  CHECK(inst_node->IsStmt());
  constexpr auto subgraph_target = TARGET(kMLU);
  constexpr auto subgraph_layout = DATALAYOUT(kNHWC);

  // get subgraph's valid precision
  const auto& places = graph->valid_places();
J
jackzhang235 已提交
281
  std::set<paddle::lite_api::PrecisionType> prec_set;
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
  for (const auto& place : places) {
    if (place.target == TARGET(kMLU)) {
      prec_set.insert(place.precision);
    }
  }

  // get subgraph op's type info
  size_t kernel_size = inst_node->AsStmt().kernels().size();
  CHECK_GT(kernel_size, 0);
  VLOG(4) << "subgraph kernel size: " << kernel_size;

  for (size_t i = 0; i < kernel_size; ++i) {
    auto* kernel = inst_node->AsStmt().kernels()[i].get();
    VLOG(4) << i << "th kernel: " << TargetToStr(kernel->target()) << ", "
            << PrecisionToStr(kernel->precision()) << ", "
            << DataLayoutToStr(kernel->layout());
  }

  for (size_t i = 0; i < kernel_size; ++i) {
    auto* kernel = inst_node->AsStmt().kernels()[i].get();
    CHECK(kernel->target() == subgraph_target);
    CHECK(kernel->layout() == subgraph_layout);
    if (prec_set.count(kernel->precision()) == 1) {
      const auto subgraph_precision = kernel->precision();
      CHECK(subgraph_precision == PRECISION(kFloat) ||
            subgraph_precision == PRECISION(kFP16))
          << "Mlu node has unsupport precision";
      VLOG(4) << "picked kernel precision: "
              << PrecisionToStr(subgraph_precision);
      *arg_type = LiteType::GetTensorTy(
          subgraph_target, subgraph_precision, subgraph_layout);
      break;
    }
  }
}

bool MLUPostprocessPass::NeedInsert(Node* node, const Type* inst_type) {
  CHECK(node->IsArg());

  // some op, for example batch_norm, has output nodes useless
  if (node->outlinks.size() == 0) {
    return false;
  }

  // check if node is weight or persistent
  bool is_persist = node->AsArg().is_weight || node->AsArg().is_persist;
  if (is_persist) {
    VLOG(4) << "Persistent arg name: " << node->AsArg().name
            << " is_weight: " << node->AsArg().is_weight
            << " is_persist: " << node->AsArg().is_persist;
    return false;
  }

  const auto target = node->AsArg().type->target();
  const auto precision = node->AsArg().type->precision();
  const auto layout = node->AsArg().type->layout();
  VLOG(4) << "arg name: " << node->AsArg().name
          << " type: " << TargetToStr(target) << ", "
          << PrecisionToStr(precision) << ", " << DataLayoutToStr(layout);

  // do not insert nodes if previous node is on mlu already
  if (target == inst_type->target()) {
    CHECK(layout == inst_type->layout()) << "Mlu node has wrong layout";
    return false;
  }

  return true;
}

void MLUPostprocessPass::InsertAfter(SSAGraph* graph,
                                     Node* tail_node,
                                     Node* inst_node,
                                     const Type* inst_type) {
  const auto* tail_type = tail_node->AsArg().type;

  // break original link
  RemoveDirectedLink(inst_node, tail_node);

  auto* cur_node = tail_node;
  const auto name_prefix =
      tail_node->AsArg().name + string_format("_%p", inst_node) + "/trans_";

364 365
  // precision cast node
  if (tail_type->precision() != inst_type->precision()) {
366
    cur_node = InsertCastAfter(
367 368
        "cast",
        name_prefix + "cast",
369 370 371 372
        graph,
        cur_node,
        inst_node,
        LiteType::GetTensorTy(
373
            tail_type->target(), inst_type->precision(), tail_type->layout()));
374 375
  }

376 377
  // layout cast node
  if (tail_type->layout() != inst_type->layout()) {
378
    cur_node = InsertCastAfter(
379 380
        "layout",
        name_prefix + "layout",
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
        graph,
        cur_node,
        inst_node,
        LiteType::GetTensorTy(
            tail_type->target(), inst_type->precision(), inst_type->layout()));
  }

  // io copy
  cur_node = InsertCastAfter(
      "io_copy",
      name_prefix + "io_copy",
      graph,
      cur_node,
      inst_node,
      LiteType::GetTensorTy(
          inst_type->target(), inst_type->precision(), inst_type->layout()));

  // connect cur_node to inst_node
  DirectedLink(inst_node, cur_node);

  // reset opdesc and update kernel information
  UpdateOutputTo(inst_node->AsStmt().op()->mutable_op_info(),
                 tail_node->AsArg().name,
                 cur_node->AsArg().name);
  // for subgraph op, modify the BlockDesc
  auto* sub_block_desc = dynamic_cast<paddle::lite::operators::SubgraphOp*>(
                             inst_node->AsStmt().op().get())
                             ->GetSubBlock();
  for (size_t i = 0; i < sub_block_desc->OpsSize(); ++i) {
    auto* sub_block_op_desc = sub_block_desc->GetOp<cpp::OpDesc>(i);
    UpdateOutputTo(
        sub_block_op_desc, tail_node->AsArg().name, cur_node->AsArg().name);
J
jackzhang235 已提交
413 414 415 416 417 418 419 420
    /* graph like this
     *        subgraph_op_0
     *          /       \
     *         /         \
     * subgraph_op_1   host_op
     */
    UpdateInputTo(
        sub_block_op_desc, tail_node->AsArg().name, cur_node->AsArg().name);
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  }

  // recreate the op
  RecreateOp(inst_node, graph);

  graph->CheckValid();
}

void MLUPostprocessPass::RecreateOp(Node* inst_node, SSAGraph* graph) {
  auto original_selected_kernel =
      std::move(inst_node->AsStmt().kernels().front());
  auto updated_op_info = *inst_node->AsStmt().mutable_op_info();

  inst_node->AsStmt().ResetOp(updated_op_info, graph->valid_places());
  inst_node->AsStmt().kernels().clear();
  inst_node->AsStmt().kernels().emplace_back(
      std::move(original_selected_kernel));
  for (auto& kernel : inst_node->AsStmt().kernels()) {
    VLOG(4) << "kernel info: " << kernel->name();
    inst_node->AsStmt().op()->AttachKernel(kernel.get());
  }
}

J
jackzhang235 已提交
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
bool MLUPostprocessPass::IsFirstConvInSubgraph(Node* arg_node, Node* inst) {
  auto* block_desc =
      static_cast<operators::SubgraphOp*>(inst->AsStmt().op().get())
          ->GetSubBlock();
  for (int op_idx = 0; op_idx < block_desc->OpsSize(); op_idx++) {
    auto op_desc = block_desc->GetOp<cpp::OpDesc>(op_idx);
    CHECK(op_desc);
    if (op_desc->Type() == "conv2d") {
      for (auto& names : op_desc->inputs()) {
        if (std::find(names.second.begin(),
                      names.second.end(),
                      arg_node->AsArg().name) != names.second.end()) {
          return true;
        }
      }
    }
  }
  return false;
}

bool MLUPostprocessPass::IsFirstConvNode(Node* arg_node) {
  CHECK(arg_node->IsArg());
  for (auto& inst : arg_node->outlinks) {
    if (inst->AsStmt().op_type() == "subgraph") {
      return IsFirstConvInSubgraph(arg_node, inst);
    }
  }
  return false;
}

J
jackzhang235 已提交
474
void MLUPostprocessPass::GatherAndModifyFirstConvNodes(SSAGraph* graph) {
J
jackzhang235 已提交
475 476 477 478 479 480
  for (auto& node : graph->mutable_nodes()) {
    if (!node.IsStmt()) continue;
    if (node.AsStmt().op_type() == "feed") {
      for (auto& out : node.outlinks) {
        if (IsFirstConvNode(out)) {
          first_conv_nodes_.insert(out->AsArg().name);
J
jackzhang235 已提交
481 482 483 484 485 486 487
          // modify first conv nodes' type
          const auto* old_type = out->AsArg().type;
          out->AsArg().type =
              LiteType::GetTensorTy(old_type->target(),
                                    paddle::lite_api::PrecisionType::kInt8,
                                    old_type->layout(),
                                    old_type->device());
J
jackzhang235 已提交
488 489 490 491 492 493
        }
      }
    }
  }
}

J
jackzhang235 已提交
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
void MLUPostprocessPass::ModifyInputOutputDataType(SSAGraph* graph) {
  for (auto& node : graph->mutable_nodes()) {
    if (node.IsStmt() && node.AsStmt().op_type() == "subgraph") {
      for (auto& in_node : node.inlinks) {
        const auto* in_node_type = in_node->AsArg().type;
        VLOG(4) << "MLU subgraph input type: " << in_node->AsArg().name
                << *in_node_type;
        if (in_node->AsArg().is_weight || in_node->AsArg().is_persist) {
          CHECK(in_node_type->target() == TARGET(kHost) &&
                in_node_type->precision() == PRECISION(kAny) &&
                in_node_type->layout() == DATALAYOUT(kNCHW))
              << "MLU subgraph unexpected persistent input type!";
          in_node->AsArg().type = LiteType::GetTensorTy(
              TARGET(kMLU), PRECISION(kAny), DATALAYOUT(kNHWC));
        } else {
          CHECK((in_node_type->target() == TARGET(kHost) ||
                 in_node_type->target() == TARGET(kX86)) &&
                in_node_type->precision() == PRECISION(kFloat) &&
                in_node_type->layout() == DATALAYOUT(kNCHW))
              << "MLU subgraph unexpected common input type!";
        }
      }
      for (auto& out_node : node.outlinks) {
        const auto* out_node_type = out_node->AsArg().type;
        VLOG(4) << "MLU subgraph output type: " << out_node->AsArg().name
                << *out_node_type;
        if (out_node->AsArg().is_weight || out_node->AsArg().is_persist) {
          CHECK(out_node_type->target() == TARGET(kHost) &&
                out_node_type->precision() == PRECISION(kAny) &&
                out_node_type->layout() == DATALAYOUT(kNCHW))
              << "MLU subgraph unexpected persistent input type!";
          out_node->AsArg().type = LiteType::GetTensorTy(
              TARGET(kMLU), PRECISION(kAny), DATALAYOUT(kNHWC));
J
jiaopu 已提交
527 528 529 530 531
        } else if (out_node_type->precision() == PRECISION(kAny) &&
                   out_node->outlinks.empty()) {
          out_node->AsArg().is_persist = true;
          out_node->AsArg().type = LiteType::GetTensorTy(
              TARGET(kMLU), PRECISION(kAny), DATALAYOUT(kNHWC));
J
jackzhang235 已提交
532 533 534 535 536 537
        } else {
          CHECK(out_node_type->precision() == PRECISION(kFloat))
              << "MLU subgraph unexpected common output type!";
          out_node->AsArg().type = LiteType::GetTensorTy(
              TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kNCHW));
        }
J
jiaopu 已提交
538 539 540 541 542 543
        const auto target = out_node->AsArg().type->target();
        const auto precision = out_node->AsArg().type->precision();
        const auto layout = out_node->AsArg().type->layout();
        VLOG(4) << "arg name: " << out_node->AsArg().name
                << " type: " << TargetToStr(target) << ", "
                << PrecisionToStr(precision) << ", " << DataLayoutToStr(layout);
J
jackzhang235 已提交
544 545 546 547 548
      }
    }
  }
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
void MLUPostprocessPass::ModifyLayout(SSAGraph* graph) {
  for (auto& node : graph->mutable_nodes()) {
    if (!node.IsStmt()) continue;
    if (node.AsStmt().op_type() == "feed") {
      for (auto& out : node.outlinks) {
        bool change = true;
        for (auto& inst : out->outlinks) {
          if (inst->AsStmt().op_type() != "subgraph") {
            change = false;
            break;
          }
        }
        if (change) {
          const auto* old_type = out->AsArg().type;
          out->AsArg().type =
              LiteType::GetTensorTy(old_type->target(),
                                    old_type->precision(),
J
jackzhang235 已提交
566
                                    paddle::lite_api::DataLayoutType::kNHWC,
567
                                    old_type->device());
568 569 570 571 572 573 574 575 576 577
          // modify inst feed to NHWC, while set_mlu_input_layout(kNHWC)
          // invoked, to keep consistent with actual data layout
          auto place = node.AsStmt().place();
          place.layout = DATALAYOUT(kNHWC);
          std::vector<Place> valid_places = {place};
          auto updated_op_info = *node.AsStmt().op_info();
          node.AsStmt().ResetOp(updated_op_info, valid_places, nullptr);
          auto kernel = &(node.AsStmt().picked_kernel());
          VLOG(4) << "kernel info: " << kernel->name();
          node.AsStmt().op()->AttachKernel(kernel);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        }
      }
    }
    if (node.AsStmt().op_type() == "fetch") {
      for (auto& inp : node.inlinks) {
        bool change = true;
        for (auto& inst : inp->inlinks) {
          if (inst->AsStmt().op_type() != "subgraph") {
            change = false;
            break;
          }
        }
        if (change) {
          const auto* old_type = inp->AsArg().type;
          inp->AsArg().type =
              LiteType::GetTensorTy(old_type->target(),
                                    old_type->precision(),
J
jackzhang235 已提交
595
                                    paddle::lite_api::DataLayoutType::kNHWC,
596 597 598 599 600 601 602 603
                                    old_type->device());
        }
      }
    }
  }
}

void MLUPostprocessPass::Apply(const std::unique_ptr<SSAGraph>& graph) {
J
jiaopu 已提交
604 605
// currently for non-persistent input and output args, mlu subgraph op
// only support float16/float32 data type
606

J
jiaopu 已提交
607 608 609 610
// in two situations as folllows:
// 1: feed->arg_in->subgraph->... 2: ...->subgraph->arg_out->fetch;
// arg_in and arg_out are assumed to be NHWC which user should be aware of.
// Thus here we change these args' layout to NHWC
611
#ifdef LITE_WITH_MLU
J
jackzhang235 已提交
612 613
  ModifyInputOutputDataType(graph.get());

J
jackzhang235 已提交
614
  if (lite::TargetWrapperMlu::InputLayout() == DATALAYOUT(kNHWC)) {
J
jackzhang235 已提交
615 616
    ModifyLayout(graph.get());
  }
617

J
jackzhang235 已提交
618
  if (lite::TargetWrapperMlu::UseFirstConv()) {
J
jackzhang235 已提交
619
    GatherAndModifyFirstConvNodes(graph.get());
J
jackzhang235 已提交
620
  }
621
#endif
J
jackzhang235 已提交
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
  // insert io_copy, layout and precision cast of subgraph's inputs and outputs
  for (auto& node : graph->mutable_nodes()) {
    if (node.IsStmt() && node.AsStmt().op_type() == "subgraph") {
      const Type* subgraph_arg_type = nullptr;
      GetSubgraphOpArgType(&node, &subgraph_arg_type, graph.get());

      auto links_tmp = node.inlinks;
      for (auto p_in : links_tmp) {
        if (NeedInsert(p_in, subgraph_arg_type)) {
          InsertBefore(graph.get(), p_in, &node, subgraph_arg_type);
        }
      }
      links_tmp.assign(node.outlinks.begin(), node.outlinks.end());
      for (auto p_out : links_tmp) {
        if (NeedInsert(p_out, subgraph_arg_type)) {
          InsertAfter(graph.get(), p_out, &node, subgraph_arg_type);
        }
      }
    }
  }
}

}  // namespace mir
}  // namespace lite
}  // namespace paddle

REGISTER_MIR_PASS(mlu_postprocess_pass, paddle::lite::mir::MLUPostprocessPass)
    .BindTargets({TARGET(kMLU)});