nn.cc 117.7 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
// Copyright (c) 2021 CINN 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 "paddle/cinn/hlir/pe/nn.h"

#include <functional>

#include "paddle/cinn/hlir/framework/node.h"
#include "paddle/cinn/hlir/framework/op.h"
#include "paddle/cinn/hlir/framework/op_strategy.h"
#include "paddle/cinn/hlir/op/op_util.h"
#include "paddle/cinn/hlir/pe/broadcast.h"
#include "paddle/cinn/hlir/pe/elementwise.h"
#include "paddle/cinn/hlir/pe/ir_schedule_pe.h"
#include "paddle/cinn/hlir/pe/schedule.h"
#include "paddle/cinn/ir/ir_base.h"
#include "paddle/cinn/ir/layout.h"
#include "paddle/cinn/poly/stage.h"

DECLARE_bool(cinn_ir_schedule);

namespace cinn {
namespace hlir {
namespace op {
using common::_CINNValuePack_;
using common::CINNValue;
using common::CINNValuePack;
using framework::OpStrategy;
using framework::shape_t;
using framework::StrategyFunction;

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
std::shared_ptr<OpStrategy> StrategyForRelu(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  framework::CINNCompute relu_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of relu compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK(!pack_args.empty())
            << "at least one input tensor for relu compute\n";
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        std::string tensor_name = UniqName("Relu_output");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
        auto out = pe::Relu(A.as_tensor_ref(), 0.0, tensor_name);
        auto stages = CreateStages({out});
        *ret = CINNValuePack{{CINNValue(Expr(out.get())), CINNValue(stages)}};
      });
68 69 70

  auto strategy = std::make_shared<framework::OpStrategy>();
  CHECK(out_type.size()) << "Out_type of relu op is empty! Please check.";
71 72 73 74
  strategy->AddImpl(relu_compute,
                    GetInjectiveScheduleFunc(output_shapes, target),
                    "strategy.relu.x86",
                    1);
75 76 77
  return strategy;
}

78 79 80 81 82
std::vector<framework::shape_t> InferShapeForRelu(
    const std::vector<framework::shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty())
      << "The input's shape is empty! Please check again.";
83 84 85 86
  std::vector<framework::shape_t> res{inputs_shape[0]};
  return res;
}

87 88 89 90
std::vector<Type> InferDtypeForRelu(const std::vector<Type> &inputs_type,
                                    const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
91 92 93 94
  std::vector<Type> res{inputs_type[0]};
  return res;
}

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
std::shared_ptr<OpStrategy> StrategyForRelu6(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  framework::CINNCompute relu6_compute(
      [](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of relu6 compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK(!pack_args.empty())
            << "at least one input tensor for relu6 compute\n";
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        std::string tensor_name = UniqName("Relu6_output");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
        auto out = pe::Relu6(A.as_tensor_ref(), 0.0, tensor_name);
        auto stages = CreateStages({out});
        *ret = CINNValuePack{{CINNValue(Expr(out.get())), CINNValue(stages)}};
      });
120 121 122

  auto strategy = std::make_shared<framework::OpStrategy>();
  CHECK(out_type.size()) << "Out_type of relu6 op is empty! Please check.";
123 124 125 126
  strategy->AddImpl(relu6_compute,
                    GetInjectiveScheduleFunc(output_shapes, target),
                    "strategy.relu6.x86",
                    1);
127 128 129
  return strategy;
}

130 131 132 133 134 135
std::shared_ptr<OpStrategy> StrategyForConv2d(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
136 137 138 139
  std::vector<int> padding({0, 0});
  std::vector<int> stride({1, 1});
  std::vector<int> dilation({1, 1});
  std::string data_format = "NCHW";
140 141 142 143
  int groups = 1;
  std::string key = "";
  std::string conv_type = "";
  bool use_mkldnn = false;
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
  if (attrs.attr_store.find("padding") != attrs.attr_store.end()) {
    padding = absl::get<std::vector<int>>(attrs.attr_store.at("padding"));
  }
  if (attrs.attr_store.find("stride") != attrs.attr_store.end()) {
    stride = absl::get<std::vector<int>>(attrs.attr_store.at("stride"));
  }
  if (attrs.attr_store.find("dilation") != attrs.attr_store.end()) {
    dilation = absl::get<std::vector<int>>(attrs.attr_store.at("dilation"));
  }
  if (attrs.attr_store.find("data_format") != attrs.attr_store.end()) {
    data_format = absl::get<std::string>(attrs.attr_store.at("data_format"));
  }
  if (attrs.attr_store.find("groups") != attrs.attr_store.end()) {
    groups = absl::get<int>(attrs.attr_store.at("groups"));
  }
  if (attrs.attr_store.find("use_mkldnn") != attrs.attr_store.end()) {
    use_mkldnn = absl::get<bool>(attrs.attr_store.at("use_mkldnn"));
  }
  if (attrs.attr_store.find("key") != attrs.attr_store.end()) {
    key = absl::get<std::string>(attrs.attr_store.at("key"));
  }
  // get conv type
  if (attrs.attr_store.find("conv_type") != attrs.attr_store.end()) {
    conv_type = absl::get<std::string>(attrs.attr_store.at("conv_type"));
  } else {
    conv_type = "forward";
  }

#ifndef CINN_WITH_CUDNN
173 174
  CHECK_EQ(conv_type, "forward")
      << "cudnn is not found, backward_data/backward_filter is not supported!";
175 176
#endif

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
  framework::CINNCompute conv2d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        std::vector<CINNValue> res;
        CHECK(!args.empty())
            << "The input argument of conv2d compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK_GE(pack_args.size(), 2U)
            << "at least 2 input tensors for conv2d compute\n";
        Expr A = pack_args[0];
        Expr B = pack_args[1];
        CHECK(A.as_tensor());
        CHECK(B.as_tensor());
        CHECK_EQ(padding.size(), 2)
            << "The size of padding in conv2d op is not 2! Please check.";
        CHECK_EQ(stride.size(), 2)
            << "The size of stride in conv2d op is not 2! Please check.";
        CHECK_EQ(dilation.size(), 2)
            << "The size of stride in conv2d op is not 2! Please check.";
        std::vector<ir::Tensor> out;
        VLOG(3) << "input shape: "
                << utils::Join(A.as_tensor_ref()->shape, ", ");
        VLOG(3) << "weight shape: "
                << utils::Join(B.as_tensor_ref()->shape, ", ");
        std::string tensor_name = UniqName("Conv2d_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_GE(pack_args.size(), 3);
          CHECK(pack_args[2].is_string());
          tensor_name = pack_args[2].operator std::string();
        }
        if (data_format == "NCHW") {
          // A is input: [N, C, H, W], B is filter: [C_out, C_in/group,
          // filter_h, filter_w]
          if (target.arch == Target::Arch::X86) {
            if (groups == 1 && !use_mkldnn) {
              out = pe::Conv2d_NCHW_5D(A.as_tensor_ref(),
                                       B.as_tensor_ref(),
                                       padding[0],
                                       padding[1],
                                       stride[0],
                                       stride[1],
                                       dilation[0],
                                       dilation[1],
                                       key,
                                       tensor_name,
                                       target);
            } else {
223
#ifdef CINN_WITH_MKLDNN
224 225 226 227 228 229 230 231 232 233 234
              out = pe::Conv2d_NCHW_MKLDNN(A.as_tensor_ref(),
                                           B.as_tensor_ref(),
                                           padding[0],
                                           padding[1],
                                           stride[0],
                                           stride[1],
                                           dilation[0],
                                           dilation[1],
                                           tensor_name);
#else
              out = pe::Conv2d_NCHW_5D(A.as_tensor_ref(),
235 236 237 238 239 240 241
                                       B.as_tensor_ref(),
                                       padding[0],
                                       padding[1],
                                       stride[0],
                                       stride[1],
                                       dilation[0],
                                       dilation[1],
242
                                       key,
243 244
                                       tensor_name);
#endif
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
            }
          } else {
            if (conv_type == "forward") {
              out = pe::Conv2d_NCHW(A.as_tensor_ref(),
                                    B.as_tensor_ref(),
                                    padding[0],
                                    padding[1],
                                    stride[0],
                                    stride[1],
                                    dilation[0],
                                    dilation[1],
                                    tensor_name);
              out.push_back(B.as_tensor_ref());
            } else {
#ifdef CINN_WITH_CUDNN
              // as backward_data and backward_filter is not support now, we
              // built a fake op to instead. as the runtime use cudnn to compute
              // the conv2d, so this fake op is not been called. When cinn
              // support backward_filter/backward_data code gen, this code is to
              // be removed.
              out = pe::Identity(A.as_tensor_ref());
              out.push_back(A.as_tensor_ref());
              out.push_back(B.as_tensor_ref());
#endif
            }
          }
        } else if (data_format == "NHWC") {
          // A is input: [N, H, W, C], B is filter: [C_out, C_in/group,
          // filter_h, filter_w]
          out = pe::Conv2d_NHWC(A.as_tensor_ref(),
275 276 277 278 279 280 281 282 283
                                B.as_tensor_ref(),
                                padding[0],
                                padding[1],
                                stride[0],
                                stride[1],
                                dilation[0],
                                dilation[1],
                                tensor_name);
        } else {
284
          LOG(FATAL) << "Only support NCHW and NHWC data layout\n";
285
        }
286
        auto stages = CreateStages({A.as_tensor_ref(), B.as_tensor_ref()});
287

288 289 290 291 292 293 294 295
        for (auto &t : out) {
          stages->InsertLazily(t);
          res.push_back(CINNValue(t));
        }
        CHECK(out.size() == 3U || out.size() == 2U || out.size() == 5U ||
              out.size() == 12U)
            << "The output tensor sizes of conv2d op in conv2d op should be 2 "
               "or 3 or 5\n";
296

297 298 299
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });
300

301 302
  framework::CINNSchedule conv2d_schedule([=](lang::Args args,
                                              lang::RetValue *ret) {
303
    if (FLAGS_cinn_ir_schedule) {
304 305
      CHECK(!args.empty())
          << "The input argument of conv2d schedule is empty! Please check.\n";
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (target.arch == Target::Arch::NVGPU) {
#ifdef CINN_WITH_CUDNN
        // If conv_type is backward_filter or backward_data, we built a fake op.
321 322 323
        // As runtime use cudnn to compute conv2d, this fake op is not to be
        // called. When cinn support backward_filter/backward_data code gen,
        // this code is to be removed.
324 325 326
        if (conv_type != "forward") {
          CHECK_EQ(vec_ast.size(), 1);
          pe::IRCudaScheduleInjective(ir_sch, output_shapes.front(), target);
327 328
          std::vector<CINNValue> res{
              CINNValue(ir_sch.GetModule().GetExprs().at(0))};
329 330 331 332 333 334 335
          *ret = CINNValuePack{res};
          return;
        }
#endif
        int expr_size = vec_ast.size();
        if (expr_size == 2) {
          pe::IRCudaScheduleConv(ir_sch, target);
336 337 338 339
          VLOG(3) << "After IRCudaScheduleConv, arg_pack[0] is : "
                  << ir_sch.GetModule().GetExprs().at(0);
          std::vector<CINNValue> res{
              CINNValue(ir_sch.GetModule().GetExprs().at(0))};
340 341 342 343 344 345 346 347 348 349
          *ret = CINNValuePack{res};
          return;
        } else {
          CINN_NOT_IMPLEMENTED
        }
      } else if (target.arch == Target::Arch::X86) {
        CINN_NOT_IMPLEMENTED
      }
      LOG(FATAL) << "This target [" << target << "] is not supported yet.";
    } else {
350 351
      CHECK(!args.empty())
          << "The input argument of conv2d schedule is empty! Please check.\n";
352
      CINNValuePack arg_pack = args[0];
353 354
      CHECK(arg_pack.size() == 4UL || arg_pack.size() == 3UL ||
            arg_pack.size() == 6UL || arg_pack.size() == 13UL);
355 356 357 358
      poly::StageMap stages = arg_pack.back();
      if (target.arch == Target::Arch::NVGPU) {
#ifdef CINN_WITH_CUDNN
        // If conv_type is backward_filter or backward_data, we built a fake op.
359 360 361
        // As runtime use cudnn to compute conv2d, this fake op is not to be
        // called. When cinn support backward_filter/backward_data code gen,
        // this code is to be removed.
362 363
        if (conv_type != "forward") {
          Expr out = arg_pack[0];
364 365
          pe::CudaScheduleInjective(
              stages[out.as_tensor_ref()], output_shapes.front(), target);
366 367 368 369 370
          *ret = CINNValuePack{{CINNValue(out), CINNValue(stages)}};
          return;
        }
#endif
        if (arg_pack.size() == 4UL) {
371 372 373 374 375
          Expr Out = arg_pack[0];
          Expr input_pad = arg_pack[1];
          Expr weights = arg_pack[2];
          ir::Tensor out_t = Out.as_tensor_ref();
          ir::Tensor input_t = input_pad.as_tensor_ref();
376 377 378 379 380 381
          ir::Tensor weights_t = weights.as_tensor_ref();
          CHECK(Out.as_tensor());
          pe::CudaScheduleConv(stages, input_t, weights_t, out_t, target);
          arg_pack[0] = Expr(out_t);
          arg_pack[1] = Expr(input_t);
          arg_pack[2] = Expr(weights_t);
382
          *ret = CINNValuePack{{arg_pack[0], CINNValue(stages)}};
383 384
          return;
        } else if (arg_pack.size() == 13UL) {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
          Expr wino_weights_dilation = arg_pack[0];
          Expr wino_input_pad = arg_pack[1];
          Expr wino_A = arg_pack[2];
          Expr wino_B = arg_pack[3];
          Expr wino_G = arg_pack[4];
          Expr kernel_pack = arg_pack[5];
          Expr input_tile = arg_pack[6];
          Expr data_pack = arg_pack[7];
          Expr bgemm = arg_pack[8];
          Expr inverse = arg_pack[9];
          Expr wino_conv = arg_pack[10];
          ir::Tensor wino_weights_dilation_t =
              wino_weights_dilation.as_tensor_ref();
          ir::Tensor wino_input_pad_t = wino_input_pad.as_tensor_ref();
          ir::Tensor wino_A_t = wino_A.as_tensor_ref();
          ir::Tensor wino_B_t = wino_B.as_tensor_ref();
          ir::Tensor wino_G_t = wino_G.as_tensor_ref();
          ir::Tensor kernel_pack_t = kernel_pack.as_tensor_ref();
          ir::Tensor input_tile_t = input_tile.as_tensor_ref();
          ir::Tensor data_pack_t = data_pack.as_tensor_ref();
          ir::Tensor bgemm_t = bgemm.as_tensor_ref();
          ir::Tensor inverse_t = inverse.as_tensor_ref();
          ir::Tensor wino_conv_t = wino_conv.as_tensor_ref();
408 409 410 411 412 413 414 415 416 417 418 419
          std::vector<ir::Tensor> all_tensors = {wino_weights_dilation_t,
                                                 wino_input_pad_t,
                                                 wino_A_t,
                                                 wino_B_t,
                                                 wino_G_t,
                                                 kernel_pack_t,
                                                 input_tile_t,
                                                 data_pack_t,
                                                 bgemm_t,
                                                 inverse_t,
                                                 wino_conv_t};
          hlir::pe::CudaScheduleWinogradConv(stages, all_tensors, target);
420 421 422 423 424 425 426 427 428 429
          arg_pack[0] = Expr(all_tensors[0]);
          arg_pack[1] = Expr(all_tensors[1]);
          arg_pack[2] = Expr(all_tensors[2]);
          arg_pack[3] = Expr(all_tensors[3]);
          arg_pack[4] = Expr(all_tensors[4]);
          arg_pack[5] = Expr(all_tensors[5]);
          arg_pack[6] = Expr(all_tensors[6]);
          arg_pack[7] = Expr(all_tensors[7]);
          arg_pack[8] = Expr(all_tensors[8]);
          arg_pack[9] = Expr(all_tensors[9]);
430
          arg_pack[10] = Expr(all_tensors[10]);
431 432 433 434 435
          *ret = CINNValuePack{{arg_pack[10],
                                arg_pack[5],
                                arg_pack[7],
                                arg_pack[8],
                                CINNValue(stages)}};
436 437 438 439
          return;
        }
      } else if (target.arch == Target::Arch::X86) {
        if (arg_pack.size() == 6UL) {
440 441
          Expr res = arg_pack[0];
          Expr packed_out = arg_pack[1];
442
          Expr weights_dilation = arg_pack[2];
443 444
          Expr input_pad = arg_pack[3];
          Expr data = arg_pack[4];
445 446 447 448 449
          CHECK(res.as_tensor());
          CHECK(packed_out.as_tensor());
          CHECK(input_pad.as_tensor());
          CHECK(weights_dilation.as_tensor());
          CHECK(data.as_tensor());
450 451
          std::vector<Expr> kernel_shape =
              weights_dilation.as_tensor_ref()->shape;
452
          // kernel_h == 1 && kernel_w == 1
453 454 455 456
          CHECK_EQ(kernel_shape.size(), 6U)
              << "kernel_dialtion shape size should be 6";
          bool is_1x1 =
              (is_zero(kernel_shape[2] - 1)) && (is_zero(kernel_shape[3] - 1));
457
          ir::Tensor packed_out_tensor = packed_out.as_tensor_ref();
458
          bool do_padding = (padding[0] == 0 && padding[1] == 0) ? false : true;
459 460 461

          if (groups == 1) {
            if (is_1x1) {
462 463 464 465 466 467 468 469 470 471
              pe::Conv2d_NCHWc_1X1_Schedule_CPU(
                  stages,
                  res.as_tensor_ref(),
                  packed_out_tensor,
                  input_pad.as_tensor_ref(),
                  weights_dilation.as_tensor_ref(),
                  data.as_tensor_ref(),
                  target,
                  key,
                  do_padding);
472 473 474 475 476 477 478 479 480 481 482 483
            } else {
              pe::Conv2d_NCHWc_Schedule_CPU(stages,
                                            res.as_tensor_ref(),
                                            packed_out_tensor,
                                            input_pad.as_tensor_ref(),
                                            weights_dilation.as_tensor_ref(),
                                            data.as_tensor_ref(),
                                            target,
                                            key,
                                            do_padding);
            }
            if (do_padding) {
484 485 486 487 488
              *ret = CINNValuePack{{CINNValue(res),
                                    CINNValue(packed_out_tensor),
                                    arg_pack[2],
                                    arg_pack[3],
                                    CINNValue(stages)}};
489
            } else {
490 491 492 493
              *ret = CINNValuePack{{CINNValue(res),
                                    CINNValue(packed_out_tensor),
                                    arg_pack[2],
                                    CINNValue(stages)}};
494 495 496 497 498 499 500 501
            }
            return;
          } else {
            // todo: opt group_conv schedule
            VLOG(3) << "use simple group convolution schedule";
            stages[input_pad.as_tensor_ref()]->ComputeInline();
            stages[weights_dilation.as_tensor_ref()]->ComputeInline();
            stages[data.as_tensor_ref()]->ComputeInline();
502 503
            *ret = CINNValuePack{
                {arg_pack[0], CINNValue(packed_out_tensor), CINNValue(stages)}};
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
          }
          return;
        } else if (arg_pack.size() == 4UL) {
          Expr input_pad = arg_pack[1];
          CHECK(input_pad.as_tensor());
          stages[input_pad.as_tensor_ref()]->ComputeInline();
          Expr weights_dilation = arg_pack[2];
          CHECK(weights_dilation.as_tensor());
          stages[weights_dilation.as_tensor_ref()]->ComputeInline();
          *ret = CINNValuePack{{arg_pack[0], CINNValue(stages)}};
          return;
        }
      }
      *ret = arg_pack;
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
  CHECK(out_type.size()) << "Out_type of conv2d op is empty! Please check.";
  strategy->AddImpl(conv2d_compute, conv2d_schedule, "strategy.conv2d.x86", 1);
  return strategy;
}

527 528 529 530 531 532 533 534 535
std::vector<shape_t> InferShapeForConv2d(
    const std::vector<shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_shape.size(), 2)
      << "The conv2d should has and only has 2 inputs";
  CHECK_EQ(inputs_shape[0].size(), 4)
      << "The conv2d's first input only support 4-dimension tensor";
  CHECK_EQ(inputs_shape[1].size(), 4)
      << "The conv2d's first input only support 4-dimension tensor";
536 537 538 539

  std::vector<int> padding({0, 0});
  std::vector<int> stride({1, 1});
  std::vector<int> dilation({1, 1});
540
  int groups = 1;
541
  std::string data_format = "NCHW";
542
  std::string conv_type = "forward";
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

  if (attrs.find("padding") != attrs.end()) {
    padding = absl::get<std::vector<int>>(attrs.at("padding"));
  }
  if (attrs.find("stride") != attrs.end()) {
    stride = absl::get<std::vector<int>>(attrs.at("stride"));
  }
  if (attrs.find("dilation") != attrs.end()) {
    dilation = absl::get<std::vector<int>>(attrs.at("dilation"));
  }
  if (attrs.find("groups") != attrs.end()) {
    groups = absl::get<int>(attrs.at("groups"));
  }
  if (attrs.find("data_format") != attrs.end()) {
    data_format = absl::get<std::string>(attrs.at("data_format"));
    if (data_format == "AnyLayout") {
      data_format = "NCHW";
    }
  }
  if (attrs.find("conv_type") != attrs.end()) {
    conv_type = absl::get<std::string>(attrs.at("conv_type"));
  }

566 567 568 569 570 571 572 573 574 575
  CHECK_EQ(padding.size(), 2)
      << "The size of padding in conv2d op is not 2! Please check.";
  CHECK_EQ(stride.size(), 2)
      << "The size of stride in conv2d op is not 2! Please check.";
  CHECK_GE(inputs_shape[0].size(), 3) << "The first input tensor's shape size "
                                         "of conv2d op is < 3! Please check.";
  CHECK(conv_type == "forward" || conv_type == "backward_data" ||
        conv_type == "backward_filter")
      << "The conv type should be one of {forward, backward_data, "
         "backward_filter}.";
576 577 578 579 580 581 582 583 584 585 586 587 588 589
  CHECK(data_format == "NCHW" || data_format == "NHWC")
      << "The conv2d only support NCHW/NHWC, but here " << data_format;

  int n = 0, c = 1, h = 2, w = 3;
  if (data_format == "NHWC") {
    n = 0;
    h = 1;
    w = 2;
    c = 3;
  }

  std::vector<int> output_shape(4, 0);
  int out_shape_h = 0, out_shape_w = 0;
  if (conv_type == "forward") {
590 591 592 593 594 595 596 597 598 599 600 601
    // A is input: [N, C, H, W], B is filter: [C_out, C_in/group, filter_h,
    // filter_w]
    out_shape_h =
        (inputs_shape[0][h] - ((inputs_shape[1][h] - 1) * dilation[0] + 1) +
         2 * padding[0]) /
            stride[0] +
        1;
    out_shape_w =
        (inputs_shape[0][w] - ((inputs_shape[1][w] - 1) * dilation[1] + 1) +
         2 * padding[1]) /
            stride[1] +
        1;
602 603 604 605 606 607

    output_shape[n] = inputs_shape[0][n];
    output_shape[c] = inputs_shape[1][n];
    output_shape[h] = out_shape_h;
    output_shape[w] = out_shape_w;
  } else if (conv_type == "backward_data") {
608 609
    CHECK(attrs.find("output_shape") != attrs.end())
        << "The shape of backward_data is not found! Please check.";
610 611 612 613 614 615 616 617 618 619 620
    const auto &x_shape = absl::get<std::vector<int>>(attrs.at("output_shape"));
    CHECK_EQ(x_shape.size(), 4) << "The rank of x shape is not 4! Please check";

    // input[0] = w(C_out, C_in/group, h, w)
    // input[1] = dy(batch, C_out, h, w)
    // output = dx(batch, C_in, h, w)
    output_shape[n] = inputs_shape[1][n];
    output_shape[c] = inputs_shape[0][c] * groups;
    output_shape[h] = x_shape[h];
    output_shape[w] = x_shape[w];
  } else if (conv_type == "backward_filter") {
621 622 623 624 625 626
    CHECK(attrs.find("output_shape") != attrs.end())
        << "The shape of backward_filter is not found! Please check.";
    const auto &weight_shape =
        absl::get<std::vector<int>>(attrs.at("output_shape"));
    CHECK_EQ(weight_shape.size(), 4)
        << "The rank of weight shape is not 4! Please check";
627 628 629 630 631 632 633 634 635 636 637 638 639

    // input[0] = x(batch, C_in, h, w)
    // input[1] = dy(batch, C_out, h, w)
    // output = dw (C_out, C_in/group, h, w)
    output_shape[n] = inputs_shape[1][c];
    output_shape[c] = inputs_shape[0][c] / groups;
    output_shape[h] = weight_shape[h];
    output_shape[w] = weight_shape[w];
  }

  std::vector<shape_t> res = {output_shape};
  if (data_format == "NCHW") {
    absl::flat_hash_map<std::string, int> conv2d_factors;
640 641 642 643 644 645 646 647 648 649 650 651
    int batch = inputs_shape[0][0];
    int oc = inputs_shape[1][0];
    int ic = inputs_shape[0][1];
    int fc = inputs_shape[1][1];
    int h_in = inputs_shape[0][2];
    int w_in = inputs_shape[0][3];
    int h_f = inputs_shape[1][2];
    int w_f = inputs_shape[1][3];
    int pad_h = padding[0];
    int pad_w = padding[1];
    std::string key = pe::GenerateX86ConvKey(
        inputs_shape[0], inputs_shape[1], stride, padding, dilation);
652
    VLOG(3) << "key: " << key;
653 654 655 656 657 658 659 660 661
    pe::GetConv2dFactors(&conv2d_factors,
                         oc,
                         ic,
                         fc,
                         -1,
                         -1,
                         Float(32),
                         common::DefaultHostTarget(),
                         key);
662 663 664 665 666 667
    int ic_bn = conv2d_factors["ic_bn"];
    int oc_bn = conv2d_factors["oc_bn"];
    int fc_bn = conv2d_factors["fc_bn"];
    VLOG(3) << "ic_bn: " << ic_bn;
    VLOG(3) << "oc_bn: " << oc_bn;
    VLOG(3) << "fc_bn: " << fc_bn;
668 669 670 671 672 673 674 675 676 677 678 679 680
    int oc_chunk = oc / oc_bn;
    int ic_chunk = ic / ic_bn;
    int fc_chunk = fc / fc_bn;
    std::vector<int> packed_out_shape = {
        batch, oc_chunk, out_shape_h, out_shape_w, oc_bn};
    std::vector<int> input_pad_shape = {
        batch, ic_chunk, h_in + 2 * pad_h, w_in + 2 * pad_w, ic_bn};
    std::vector<int> weights_dilation_shape = {oc_chunk,
                                               fc_chunk,
                                               dilation[0] * (h_f - 1) + 1,
                                               dilation[1] * (w_f - 1) + 1,
                                               fc_bn,
                                               oc_bn};
681 682
    std::vector<int> data_shape = {batch, ic_chunk, h_in, w_in, ic_bn};

683 684 685 686
    res = {output_shape,
           packed_out_shape,
           weights_dilation_shape,
           input_pad_shape};
687 688 689 690 691 692 693
  } else if (data_format == "NHWC") {
    // now conv2d codegen version only support NCHW data format
    res = {output_shape};
  }
  return res;
}

694 695 696 697 698 699
std::vector<Type> InferDtypeForConv2d(const std::vector<Type> &inputs_type,
                                      const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
  std::vector<Type> res{
      inputs_type[0], inputs_type[0], inputs_type[0], inputs_type[0]};
700 701 702
  return res;
}

703 704 705 706 707 708 709
std::vector<std::vector<std::string>> InferLayoutForConv2d(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 2U)
      << "The input's layouts size is not 2! Please check again.";
710
  ir::Layout weight_layout(input_layouts[1]);
711 712 713
  return {
      {input_layouts[0], input_layouts[0], input_layouts[0], input_layouts[0]},
      input_layouts};
714 715
}

716 717 718 719 720 721
std::shared_ptr<OpStrategy> StrategyForConv2dNCHWc(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
722 723 724 725
  std::vector<int> padding({0, 0});
  std::vector<int> stride({1, 1});
  std::vector<int> dilation({1, 1});
  std::string data_format = "NCHWc";
726
  int groups = 1;
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  if (attrs.attr_store.find("padding") != attrs.attr_store.end()) {
    padding = absl::get<std::vector<int>>(attrs.attr_store.at("padding"));
  }
  if (attrs.attr_store.find("stride") != attrs.attr_store.end()) {
    stride = absl::get<std::vector<int>>(attrs.attr_store.at("stride"));
  }
  if (attrs.attr_store.find("dilation") != attrs.attr_store.end()) {
    dilation = absl::get<std::vector<int>>(attrs.attr_store.at("dilation"));
  }
  if (attrs.attr_store.find("data_format") != attrs.attr_store.end()) {
    data_format = absl::get<std::string>(attrs.attr_store.at("data_format"));
  }
  if (attrs.attr_store.find("groups") != attrs.attr_store.end()) {
    groups = absl::get<int>(attrs.attr_store.at("groups"));
  }
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
  CHECK(data_format == "NCHWc")
      << "conv2d_NCHWc op's data_format should be NCHWc";
  framework::CINNCompute conv2d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty()) << "The input argument of conv2d_NCHWc compute is "
                                "empty! Please check.\n";
        CINNValuePack a = args[0];
        CHECK_GE(a.size(), 2U)
            << "at least 2 input tensors for conv2d_NCHWc compute\n";
        Expr A = a[0];
        Expr B = a[1];
        CHECK(A.as_tensor());
        CHECK(B.as_tensor());
        auto tensor_a = A.as_tensor_ref();
        auto tensor_b = B.as_tensor_ref();
        CHECK_EQ(tensor_a->shape.size(), 5) << "input's shape should be 5";
        CHECK_EQ(tensor_b->shape.size(), 6) << "weight's shape should be 6";
        CHECK_EQ(padding.size(), 2)
            << "The size of padding in conv2d_NCHWc op is not 2! Please check.";
        CHECK_EQ(stride.size(), 2)
            << "The size of stride in conv2d_NCHWc op is not 2! Please check.";
        CHECK_EQ(dilation.size(), 2)
            << "The size of stride in conv2d_NCHWc op is not 2! Please check.";
        std::vector<ir::Tensor> out;
        CHECK(target.arch == Target::Arch::X86)
            << "conv2d_NCHWc op is only used in x86";
        // A is input: [N, C_in_outer, H, W, C_in_inner], B is filter: [C_out,
        // C_in_group_outer, filter_h, filter_w, C_in_group_inner]
        std::string key;
        VLOG(3) << "input[" << utils::Join(tensor_a->shape, ", ")
                << "], weight shape[" << utils::Join(tensor_b->shape, ", ")
                << "]";
        out = pe::Conv2d_NCHWc(tensor_a,
                               tensor_b,
                               padding[0],
                               padding[1],
                               stride[0],
                               stride[1],
                               dilation[0],
                               dilation[1],
                               UniqName("T_conv2d_NCHWc_out"),
                               target);

        auto stages = CreateStages({tensor_a, tensor_b});

        std::vector<CINNValue> res;
        CHECK(out.size() == 2U)
            << "The output tensor sizes of conv2d_NCHWc op should be 2\n";
        for (auto &t : out) {
          stages->InsertLazily(t);
          res.push_back(CINNValue(t));
        }
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });

  framework::CINNSchedule conv2d_schedule(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty()) << "The input argument of conv2d_NCHWc schedule "
                                "is empty! Please check.\n";
        CINNValuePack arg_pack = args[0];
        CHECK_EQ(arg_pack.size(), 3UL);
        poly::StageMap stages = arg_pack.back();
        Expr packed_out = arg_pack[0];
        Expr input_pad = arg_pack[1];
        CHECK(packed_out.as_tensor());
        CHECK(input_pad.as_tensor());
        std::vector<Expr> kernel_shape = inputs[1]->shape;
        // kernel_h == 1 && kernel_w == 1
        CHECK_EQ(kernel_shape.size(), 6U)
            << "kernel_dialtion shape size should be 6";
        bool is_1x1 =
            (is_zero(kernel_shape[2] - 1)) && (is_zero(kernel_shape[3] - 1));
        ir::Tensor res;
        ir::Tensor data;
        ir::Tensor weights;
        ir::Tensor packed_out_tensor = packed_out.as_tensor_ref();
        std::string key;
        bool do_padding = (padding[0] == 0 && padding[1] == 0) ? false : true;
        if (attrs.attr_store.find("key") != attrs.attr_store.end()) {
          key = absl::get<std::string>(attrs.attr_store.at("key"));
        }
        if (is_1x1) {
          pe::Conv2d_NCHWc_1X1_Schedule_CPU(stages,
                                            res,
                                            packed_out_tensor,
                                            input_pad.as_tensor_ref(),
                                            weights,
                                            data,
                                            target,
                                            key,
                                            do_padding);
        } else {
          pe::Conv2d_NCHWc_Schedule_CPU(stages,
                                        res,
                                        packed_out_tensor,
                                        input_pad.as_tensor_ref(),
                                        weights,
                                        data,
                                        target,
                                        key,
                                        do_padding);
        }
        if (do_padding) {
          *ret = CINNValuePack{{CINNValue(packed_out_tensor),
                                arg_pack[0],
                                arg_pack[1],
                                CINNValue(stages)}};
        } else {
          *ret = CINNValuePack{
              {CINNValue(packed_out_tensor), arg_pack[0], CINNValue(stages)}};
        }
      });
855 856

  auto strategy = std::make_shared<framework::OpStrategy>();
857 858
  CHECK(out_type.size())
      << "Out_type of conv2d_NCHWc op is empty! Please check.";
859
  if (out_type[0] == Float(32)) {
860 861
    strategy->AddImpl(
        conv2d_compute, conv2d_schedule, "strategy.conv2d_NCHWc.x86", 1);
862
  } else {
863 864
    LOG(FATAL)
        << "conv2d_NCHWc op with dtype != float32 is not implemented yet!";
865 866 867 868
  }
  return strategy;
}

869 870 871 872 873
std::vector<shape_t> InferShapeForConv2dNCHWc(
    const std::vector<shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty() && !inputs_shape[0].empty())
      << "The input's shape size is 0! Please check again.";
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  std::vector<int> padding({0, 0});
  std::vector<int> stride({1, 1});
  std::vector<int> dilation({1, 1});
  std::string data_format = "NCHWc";
  if (attrs.find("padding") != attrs.end()) {
    padding = absl::get<std::vector<int>>(attrs.at("padding"));
  }
  if (attrs.find("stride") != attrs.end()) {
    stride = absl::get<std::vector<int>>(attrs.at("stride"));
  }
  if (attrs.find("dilation") != attrs.end()) {
    dilation = absl::get<std::vector<int>>(attrs.at("dilation"));
  }
  if (attrs.find("data_format") != attrs.end()) {
    data_format = absl::get<std::string>(attrs.at("data_format"));
  }
890 891 892 893
  CHECK_EQ(padding.size(), 2)
      << "The size of padding in conv2d_NCHWc op is not 2! Please check.";
  CHECK_EQ(stride.size(), 2)
      << "The size of stride in conv2d_NCHWc op is not 2! Please check.";
894
  CHECK_EQ(inputs_shape[0].size(), 5)
895 896
      << "The first input tensor's shape size of conv2d_NCHWc op should be 5! "
         "Please check.";
897
  CHECK_EQ(inputs_shape[1].size(), 6)
898 899
      << "The second input tensor's shape size of conv2d_NCHWc op should be 6! "
         "Please check.";
900 901 902 903

  std::vector<shape_t> res;
  CHECK(data_format == "NCHWc") << "NCHWc op's data_format should be NCHWc";
  int out_shape_h =
904 905 906 907
      (inputs_shape[0][2] - ((inputs_shape[1][2] - 1) * dilation[0] + 1) +
       2 * padding[0]) /
          stride[0] +
      1;
908
  int out_shape_w =
909 910 911 912
      (inputs_shape[0][3] - ((inputs_shape[1][3] - 1) * dilation[1] + 1) +
       2 * padding[1]) /
          stride[1] +
      1;
913 914

  // A: NCHWc, B: OIHWio
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
  int batch = inputs_shape[0][0];
  int h_in = inputs_shape[0][2];
  int w_in = inputs_shape[0][3];
  int oc = inputs_shape[1][0];
  int h_f = inputs_shape[1][2];
  int w_f = inputs_shape[1][3];
  int pad_h = padding[0];
  int pad_w = padding[1];
  int ic_bn = inputs_shape[0][4];
  int ic_chunk = inputs_shape[0][1];
  int oc_bn = inputs_shape[1][5];
  int oc_chunk = inputs_shape[1][0];
  std::vector<int> packed_out_shape = {
      batch, oc_chunk, out_shape_h, out_shape_w, oc_bn};
  auto pad_h_bound =
      (out_shape_h - 1) * stride[0] + (h_f - 1) * dilation[0] + 1;
  auto pad_w_bound =
      (out_shape_w - 1) * stride[1] + (w_f - 1) * dilation[1] + 1;
  auto input_pad_h = std::min(pad_h_bound, h_in + 2 * pad_h);
  auto input_pad_w = std::min(pad_w_bound, w_in + 2 * pad_w);
  std::vector<int> input_pad_shape = {
      batch, ic_chunk, input_pad_h, input_pad_w, ic_bn};
937 938 939 940
  VLOG(3) << "packed_out_shape: " << utils::Join(packed_out_shape, ", ");
  return {packed_out_shape, packed_out_shape, input_pad_shape};
}

941 942 943 944 945 946 947
std::vector<std::vector<std::string>> InferLayoutForConv2dNCHWc(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 2U)
      << "The input's layouts size is not 2! Please check again.";
948 949
  ir::Layout weight_layout(input_layouts[1]);
  CHECK_EQ(weight_layout.ndims(), 6U);
950
  auto var = weight_layout.axes().back();
951 952 953 954 955 956
  int factor = var->upper_bound.as_int32();
  CHECK_GE(factor, 1) << "factor should be larger than 1";
  std::string outlayout = "NCHW" + std::to_string(factor) + "c";
  return {{outlayout, outlayout, input_layouts[0]}, input_layouts};
}

957 958 959 960
std::vector<Type> InferDtypeForConv2dNCHWc(
    const std::vector<Type> &inputs_type, const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
961 962 963 964
  std::vector<Type> res{inputs_type[0], inputs_type[0], inputs_type[0]};
  return res;
}

965 966 967 968 969 970 971 972
std::shared_ptr<OpStrategy> StrategyForDepthwiseConv2d(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  std::vector<int> padding = {0, 0};
  std::vector<int> stride = {1, 1};
973
  std::vector<int> dilation = {1, 1};
974
  std::string data_format = "NCHW";
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
  std::string key;
  if (attrs.attr_store.find("padding") != attrs.attr_store.end()) {
    padding = absl::get<std::vector<int>>(attrs.attr_store.at("padding"));
  }
  if (attrs.attr_store.find("stride") != attrs.attr_store.end()) {
    stride = absl::get<std::vector<int>>(attrs.attr_store.at("stride"));
  }
  if (attrs.attr_store.find("data_format") != attrs.attr_store.end()) {
    data_format = absl::get<std::string>(attrs.attr_store.at("data_format"));
  }
  if (attrs.attr_store.find("dilation") != attrs.attr_store.end()) {
    dilation = absl::get<std::vector<int>>(attrs.attr_store.at("dilation"));
  }
  if (attrs.attr_store.find("key") != attrs.attr_store.end()) {
    key = absl::get<std::string>(attrs.attr_store.at("key"));
  }

992 993 994 995
  framework::CINNCompute depthwise_conv2d_compute([=](lang::Args args,
                                                      lang::RetValue *ret) {
    CHECK(!args.empty()) << "The input argument of depthwise_conv compute is "
                            "empty! Please check.\n";
996
    CINNValuePack pack_args = args[0];
997 998
    CHECK_GE(pack_args.size(), 2U)
        << "at least 2 input tensors for depthwise_conv compute\n";
999 1000 1001 1002
    Expr A = pack_args[0];
    Expr B = pack_args[1];
    CHECK(A.as_tensor());
    CHECK(B.as_tensor());
1003 1004 1005 1006 1007 1008
    CHECK_EQ(padding.size(), 2)
        << "The size of padding in depthwise_conv op is not 2! Please check.\n";
    CHECK_EQ(stride.size(), 2)
        << "The size of stride in depthwise_conv op is not 2! Please check.\n";
    CHECK(data_format == "NCHW" || data_format == "NHWC")
        << "only support NCHW/NHWC data_format.\n";
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    std::vector<ir::Tensor> out;
    std::string tensor_name = UniqName("Depthwise_Conv2d_out");
    if (FLAGS_cinn_ir_schedule) {
      CHECK_GE(pack_args.size(), 3);
      CHECK(pack_args[2].is_string());
      tensor_name = pack_args[2].operator std::string();
    }
    if (data_format == "NCHW") {
      if (target.arch == Target::Arch::X86) {
        out = pe::Conv2d_NCHW_5D(A.as_tensor_ref(),
                                 B.as_tensor_ref(),
                                 padding[0],
                                 padding[1],
                                 stride[0],
                                 stride[1],
                                 dilation[0],
                                 dilation[1],
                                 key,
                                 tensor_name,
                                 target);
      } else {
1030 1031 1032 1033 1034 1035 1036
        out = pe::Depthwise_Conv2d_NCHW(A.as_tensor_ref(),
                                        B.as_tensor_ref(),
                                        padding[0],
                                        padding[1],
                                        stride[0],
                                        stride[1],
                                        tensor_name);
1037 1038
      }
    } else if (data_format == "NHWC") {
1039 1040 1041 1042 1043 1044 1045
      out = pe::Depthwise_Conv2d_NHWC(A.as_tensor_ref(),
                                      B.as_tensor_ref(),
                                      padding[0],
                                      padding[1],
                                      stride[0],
                                      stride[1],
                                      tensor_name);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    } else {
      LOG(FATAL) << "Only support NCHW and NHWC data layout\n";
    }

    auto stages = CreateStages({A.as_tensor_ref(), B.as_tensor_ref()});
    std::vector<CINNValue> res;
    for (auto &t : out) {
      stages->InsertLazily(t);
      res.push_back(CINNValue(t));
    }
    CHECK(out.size() == 2U || out.size() == 1U || out.size() == 5U)
1057 1058
        << "The output tensor sizes of depthwise_conv op in depthwise_conv op "
           "should be 1 or 2 or 5\n";
1059 1060 1061 1062
    res.push_back(CINNValue(stages));
    *ret = CINNValuePack{res};
  });

1063 1064
  framework::CINNSchedule depthwise_conv2d_schedule([=](lang::Args args,
                                                        lang::RetValue *ret) {
1065
    if (FLAGS_cinn_ir_schedule) {
1066 1067
      CHECK(!args.empty()) << "The input argument of InjectiveSchedule is "
                              "empty! Please check.\n";
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
      common::CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      std::vector<Expr> vec_tensor;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        } else if (arg_pack[i].is_tensor()) {
          Expr temp = arg_pack[i];
          vec_tensor.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (target.arch == Target::Arch::NVGPU) {
        pe::IRCudaScheduleDepthwiseConv(ir_sch, vec_tensor);
      } else {
        CINN_NOT_IMPLEMENTED
      }
1089 1090
      std::vector<common::CINNValue> res{
          common::CINNValue(ir_sch.GetModule().GetExprs().at(0))};
1091 1092
      *ret = common::CINNValuePack{res};
    } else {
1093 1094
      CHECK(!args.empty()) << "The input argument of depthwise_conv schedule "
                              "is empty! Please check.\n";
1095
      CINNValuePack arg_pack = args[0];
1096 1097
      CHECK(arg_pack.size() == 2UL || arg_pack.size() == 3UL ||
            arg_pack.size() == 6UL);
1098
      poly::StageMap stages = arg_pack[arg_pack.size() - 1];
1099
      Expr Out = arg_pack[0];
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
      CHECK(Out.as_tensor());
      if (arg_pack.size() == 3UL) {
        Expr input_pad = arg_pack[1];
        CHECK(input_pad.as_tensor());
        stages[input_pad.as_tensor_ref()]->ComputeInline();
      }
      if (target.arch == Target::Arch::NVGPU) {
        ir::Tensor output = Out.as_tensor_ref();
        CHECK(Out.as_tensor());
        pe::CudaScheduleDepthwiseConv(stages, output, target);
        arg_pack[0] = Expr(output);
      } else if (target.arch == Target::Arch::X86) {
        if (arg_pack.size() == 6UL) {
1113 1114
          Expr res = arg_pack[0];
          Expr packed_out = arg_pack[1];
1115
          Expr weights_dilation = arg_pack[2];
1116 1117
          Expr input_pad = arg_pack[3];
          Expr data = arg_pack[4];
1118 1119 1120 1121 1122 1123
          CHECK(res.as_tensor());
          CHECK(packed_out.as_tensor());
          CHECK(input_pad.as_tensor());
          CHECK(weights_dilation.as_tensor());
          CHECK(data.as_tensor());
          ir::Tensor packed_out_tensor = packed_out.as_tensor_ref();
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
          bool do_padding = (padding[0] == 0 && padding[1] == 0) ? false : true;
          pe::Depthwise_Conv2d_NCHWc_Schedule_CPU_Nofuse(
              stages,
              res.as_tensor_ref(),
              packed_out_tensor,
              input_pad.as_tensor_ref(),
              weights_dilation.as_tensor_ref(),
              data.as_tensor_ref(),
              target,
              do_padding);
1134
          if (do_padding) {
1135 1136 1137 1138 1139
            *ret = CINNValuePack{{CINNValue(res),
                                  CINNValue(packed_out_tensor),
                                  arg_pack[2],
                                  arg_pack[3],
                                  CINNValue(stages)}};
1140
          } else {
1141 1142 1143 1144
            *ret = CINNValuePack{{CINNValue(res),
                                  CINNValue(packed_out_tensor),
                                  arg_pack[2],
                                  CINNValue(stages)}};
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
          }
          return;
        }
      }

      *ret = CINNValuePack{{arg_pack[0], CINNValue(stages)}};
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
1155 1156
  CHECK(out_type.size())
      << "Out_type of depthwise_conv op is empty! Please check.";
1157
  if (out_type[0] == Float(32)) {
1158 1159 1160 1161
    strategy->AddImpl(depthwise_conv2d_compute,
                      depthwise_conv2d_schedule,
                      "strategy.depthwise_conv.x86",
                      1);
1162
  } else {
1163 1164
    VLOG(3)
        << "depthwise_conv op with dtype != float32 is not implemented yet!";
1165 1166 1167 1168
  }
  return strategy;
}

1169 1170 1171 1172 1173 1174 1175 1176 1177
std::vector<shape_t> InferShapeForDepthwiseConv2d(
    const std::vector<shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_shape.size(), 2U)
      << "at least 2 input tensors for depthwise_conv2d op\n";
  CHECK_EQ(inputs_shape[0].size(), 4U)
      << "The input tensor's shape should be 4! Please check again.";
  CHECK_EQ(inputs_shape[1].size(), 4U)
      << "The input tensor's shape should be 4! Please check again.";
1178
  std::vector<int> padding = {0, 0};
1179 1180
  std::vector<int> stride = {1, 1};
  std::string data_format = "NCHW";
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
  if (attrs.find("padding") != attrs.end()) {
    padding = absl::get<std::vector<int>>(attrs.at("padding"));
  }
  if (attrs.find("stride") != attrs.end()) {
    stride = absl::get<std::vector<int>>(attrs.at("stride"));
  }
  if (attrs.find("data_format") != attrs.end()) {
    data_format = absl::get<std::string>(attrs.at("data_format"));
  }
  std::vector<shape_t> res;
1191 1192 1193 1194
  CHECK_EQ(padding.size(), 2U)
      << "The size of padding in depthwise_conv2d op is not 2! Please check.";
  CHECK_EQ(stride.size(), 2U)
      << "The size of stride in depthwise_conv2d op is not 2! Please check.";
1195
  if (data_format == "NCHW") {
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    // A is input: [N, C, H, W], and B is filter: [C_in, channel_multiplier,
    // f_h, f_w]
    int out_shape_h =
        (inputs_shape[0][2] - inputs_shape[1][2] + 2 * padding[0]) / stride[0] +
        1;
    int out_shape_w =
        (inputs_shape[0][3] - inputs_shape[1][3] + 2 * padding[1]) / stride[1] +
        1;
    res = {{inputs_shape[0][0],
            inputs_shape[1][1] * inputs_shape[0][1],
            out_shape_h,
            out_shape_w}};
1208
  } else if (data_format == "NHWC") {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    // A is input: [N, H, W, C], and B is filter: [C_in, channel_multiplier,
    // f_h, f_w]
    int out_shape_h =
        (inputs_shape[0][1] - inputs_shape[1][1] + 2 * padding[0]) / stride[0] +
        1;
    int out_shape_w =
        (inputs_shape[0][2] - inputs_shape[1][2] + 2 * padding[1]) / stride[1] +
        1;
    res = {{inputs_shape[0][0],
            out_shape_h,
            out_shape_w,
            inputs_shape[1][1] * inputs_shape[0][3]}};
1221 1222 1223 1224 1225 1226
  } else {
    LOG(FATAL) << "Only support NCHW and NHWC data layout\n";
  }
  return res;
}

1227 1228 1229 1230
std::vector<Type> InferDtypeForDepthwiseConv2d(
    const std::vector<Type> &inputs_type, const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
1231 1232 1233 1234
  std::vector<Type> res{inputs_type[0]};
  return res;
}

1235 1236 1237 1238 1239 1240
std::shared_ptr<OpStrategy> StrategyForBatchNorm(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
1241 1242 1243 1244 1245 1246
  float epsilon = 0.00001f;
  std::vector<std::string> input_layouts;
  if (attrs.attr_store.find("epsilon") != attrs.attr_store.end()) {
    epsilon = absl::get<float>(attrs.attr_store.at("epsilon"));
  }
  if (attrs.attr_store.find("input_layouts") != attrs.attr_store.end()) {
1247 1248
    input_layouts = absl::get<std::vector<std::string>>(
        attrs.attr_store.at("input_layouts"));
1249
  }
1250 1251 1252 1253
  framework::CINNCompute batchnorm_compute([=](lang::Args args,
                                               lang::RetValue *ret) {
    CHECK(!args.empty())
        << "The input argument of batchnorm compute is empty! Please check.\n";
1254
    CINNValuePack arg_pack = args[0];
1255 1256 1257 1258 1259 1260 1261
    CHECK_GE(arg_pack.size(), 5U)
        << "at least 5 input tensors for batchnorm compute\n";
    Expr A = arg_pack[0];
    Expr Scale = arg_pack[1];
    Expr Bias = arg_pack[2];
    Expr Mean = arg_pack[3];
    Expr Variance = arg_pack[4];
1262 1263 1264 1265 1266
    std::string out_name = UniqName("BatchNorm_output");
    if (FLAGS_cinn_ir_schedule) {
      CHECK_EQ(arg_pack.size(), 6U);
      CHECK(arg_pack[5].is_string());
      std::string str = arg_pack[5];
1267
      out_name = str;
1268 1269 1270 1271 1272 1273 1274 1275 1276
    }
    CHECK(A.as_tensor());
    CHECK(Scale.as_tensor());
    CHECK(Bias.as_tensor());
    CHECK(Mean.as_tensor());
    CHECK(Variance.as_tensor());
    ir::Tensor out;
    auto tensor_input = A.as_tensor_ref();
    if (tensor_input->shape.size() != 4 && target.arch == Target::Arch::X86) {
1277 1278
      CHECK_EQ(input_layouts.size(), 5U)
          << "batch_norm_NCHWc's input layout should be 5";
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
      std::string input_layout = input_layouts[0];
      CHECK_GE(input_layout.size(), 5U);
      CHECK_EQ(input_layout.substr(0, 4), "NCHW");
      CHECK_EQ(tensor_input->shape.size(), 5U);
      out = pe::BatchNorm_NCHWc(tensor_input,
                                Scale.as_tensor_ref(),
                                Bias.as_tensor_ref(),
                                Mean.as_tensor_ref(),
                                Variance.as_tensor_ref(),
                                epsilon,
                                out_name);
    } else {
      out = pe::BatchNorm_NCHW(tensor_input,
                               Scale.as_tensor_ref(),
                               Bias.as_tensor_ref(),
                               Mean.as_tensor_ref(),
                               Variance.as_tensor_ref(),
                               epsilon,
                               out_name);
    }
    auto stages = CreateStages({out});
1300
    *ret = CINNValuePack{{CINNValue(out), CINNValue(stages)}};
1301 1302 1303 1304 1305
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
  CHECK(out_type.size()) << "Out_type of batchnorm op is empty! Please check.";
  if (out_type[0] == Float(32)) {
1306 1307 1308 1309
    strategy->AddImpl(batchnorm_compute,
                      GetInjectiveScheduleFunc(output_shapes, target),
                      "strategy.batchnorm.x86",
                      1);
1310 1311 1312 1313 1314 1315
  } else {
    LOG(FATAL) << "BatchNorm op with dtype != float32 is not implemented yet!";
  }
  return strategy;
}

1316 1317 1318 1319 1320
std::vector<shape_t> InferShapeForBatchNorm(
    const std::vector<shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty() && !inputs_shape[0].empty())
      << "The input's shape size is 0! Please check again.";
1321 1322 1323 1324
  std::vector<shape_t> res{inputs_shape[0]};
  return res;
}

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
std::vector<Type> InferDtypeForBatchNorm(const std::vector<Type> &inputs_type,
                                         const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_type.size(), 5U) << "The BatchNorm Infer input's type size "
                                      "should be 5! Please check again.";
  CHECK_EQ(inputs_type[1], inputs_type[2])
      << "The BatchNorm Infer scale type should the same as bias type";
  CHECK_EQ(inputs_type[1], inputs_type[3])
      << "The BatchNorm Infer scale type should the same as moving_mean type";
  CHECK_EQ(inputs_type[1], inputs_type[4])
      << "The BatchNorm Infer scale type should the same as moving_variance "
         "type";
1336 1337 1338 1339
  std::vector<Type> res{inputs_type[0]};
  return res;
}

1340 1341 1342 1343 1344 1345 1346
std::vector<std::vector<std::string>> InferLayoutForBatchNorm(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 5U)
      << "The input's layouts size is not 5! Please check again.";
1347
  std::string input_layout = input_layouts[0];
1348 1349
  CHECK_GE(input_layout.size(), 4)
      << "batchnorm's first input layout size should be >= 4";
1350 1351 1352
  return {{input_layout}, input_layouts};
}

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
std::shared_ptr<OpStrategy> StrategyForPool1d(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  framework::CINNCompute pool1d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of pool1d compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK(!pack_args.empty())
            << "The input tensor of pool1d compute is empty! Please check.\n";
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        auto attr_store = attrs.attr_store;
        std::vector<int> kernel_size;   // [kernel_w]
        std::vector<int> stride_size;   // [stride_w]
        std::vector<int> padding_size;  // [padding_left, padding_right]
        std::string pool_type = "max";
        bool ceil_mode = false;
        bool exclusive = true;
        std::string data_format = "NCW";
        for (auto &iter : attrs.attr_store) {
          if (iter.first == "kernel_size") {
            kernel_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "stride_size") {
            stride_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "padding_size") {
            padding_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "pool_type") {
            pool_type = absl::get<std::string>(iter.second);
          } else if (iter.first == "ceil_mode") {
            ceil_mode = absl::get<bool>(iter.second);
          } else if (iter.first == "exclusive") {
            exclusive = absl::get<bool>(iter.second);
          } else if (iter.first == "data_format") {
            data_format = absl::get<std::string>(iter.second);
          } else {
            LOG(ERROR) << "Unsupported attr: " << iter.first << std::endl;
          }
        }
        CHECK(!kernel_size.empty())
            << "kernel_size for pool1d is empty. Please check.\n";
        CHECK(!stride_size.empty())
            << "stride_size for pool1d is empty. Please check.\n";
        CHECK(!padding_size.empty())
            << "padding_size for pool1d is empty. Please check.\n";
        CHECK(pool_type == "max" || pool_type == "avg")
            << "pool_type for pool1d should be max or avg.\n";

        std::string tensor_name = UniqName("Pool1d_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
1410

1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        auto out = pe::Pool1d(A.as_tensor_ref(),
                              kernel_size,
                              stride_size,
                              padding_size,
                              pool_type,
                              ceil_mode,
                              exclusive,
                              data_format,
                              tensor_name);

        auto stages = CreateStages(out);
        CHECK(out.size() == 1U || out.size() == 2U)
            << "The size of pe::Pool1d's output should be 1 or 2.";
        CHECK(!out_type.empty())
            << "Output type of Pool1d is empty! Please check.\n";
        std::vector<CINNValue> res;
        for (auto &t : out) {
          res.push_back(CINNValue(Expr(t.get())));
        }
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });
1433

1434 1435
  framework::CINNSchedule pool1d_schedule([=](lang::Args args,
                                              lang::RetValue *ret) {
1436
    if (FLAGS_cinn_ir_schedule) {
1437 1438
      CHECK(!args.empty())
          << "The input argument of pool1d schedule is empty! Please check.\n";
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      std::vector<Expr> vec_tensor;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        } else if (arg_pack[i].is_tensor()) {
          Expr temp = arg_pack[i];
          vec_tensor.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (arg_pack.size() == 3UL) {
        CHECK_EQ(vec_tensor.size(), 2);
        Expr input_pad = vec_tensor[1];
        CHECK(input_pad.as_tensor());
        auto block_input_pad = ir_sch.GetBlock(input_pad.as_tensor()->name);
        ir_sch.ComputeInline(block_input_pad);
      }
      if (target.arch == Target::Arch::NVGPU) {
        CHECK(!vec_tensor.empty());
        Expr Out = vec_tensor[0];
        CHECK(Out.as_tensor());
        auto loops = ir_sch.GetLoops(Out.as_tensor()->name);
        ir_sch.Split(loops[1], {-1, 2});
        loops = ir_sch.GetLoops(Out.as_tensor()->name);
        ir_sch.Bind(loops[0], "blockIdx.x");
        ir_sch.Bind(loops[1], "threadIdx.x");
      }
1472 1473
      std::vector<CINNValue> res{
          CINNValue(ir_sch.GetModule().GetExprs().at(0))};
1474 1475
      *ret = CINNValuePack{res};
    } else {
1476 1477
      CHECK(!args.empty())
          << "The input argument of pool1d schedule is empty! Please check.\n";
1478 1479
      CINNValuePack arg_pack = args[0];
      CHECK(arg_pack.size() == 2UL || arg_pack.size() == 3UL);
1480
      Expr Out = arg_pack[0];
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
      poly::StageMap stages = arg_pack[arg_pack.size() - 1];
      if (arg_pack.size() == 3UL) {
        Expr input_pad = arg_pack[1];
        CHECK(input_pad.as_tensor());
        stages[input_pad.as_tensor_ref()]->ComputeInline();
      }

      if (target.arch == Target::Arch::NVGPU) {
        CHECK(Out.as_tensor());
        stages[Out.as_tensor_ref()]->Split(1, 2);
        stages[Out.as_tensor_ref()]->Bind(0, "blockIdx.x");
        stages[Out.as_tensor_ref()]->Bind(1, "threadIdx.x");
      }
      *ret = CINNValuePack{{CINNValue(Out), CINNValue(stages)}};
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
  strategy->AddImpl(pool1d_compute, pool1d_schedule, "strategy.pool1d.x86", 1);

  return strategy;
}

1504 1505 1506 1507 1508
std::vector<std::vector<int>> InferShapeForPool1d(
    const std::vector<std::vector<int>> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty() && !inputs_shape[0].empty())
      << "The input's shape size is 0! Please check again.";
1509 1510 1511
  std::vector<int> kernel_size;   // [kernel_w]
  std::vector<int> stride_size;   // [stride_w]
  std::vector<int> padding_size;  // [padding_left, padding_right]
1512 1513 1514
  std::string pool_type = "max";
  bool ceil_mode = false;
  bool exclusive = true;
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
  std::string data_format = "NCW";
  for (auto &iter : attrs) {
    if (iter.first == "kernel_size") {
      kernel_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "stride_size") {
      stride_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "padding_size") {
      padding_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "ceil_mode") {
      ceil_mode = absl::get<bool>(iter.second);
    } else if (iter.first == "exclusive") {
      exclusive = absl::get<bool>(iter.second);
    } else if (iter.first == "data_format") {
      data_format = absl::get<std::string>(iter.second);
    }
  }
  CHECK_EQ(kernel_size.size(), 1U) << "kernel size for pool1d should be 1.\n";
1532 1533 1534 1535 1536 1537
  CHECK_EQ(stride_size.size(), 1U)
      << "stride_size size for pool1d should be 1.\n";
  CHECK_EQ(padding_size.size(), 2U)
      << "padding_size size for pool1d should be 2.\n";
  CHECK(pool_type == "max" || pool_type == "avg")
      << "pool_type for pool1d should be max or avg.\n";
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551

  std::vector<int> output_shape1 = inputs_shape[0];
  CHECK_EQ(output_shape1.size(), 3U);
  int width_axis = -1;
  if (data_format == "NCW") {
    width_axis = 2;
  } else if (data_format == "NWC") {
    width_axis = 1;
  } else {
    LOG(FATAL) << "unsupported data_format: " << data_format << std::endl;
  }

  if (ceil_mode) {
    output_shape1[width_axis] =
1552 1553
        (inputs_shape[0][width_axis] - kernel_size[0] + padding_size[0] +
         padding_size[1] + stride_size[0] - 1) /
1554 1555 1556
            stride_size[0] +
        1;
  } else {
1557 1558 1559 1560
    output_shape1[width_axis] = (inputs_shape[0][width_axis] - kernel_size[0] +
                                 padding_size[0] + padding_size[1]) /
                                    stride_size[0] +
                                1;
1561 1562 1563 1564 1565 1566
  }

  std::vector<std::vector<int>> res{output_shape1};
  return res;
}

1567 1568 1569 1570 1571 1572
std::shared_ptr<OpStrategy> StrategyForPool2d(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
1573 1574 1575
  auto attr_store = attrs.attr_store;
  std::vector<int> kernel_size;   // [kernel_h, kernel_w]
  std::vector<int> stride_size;   // [stride_h, stride_w]
1576 1577 1578 1579 1580 1581 1582
  std::vector<int> padding_size;  // [padding_top, padding_left, padding_bottom,
                                  // padding_right]
  std::string pool_type = "max";
  bool ceil_mode = false;
  bool exclusive = true;
  bool global_pooling = false;
  bool adaptive = false;
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
  std::string data_format = "NCHW";
  for (auto &iter : attrs.attr_store) {
    if (iter.first == "kernel_size") {
      kernel_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "stride_size") {
      stride_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "padding_size") {
      padding_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "pool_type") {
      pool_type = absl::get<std::string>(iter.second);
    } else if (iter.first == "ceil_mode") {
      ceil_mode = absl::get<bool>(iter.second);
    } else if (iter.first == "exclusive") {
      exclusive = absl::get<bool>(iter.second);
    } else if (iter.first == "data_format") {
      data_format = absl::get<std::string>(iter.second);
    } else if (iter.first == "global_pooling") {
      global_pooling = absl::get<bool>(iter.second);
    } else if (iter.first == "adaptive") {
      adaptive = absl::get<bool>(iter.second);
    }
  }
  // It can be removed after fixing the global_pool2d problem
  if (attr_store.count("origin_kernel_size")) {
1607 1608
    kernel_size =
        absl::get<std::vector<int>>(attr_store.at("origin_kernel_size"));
1609 1610
  }
  if (attr_store.count("origin_padding_size")) {
1611 1612
    padding_size =
        absl::get<std::vector<int>>(attr_store.at("origin_padding_size"));
1613 1614 1615 1616 1617 1618 1619 1620
  }
  if (attr_store.count("origin_global_pooling")) {
    global_pooling = absl::get<bool>(attr_store.at("origin_global_pooling"));
  }
  if (attr_store.count("origin_adaptive")) {
    adaptive = absl::get<bool>(attr_store.at("origin_adaptive"));
  }

1621 1622 1623 1624 1625 1626 1627 1628
  CHECK(!kernel_size.empty())
      << "kernel_size for pool2d is empty. Please check.\n";
  CHECK(!stride_size.empty())
      << "stride_size for pool2d is empty. Please check.\n";
  CHECK(!padding_size.empty())
      << "padding_size for pool2d is empty. Please check.\n";
  CHECK(pool_type == "max" || pool_type == "avg")
      << "pool_type for pool2d should be max or avg.\n";
1629

1630 1631
  CHECK(!inputs.empty())
      << "The input tensor of pool2d compute is empty! Please check.\n";
1632 1633 1634 1635 1636 1637
  const ir::Tensor &A_tensor = inputs[0];
  CHECK(A_tensor->shape.size() == 4U || A_tensor->shape.size() == 5U)
      << "pool2d requires tensor's shape_size to be 4 or 5\n";

  if (global_pooling) {
    int height_index = -1;
1638
    int width_index = -1;
1639 1640
    if (data_format == "NCHW") {
      height_index = 2;
1641
      width_index = 3;
1642 1643
    } else if (data_format == "NHWC") {
      height_index = 1;
1644
      width_index = 2;
1645 1646
    } else if (data_format == "AnyLayout") {
      height_index = 2;
1647 1648
      width_index = 3;
      data_format = "NCHW";
1649
    } else {
1650 1651
      LOG(FATAL)
          << "Only support 'NCHW' or 'NHWC' or 'AnyLayout' data_format.\n";
1652
    }
1653 1654
    kernel_size = {A_tensor->shape[height_index].as_int32(),
                   A_tensor->shape[width_index].as_int32()};
1655 1656 1657
    padding_size = {0, 0, 0, 0};
  }
  if (kernel_size.size() == padding_size.size()) {
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
    padding_size.insert(
        padding_size.end(), padding_size.begin(), padding_size.end());
  }

  framework::CINNCompute global_pool2d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of pool2d compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        ir::Tensor A_tensor = A.as_tensor_ref();

        std::string tensor_name = UniqName("GlobalPool2d_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
1677

1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
        auto out = pe::GlobalPool2d(A_tensor, pool_type, tensor_name);
        CHECK(out.size() == 2U)
            << "The size of pe::GlobalPool2d's output should be 2.";
        auto stages = CreateStages({A_tensor, out[0], out[1]});
        *ret = CINNValuePack{
            {CINNValue(out[0]), CINNValue(out[1]), CINNValue(stages)}};
      });

  framework::CINNSchedule global_pool2d_schedule([=](lang::Args args,
                                                     lang::RetValue *ret) {
    CHECK(!args.empty())
        << "The input argument of pool2d schedule is empty! Please check.\n";
1690
    if (FLAGS_cinn_ir_schedule) {
1691 1692
      CHECK(!args.empty())
          << "The input argument of pool1d schedule is empty! Please check.\n";
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      std::vector<Expr> vec_tensor;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        } else if (arg_pack[i].is_tensor()) {
          Expr temp = arg_pack[i];
          vec_tensor.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (target.arch == Target::Arch::NVGPU) {
        pe::IRGlobalPoolScheduleGPU(ir_sch, target);
      } else {
        CINN_NOT_IMPLEMENTED
      }
1714 1715
      std::vector<CINNValue> res{
          CINNValue(ir_sch.GetModule().GetExprs().at(0))};
1716 1717 1718
      *ret = CINNValuePack{res};
    } else {
      CINNValuePack arg_pack = args[0];
1719
      CHECK_EQ(arg_pack.size(), 3UL);
1720
      Expr out = arg_pack[0];
1721 1722 1723
      Expr reduce = arg_pack[1];
      CHECK(out.as_tensor() && reduce.as_tensor());
      poly::StageMap stages = arg_pack[arg_pack.size() - 1];
1724 1725
      pe::GlobalPoolScheduleGPU(
          stages, {out.as_tensor_ref(), reduce.as_tensor_ref()}, target);
1726 1727 1728 1729
      *ret = CINNValuePack{{CINNValue(out), CINNValue(stages)}};
    }
  });

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
  framework::CINNCompute pool2d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of pool2d compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        ir::Tensor A_tensor = A.as_tensor_ref();

        std::string tensor_name = UniqName("Pool2d_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
1745

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
        auto out = pe::Pool2d(A_tensor,
                              kernel_size,
                              stride_size,
                              padding_size,
                              pool_type,
                              ceil_mode,
                              exclusive,
                              data_format,
                              adaptive,
                              tensor_name);

        auto stages = CreateStages({A_tensor});
        CHECK(out.size() == 1U || out.size() == 2U)
            << "The size of pe::Pool2d's output should be 1 or 2.";
        std::vector<CINNValue> res;
        for (auto &t : out) {
          stages->InsertLazily(t);
          res.push_back(CINNValue(t));
        }
        CHECK(!out_type.empty())
            << "Output type of Pool2d is empty! Please check.\n";
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });
1770

1771 1772
  framework::CINNSchedule pool2d_schedule([=](lang::Args args,
                                              lang::RetValue *ret) {
1773
    if (FLAGS_cinn_ir_schedule) {
1774 1775
      CHECK(!args.empty())
          << "The input argument of pool2d schedule is empty! Please check.\n";
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      std::vector<Expr> vec_tensor;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        } else if (arg_pack[i].is_tensor()) {
          Expr temp = arg_pack[i];
          vec_tensor.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      int arg_pack_size = arg_pack.size();
      // arg_pack_size == 3 case: input, input_pad, output
      // arg_pack_size == 4 case: input, input_pad, output, stage
      if (arg_pack_size == 3UL || arg_pack_size == 4UL) {
        CHECK_EQ(vec_tensor.size(), 2);
        Expr input_pad = vec_tensor[1];
        CHECK(input_pad.as_tensor());
        const std::string &input_pad_name = input_pad.as_tensor()->name;
        VLOG(6) << "ComputeInline on " << input_pad_name;
        auto block_input_pad = ir_sch.GetBlock(input_pad_name);
        ir_sch.ComputeInline(block_input_pad);
      }
      if (target.arch == Target::Arch::NVGPU) {
        pe::IRPoolScheduleGPU(ir_sch, target, arg_pack_size);
      }
1807 1808
      std::vector<CINNValue> res{
          CINNValue(ir_sch.GetModule().GetExprs().at(0))};
1809 1810
      *ret = CINNValuePack{res};
    } else {
1811 1812
      CHECK(!args.empty())
          << "The input argument of pool2d schedule is empty! Please check.\n";
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
      CINNValuePack arg_pack = args[0];
      CHECK(arg_pack.size() == 2UL || arg_pack.size() == 3UL);
      Expr Out = arg_pack[0];
      CHECK(Out.as_tensor());
      poly::StageMap stages = arg_pack[arg_pack.size() - 1];
      if (arg_pack.size() == 3UL) {
        Expr input_pad = arg_pack[1];
        CHECK(input_pad.as_tensor());
        stages[input_pad.as_tensor_ref()]->ComputeInline();
      }
      ir::Tensor temp_out = Out.as_tensor_ref();
      if (target.arch == Target::Arch::NVGPU) {
        pe::PoolScheduleGPU(stages, temp_out, target);
        arg_pack[arg_pack.size() - 2] = Expr(temp_out);
      }
      *ret = CINNValuePack{{CINNValue(Out), CINNValue(stages)}};
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();

  bool use_warp_reduce = false;
1835 1836
  if (global_pooling && data_format == "NCHW" &&
      target.arch == Target::Arch::NVGPU) {
1837 1838
    // TODO(hp03): 32 may not be the exact number, try also 16 or 8 or other
    // number
1839 1840 1841 1842 1843 1844 1845
    //      we choose 32 to make sure all the threads in a warp has work to do,
    if ((A_tensor->shape[2].as_int32() * A_tensor->shape[3].as_int32()) >= 32) {
      use_warp_reduce = true;
    }
  }
  strategy->AddImpl(pool2d_compute, pool2d_schedule, "strategy.pool2d.x86", 1);
  if (use_warp_reduce) {
1846 1847 1848 1849
    strategy->AddImpl(global_pool2d_compute,
                      global_pool2d_schedule,
                      "strategy.pool2d.gpu.global",
                      2);
1850 1851 1852 1853 1854
  }

  return strategy;
}

1855 1856 1857
std::vector<std::vector<int>> InferShapeForPool2d(
    const std::vector<std::vector<int>> &inputs_shape,
    const framework::AttrMapType &attrs) {
1858
  CHECK(inputs_shape[0].size() == 4 || inputs_shape[0].size() == 5)
1859 1860
      << "The input's shape size of pool2d should be 4 or 5! Please check "
         "again.";
1861 1862 1863
  std::vector<int> kernel_size;
  std::vector<int> stride_size;
  std::vector<int> padding_size;
1864 1865 1866
  std::string pool_type = "max";
  bool ceil_mode = false;
  bool exclusive = true;
1867
  std::string data_format = "NCHW";
1868 1869
  bool global_pooling = false;
  bool adaptive = false;
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
  for (auto &iter : attrs) {
    if (iter.first == "kernel_size") {
      kernel_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "stride_size") {
      stride_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "padding_size") {
      padding_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "ceil_mode") {
      ceil_mode = absl::get<bool>(iter.second);
    } else if (iter.first == "exclusive") {
      exclusive = absl::get<bool>(iter.second);
    } else if (iter.first == "global_pooling") {
      global_pooling = absl::get<bool>(iter.second);
    } else if (iter.first == "data_format") {
      data_format = absl::get<std::string>(iter.second);
    } else if (iter.first == "adaptive") {
      adaptive = absl::get<bool>(iter.second);
    } else if (iter.first == "pool_type") {
      pool_type = absl::get<std::string>(iter.second);
    }
  }

  int height_axis = -1;
1893
  int width_axis = -1;
1894 1895
  if (data_format == "NCHW") {
    height_axis = 2;
1896
    width_axis = 3;
1897 1898
  } else {
    height_axis = 1;
1899
    width_axis = 2;
1900 1901 1902 1903 1904
  }

  std::vector<int> output_shape1 = inputs_shape[0];
  if (ceil_mode) {
    output_shape1[height_axis] =
1905 1906
        (inputs_shape[0][height_axis] - kernel_size[0] + padding_size[0] +
         padding_size[2] + stride_size[0] - 1) /
1907 1908 1909
            stride_size[0] +
        1;
    output_shape1[width_axis] =
1910 1911
        (inputs_shape[0][width_axis] - kernel_size[1] + padding_size[1] +
         padding_size[3] + stride_size[1] - 1) /
1912 1913 1914 1915
            stride_size[1] +
        1;
  } else {
    output_shape1[height_axis] =
1916 1917 1918 1919 1920 1921 1922 1923
        (inputs_shape[0][height_axis] - kernel_size[0] + padding_size[0] +
         padding_size[2]) /
            stride_size[0] +
        1;
    output_shape1[width_axis] = (inputs_shape[0][width_axis] - kernel_size[1] +
                                 padding_size[1] + padding_size[3]) /
                                    stride_size[1] +
                                1;
1924 1925 1926 1927 1928
  }

  if (adaptive) {
    kernel_size = absl::get<std::vector<int>>(attrs.at("kernel_size"));
    if (kernel_size.size() == 1UL) kernel_size.push_back(kernel_size[0]);
1929 1930
    CHECK(kernel_size.size() >= 2UL)
        << "In pool2d, kernel_size's size should be >= 2, please check!";
1931
    output_shape1[height_axis] = kernel_size[0];
1932
    output_shape1[width_axis] = kernel_size[1];
1933 1934
  }

1935 1936 1937 1938 1939 1940 1941 1942
  VLOG(4) << std::boolalpha << "y[" << cinn::utils::Join(output_shape1, ", ")
          << "] = pool2d(x[" << cinn::utils::Join(inputs_shape[0], ", ")
          << "], kernel_size=[" << cinn::utils::Join(kernel_size, ", ")
          << "], stride_size=[" << cinn::utils::Join(stride_size, ", ")
          << "], padding_size=[" << cinn::utils::Join(padding_size, ", ")
          << "], pool_type=" << pool_type << ", ceil_mode=" << ceil_mode
          << ", exclusive=" << exclusive << ", data_format=" << data_format
          << ", global_pooling=" << global_pooling << ", adaptive=" << adaptive;
1943 1944 1945 1946
  std::vector<std::vector<int>> res{output_shape1};
  return res;
}

1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
std::shared_ptr<OpStrategy> StrategyForPool3d(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  framework::CINNCompute pool3d_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of pool3d compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK(!pack_args.empty())
            << "The input tensor of pool3d compute is empty! Please check.\n";
        Expr A = pack_args[0];
        CHECK(A.as_tensor());
        auto attr_store = attrs.attr_store;
        std::vector<int> kernel_size;  // [kernel_d, kernel_h, kernel_w]
        std::vector<int> stride_size;  // [stride_d, stride_h, stride_w]
        std::vector<int>
            padding_size;  // [padding_front, padding_top, padding_left,
                           // padding_back, padding_bottom, padding_right]
        std::string pool_type = "max";
        bool ceil_mode = false;
        bool exclusive = true;
        std::string data_format = "NCDHW";
        for (auto &iter : attrs.attr_store) {
          if (iter.first == "kernel_size") {
            kernel_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "stride_size") {
            stride_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "padding_size") {
            padding_size = absl::get<std::vector<int>>(iter.second);
          } else if (iter.first == "pool_type") {
            pool_type = absl::get<std::string>(iter.second);
          } else if (iter.first == "ceil_mode") {
            ceil_mode = absl::get<bool>(iter.second);
          } else if (iter.first == "exclusive") {
            exclusive = absl::get<bool>(iter.second);
          } else if (iter.first == "data_format") {
            data_format = absl::get<std::string>(iter.second);
          } else {
            LOG(ERROR) << "Unsupported attr: " << iter.first << std::endl;
          }
        }
        CHECK(!kernel_size.empty())
            << "kernel_size for pool3d is empty. Please check.\n";
        CHECK(!stride_size.empty())
            << "stride_size for pool3d is empty. Please check.\n";
        CHECK(!padding_size.empty())
            << "padding_size for pool3d is empty. Please check.\n";
        CHECK(pool_type == "max" || pool_type == "avg")
            << "pool_type for pool3d should be max or avg.\n";

        std::string tensor_name = UniqName("Pool3d_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 2);
          CHECK(pack_args[1].is_string());
          tensor_name = pack_args[1].operator std::string();
        }
2006

2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
        auto out = pe::Pool3d(A.as_tensor_ref(),
                              kernel_size,
                              stride_size,
                              padding_size,
                              pool_type,
                              ceil_mode,
                              exclusive,
                              data_format,
                              tensor_name);

        auto stages = CreateStages(out);
        CHECK(out.size() == 1U || out.size() == 2U)
            << "The size of pe::Pool3d's output should be 1 or 2.";
        CHECK(!out_type.empty())
            << "Output type of Pool3d is empty! Please check.\n";

        std::vector<CINNValue> res;
        for (auto &t : out) {
          res.push_back(CINNValue(Expr(t.get())));
        }
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });
2030

2031 2032
  framework::CINNSchedule pool3d_schedule([=](lang::Args args,
                                              lang::RetValue *ret) {
2033
    if (FLAGS_cinn_ir_schedule) {
2034 2035
      CHECK(!args.empty())
          << "The input argument of pool3d schedule is empty! Please check.\n";
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      std::vector<Expr> vec_tensor;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        } else if (arg_pack[i].is_tensor()) {
          Expr temp = arg_pack[i];
          vec_tensor.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (arg_pack.size() == 3UL) {
        CHECK_EQ(vec_tensor.size(), 2);
        Expr input_pad = vec_tensor[1];
        CHECK(input_pad.as_tensor());
        auto block_input_pad = ir_sch.GetBlock(input_pad.as_tensor()->name);
        ir_sch.ComputeInline(block_input_pad);
      }
      if (target.arch == Target::Arch::NVGPU) {
        CHECK(!vec_tensor.empty());
        Expr Out = vec_tensor[0];
        CHECK(Out.as_tensor());
        auto loops = ir_sch.GetLoops(Out.as_tensor()->name);
        ir_sch.Split(loops[1], {-1, 2});
        loops = ir_sch.GetLoops(Out.as_tensor()->name);
        ir_sch.Bind(loops[0], "blockIdx.x");
        ir_sch.Bind(loops[1], "threadIdx.x");
      }
2069 2070
      std::vector<CINNValue> res{
          CINNValue(ir_sch.GetModule().GetExprs().at(0))};
2071 2072
      *ret = CINNValuePack{res};
    } else {
2073 2074
      CHECK(!args.empty())
          << "The input argument of pool3d schedule is empty! Please check.\n";
2075 2076
      CINNValuePack arg_pack = args[0];
      CHECK(arg_pack.size() == 2UL || arg_pack.size() == 3UL);
2077
      Expr Out = arg_pack[0];
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
      poly::StageMap stages = arg_pack[arg_pack.size() - 1];
      if (arg_pack.size() == 3UL) {
        Expr input_pad = arg_pack[1];
        CHECK(input_pad.as_tensor());
        stages[input_pad.as_tensor_ref()]->ComputeInline();
      }

      if (target.arch == Target::Arch::NVGPU) {
        CHECK(Out.as_tensor());
        stages[Out.as_tensor_ref()]->Split(1, 2);
        stages[Out.as_tensor_ref()]->Bind(0, "blockIdx.x");
        stages[Out.as_tensor_ref()]->Bind(1, "threadIdx.x");
      }
      *ret = CINNValuePack{{CINNValue(Out), CINNValue(stages)}};
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
  strategy->AddImpl(pool3d_compute, pool3d_schedule, "strategy.pool3d.x86", 1);

  return strategy;
}

2101 2102 2103 2104 2105
std::vector<std::vector<int>> InferShapeForPool3d(
    const std::vector<std::vector<int>> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty() && !inputs_shape[0].empty())
      << "The input's shape size is 0! Please check again.";
2106 2107 2108
  std::vector<int> kernel_size;  // [kernel_d, kernel_h, kernel_w]
  std::vector<int> stride_size;  // [stride_d, stride_h, stride_w]
  std::vector<int>
2109 2110 2111 2112 2113
      padding_size;  // [padding_front, padding_top, padding_left,
                     // padding_bottom, padding_right, padding_back]
  std::string pool_type = "max";
  bool ceil_mode = false;
  bool exclusive = true;
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
  std::string data_format = "NCDHW";
  for (auto &iter : attrs) {
    if (iter.first == "kernel_size") {
      kernel_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "stride_size") {
      stride_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "padding_size") {
      padding_size = absl::get<std::vector<int>>(iter.second);
    } else if (iter.first == "ceil_mode") {
      ceil_mode = absl::get<bool>(iter.second);
    } else if (iter.first == "exclusive") {
      exclusive = absl::get<bool>(iter.second);
    } else if (iter.first == "data_format") {
      data_format = absl::get<std::string>(iter.second);
    }
  }

  CHECK_EQ(kernel_size.size(), 3U) << "kernel_size for pool3d should be 3.\n";
  CHECK_EQ(stride_size.size(), 3U) << "stride_size for pool3d should be 3.\n";
2133 2134
  CHECK(pool_type == "max" || pool_type == "avg")
      << "pool_type for pool3d should be max or avg.\n";
2135 2136

  std::vector<int> output_shape1 = inputs_shape[0];
2137 2138 2139
  CHECK_EQ(inputs_shape[0].size(), 5U)
      << "input_shape size for pool3d should be 5.\n";
  int depth_axis = -1;
2140
  int height_axis = -1;
2141
  int width_axis = -1;
2142
  if (data_format == "NCDHW") {
2143
    depth_axis = 2;
2144
    height_axis = 3;
2145
    width_axis = 4;
2146
  } else if (data_format == "NDHWC") {
2147
    depth_axis = 1;
2148
    height_axis = 2;
2149
    width_axis = 3;
2150 2151 2152 2153 2154 2155
  } else {
    LOG(ERROR) << "unsupported data_format: " << data_format << std::endl;
  }

  if (ceil_mode) {
    output_shape1[depth_axis] =
2156 2157
        (inputs_shape[0][depth_axis] - kernel_size[0] + padding_size[0] +
         padding_size[3] + stride_size[0] - 1) /
2158 2159 2160
            stride_size[0] +
        1;
    output_shape1[height_axis] =
2161 2162
        (inputs_shape[0][height_axis] - kernel_size[1] + padding_size[1] +
         padding_size[4] + stride_size[1] - 1) /
2163 2164 2165
            stride_size[1] +
        1;
    output_shape1[width_axis] =
2166 2167
        (inputs_shape[0][width_axis] - kernel_size[2] + padding_size[2] +
         padding_size[5] + stride_size[2] - 1) /
2168 2169 2170
            stride_size[2] +
        1;
  } else {
2171 2172 2173 2174
    output_shape1[depth_axis] = (inputs_shape[0][depth_axis] - kernel_size[0] +
                                 padding_size[0] + padding_size[3]) /
                                    stride_size[0] +
                                1;
2175
    output_shape1[height_axis] =
2176 2177 2178 2179 2180 2181 2182 2183
        (inputs_shape[0][height_axis] - kernel_size[1] + padding_size[1] +
         padding_size[4]) /
            stride_size[1] +
        1;
    output_shape1[width_axis] = (inputs_shape[0][width_axis] - kernel_size[2] +
                                 padding_size[2] + padding_size[5]) /
                                    stride_size[2] +
                                1;
2184 2185 2186 2187 2188 2189
  }

  std::vector<std::vector<int>> res{output_shape1};
  return res;
}

2190 2191 2192 2193
std::vector<Type> InferDtypeForPool(const std::vector<Type> &inputs_type,
                                    const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
2194 2195 2196 2197
  std::vector<Type> res{inputs_type[0]};
  return res;
}

2198 2199 2200 2201 2202 2203 2204
std::vector<std::vector<std::string>> InferLayoutForPool(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 1U)
      << "The input's layout size is not 1! Please check again.";
2205 2206 2207
  return {input_layouts, input_layouts};
}

2208 2209 2210 2211 2212 2213 2214
std::shared_ptr<OpStrategy> StrategyForSoftmax(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  int axis = -1;
2215 2216 2217 2218 2219 2220 2221
  bool use_mkldnn = false;
  if (attrs.attr_store.count("axis")) {
    axis = absl::get<int>(attrs.attr_store.at("axis"));
  }
  if (attrs.attr_store.count("use_mkldnn")) {
    use_mkldnn = absl::get<bool>(attrs.attr_store.at("use_mkldnn"));
  }
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
  framework::CINNCompute softmax_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input arguments of softmax compute is empty! Please check.";
        CINNValuePack pack_args = args[0];
        CHECK(!pack_args.empty())
            << "The input tensors of softmax compute is empty! Please check.";
        Expr A_expr = pack_args[0];
        CHECK(A_expr.as_tensor());
        ir::Tensor A = A_expr.as_tensor_ref();
        auto stages = CreateStages({A});
        int new_axis = axis;
        if (axis == -1) {
          new_axis = A->shape.size() - 1;
        }
        std::vector<ir::Tensor> out;
2238

2239 2240 2241 2242 2243 2244
        std::string tensor_name = UniqName("Softmax_out");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_GE(pack_args.size(), 2);
          CHECK(pack_args[pack_args.size() - 1].is_string());
          tensor_name = pack_args[pack_args.size() - 1].operator std::string();
        }
2245 2246

#ifdef CINN_WITH_MKLDNN
2247 2248 2249 2250 2251
        if (use_mkldnn) {
          out = pe::SoftmaxMKLDNN(A, new_axis, tensor_name);
        } else {
          out = pe::Softmax(A, new_axis, tensor_name);
        }
2252
#else
2253
        out = pe::Softmax(A, new_axis, tensor_name);
2254
#endif
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
        std::vector<CINNValue> res;
        for (auto &t : out) {
          stages->InsertLazily(t);
          res.push_back(CINNValue(t));
        }
        CHECK_EQ(out.size(), 2U)
            << "The size of pe::Softmax's output should be 2.";
        CHECK(!out_type.empty())
            << "Output type of Softmax is empty! Please check.\n";
        res.push_back(CINNValue(stages));
        *ret = CINNValuePack{res};
      });
2267

2268 2269
  framework::CINNSchedule softmax_schedule([=](lang::Args args,
                                               lang::RetValue *ret) {
2270
    if (FLAGS_cinn_ir_schedule) {
2271 2272
      CHECK(!args.empty())
          << "The input arguments of softmax schedule is empty! Please check.";
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
      CINNValuePack arg_pack = args[0];
      std::vector<Expr> vec_ast;
      for (int i = 0; i < arg_pack.size(); i++) {
        if (arg_pack[i].is_expr()) {
          Expr temp = arg_pack[i];
          vec_ast.emplace_back(temp);
        }
      }
      CHECK(!vec_ast.empty());
      ir::ModuleExpr mod_expr(vec_ast);
      ir::IRSchedule ir_sch(mod_expr);
      ir_sch.MergeExprs();
      if (target.arch == Target::Arch::NVGPU) {
        if (output_shapes[0].size() > 1) {
          auto all_blocks = ir_sch.GetAllBlocks();
          CHECK_EQ(all_blocks.size(), 3);
          auto loops = ir_sch.GetLoops(all_blocks[2]);
          ir_sch.ComputeAt(all_blocks[1], loops.back());

          if (output_shapes[0][0] != 1) {
            ir_sch.SimpleComputeAt(all_blocks[0], loops[0]);
          }

2296
          loops = ir_sch.GetLoops(all_blocks[2]);
2297 2298 2299 2300 2301 2302
          int loop_index = 1;
          if (output_shapes[0][0] == 1) loop_index--;
          CHECK_GE(loops.size(), loop_index + 1);
          auto splited_loops = ir_sch.Split(loops[loop_index], {-1, 5});

          all_blocks = ir_sch.GetAllBlocks();
2303
          loops = ir_sch.GetLoops(all_blocks[2]);
2304 2305 2306
          ir_sch.Bind(loops[0], "blockIdx.x");
          ir_sch.Bind(loops[1], "threadIdx.x");
        }
2307 2308
        std::vector<CINNValue> res{
            CINNValue(ir_sch.GetModule().GetExprs().at(0))};
2309 2310 2311
        *ret = CINNValuePack{res};
      } else if (target.arch == Target::Arch::X86) {
        pe::IRSoftmaxScheduleCPU(ir_sch, axis);
2312 2313
        std::vector<CINNValue> res{
            CINNValue(ir_sch.GetModule().GetExprs().at(0))};
2314 2315 2316
        *ret = CINNValuePack{res};
      }
    } else {
2317 2318
      CHECK(!args.empty())
          << "The input arguments of softmax schedule is empty! Please check.";
2319
      CINNValuePack arg_pack = args[0];
2320 2321 2322 2323 2324
      CHECK_EQ(arg_pack.size(), 3UL)
          << "The input tensor's size of softmax schedule is "
          << arg_pack.size() << "and it should be equal to 3! Please check.";
      Expr out1 = arg_pack[0];
      Expr out2 = arg_pack[1];
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
      poly::StageMap stages = arg_pack[2];
      CHECK(out1.as_tensor());
      CHECK(out2.as_tensor());
      ir::Tensor tensor_a = out1.as_tensor_ref();
      ir::Tensor tensor_b = out2.as_tensor_ref();
      if (target.arch == Target::Arch::NVGPU) {
        if (tensor_a->shape.size() > 1) {
          stages[tensor_a]->Split(1, 5);
          stages[tensor_a]->Bind(0, "blockIdx.x");
          stages[tensor_a]->Bind(1, "threadIdx.x");
          int shape_size = tensor_a->shape.size();
          stages[tensor_b]->ComputeAt(stages[tensor_a], shape_size);
        }
      } else if (target.arch == Target::Arch::X86) {
        pe::SoftmaxScheduleCPU(stages, tensor_a, tensor_b, axis);
      }
      *ret = arg_pack;
    }
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
2346 2347
  strategy->AddImpl(
      softmax_compute, softmax_schedule, "strategy.softmax.x86", 1);
2348 2349 2350 2351

  return strategy;
}

2352 2353 2354 2355 2356
std::vector<std::vector<int>> InferShapeForSoftmax(
    const std::vector<std::vector<int>> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty() && !inputs_shape[0].empty())
      << "The input's shape size is 0! Please check again.";
2357 2358 2359 2360
  std::vector<std::vector<int>> res{inputs_shape[0]};
  return res;
}

2361 2362 2363 2364
std::vector<Type> InferDtypeForSoftmax(const std::vector<Type> &inputs_type,
                                       const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
2365 2366 2367 2368
  std::vector<Type> res{inputs_type[0]};
  return res;
}

2369 2370 2371 2372 2373 2374 2375
std::vector<std::vector<std::string>> InferLayoutForSoftmax(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 1U)
      << "The input's layout size is not 1! Please check again.";
2376 2377 2378 2379 2380 2381 2382
  if (input_shapes[0].size() > 4) {
    // input tensor needs to be transformed back to NCHW for mkldnn
    return {{"NCHW", "NCHW"}, {"NCHW"}};
  }
  return {{input_layouts[0], input_layouts[0]}, input_layouts};
}

2383 2384 2385 2386 2387 2388 2389
std::shared_ptr<OpStrategy> StrategyForDropoutInfer(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  float dropout_prob = 0;
2390 2391 2392 2393
  std::string dropout_implementation = "downgrade_in_infer";
  if (attrs.attr_store.find("dropout_prob") != attrs.attr_store.end()) {
    dropout_prob = absl::get<float>(attrs.attr_store.at("dropout_prob"));
  }
2394 2395 2396 2397
  if (attrs.attr_store.find("dropout_implementation") !=
      attrs.attr_store.end()) {
    dropout_implementation =
        absl::get<std::string>(attrs.attr_store.at("dropout_implementation"));
2398 2399
  }

2400 2401 2402 2403
  framework::CINNCompute dropout_infer_compute([=](lang::Args args,
                                                   lang::RetValue *ret) {
    CHECK(!args.empty()) << "The input arguments of dropout_infer compute is "
                            "empty! Please check.";
2404
    CINNValuePack pack_args = args[0];
2405 2406
    CHECK(!pack_args.empty())
        << "The input tensors of dropout_infer compute is empty! Please check.";
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
    Expr A_expr = pack_args[0];
    CHECK(A_expr.as_tensor());
    ir::Tensor A = A_expr.as_tensor_ref();

    std::string tensor_name = UniqName("dropout_infer_out");
    if (FLAGS_cinn_ir_schedule) {
      CHECK_EQ(pack_args.size(), 2);
      CHECK(pack_args[1].is_string());
      tensor_name = pack_args[1].operator std::string();
    }

2418 2419
    auto out =
        pe::DropoutInfer(A, dropout_prob, dropout_implementation, tensor_name);
2420
    auto stages = CreateStages({A, out});
2421
    *ret = CINNValuePack{{CINNValue(out), CINNValue(stages)}};
2422 2423 2424
  });

  auto strategy = std::make_shared<framework::OpStrategy>();
2425 2426 2427 2428
  strategy->AddImpl(dropout_infer_compute,
                    GetInjectiveScheduleFunc(output_shapes, target),
                    "strategy.dropout_infer.x86",
                    1);
2429 2430 2431 2432

  return strategy;
}

2433 2434 2435 2436 2437 2438
std::vector<std::vector<int>> InferShapeForDropoutInfer(
    const std::vector<std::vector<int>> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK(!inputs_shape.empty())
      << "The input's shape size is 0! Please check again.";
  float dropout_prob = 0;
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
  std::string dropout_implementation = "downgrade_in_infer";
  for (auto &iter : attrs) {
    if (iter.first == "dropout_prob") {
      dropout_prob = absl::get<float>(iter.second);
    } else if (iter.first == "dropout_implementation") {
      dropout_implementation = absl::get<std::string>(iter.second);
    } else {
      LOG(ERROR) << "Unsupported attr: " << iter.first << std::endl;
    }
  }

  std::vector<std::vector<int>> res{inputs_shape[0]};
  return res;
}

2454 2455 2456 2457
std::vector<Type> InferDtypeForDropoutInfer(
    const std::vector<Type> &inputs_type, const framework::AttrMapType &attrs) {
  CHECK(!inputs_type.empty())
      << "The input's type size is 0! Please check again.";
2458 2459 2460 2461
  std::vector<Type> res{inputs_type[0]};
  return res;
}

2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
std::shared_ptr<OpStrategy> StrategyForSelect(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  framework::CINNCompute select_compute(
      [=](lang::Args args, lang::RetValue *ret) {
        CHECK(!args.empty())
            << "The input argument of select compute is empty! Please check.\n";
        CINNValuePack pack_args = args[0];
        CHECK_GE(pack_args.size(), 3U)
            << "at least three input tensor for select compute\n";
        Expr condition = pack_args[0];
        Expr true_value = pack_args[1];
        Expr false_value = pack_args[2];
        CHECK(condition.as_tensor());
        CHECK(true_value.as_tensor());
        CHECK(false_value.as_tensor());

        std::string tensor_name = UniqName("Select_output");
        if (FLAGS_cinn_ir_schedule) {
          CHECK_EQ(pack_args.size(), 4U);
          CHECK(pack_args[3].is_string());
          tensor_name = pack_args[3].operator std::string();
        }
2488

2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
        auto out = pe::Select(condition.as_tensor_ref(),
                              true_value.as_tensor_ref(),
                              false_value.as_tensor_ref(),
                              tensor_name);
        auto stages = CreateStages({condition.as_tensor_ref(),
                                    true_value.as_tensor_ref(),
                                    false_value.as_tensor_ref(),
                                    out});
        *ret = CINNValuePack{{CINNValue(out), CINNValue(stages)}};
      });
2499 2500 2501

  auto strategy = std::make_shared<framework::OpStrategy>();
  CHECK(out_type.size()) << "Out_type of select op is empty! Please check.";
2502 2503 2504 2505
  strategy->AddImpl(select_compute,
                    GetInjectiveScheduleFunc(output_shapes, target, false),
                    "strategy.select.x86",
                    1);
2506 2507 2508
  return strategy;
}

2509 2510 2511 2512 2513 2514 2515
std::vector<framework::shape_t> InferShapeForSelect(
    const std::vector<framework::shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_GE(inputs_shape.size(), 3)
      << "The input's shape size is 0! Please check again.";
  CHECK(inputs_shape[0].size() == inputs_shape[1].size() &&
        inputs_shape[1].size() == inputs_shape[2].size())
2516
      << "input tensors n_dim is not equal!";
2517 2518
  CHECK(inputs_shape[0] == inputs_shape[1] &&
        inputs_shape[1] == inputs_shape[2])
2519 2520 2521 2522 2523
      << "input tensor shapes is not equal!";
  std::vector<framework::shape_t> res{inputs_shape[0]};
  return res;
}

2524 2525 2526 2527
std::vector<Type> InferDtypeForSelect(const std::vector<Type> &inputs_type,
                                      const framework::AttrMapType &attrs) {
  CHECK_GE(inputs_type.size(), 3)
      << "The input's type size is less than three! Please check again.";
2528
  CHECK(inputs_type[0].is_bool()) << "The condition tensor type should be bool";
2529 2530
  CHECK_EQ(inputs_type[1], inputs_type[2])
      << "The true or false tensor type should be equal";
2531 2532 2533 2534
  std::vector<Type> res{inputs_type[1]};
  return res;
}

2535 2536 2537 2538 2539 2540 2541
std::vector<std::vector<std::string>> InferLayoutForUnary(
    const std::vector<framework::shape_t> &input_shapes,
    const std::vector<std::string> &input_layouts,
    const framework::NodeAttr &attrs,
    const Target &target) {
  CHECK_EQ(input_layouts.size(), 1U)
      << "The input's layout size is not 1! Please check again.";
2542 2543 2544 2545
  return {input_layouts, input_layouts};
}

// batch norm train
2546 2547 2548 2549 2550
std::vector<framework::shape_t> InferShapeForBatchNormTrain(
    const std::vector<framework::shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_shape.size(), 5U)
      << "The input's layout size is not 5! Please check again.";
2551 2552 2553 2554 2555 2556 2557 2558
  std::string data_layout = "";
  if (attrs.find("data_layout") != attrs.end()) {
    data_layout = absl::get<std::string>(attrs.at("data_layout"));
  } else {
    LOG(FATAL) << "data_layout is not found, please check!";
  }

  CHECK_EQ(inputs_shape[0].size(), 4) << "x dimension size is not required!";
2559 2560
  CHECK_EQ(inputs_shape[1].size(), 1)
      << "scale dimension size is not required!";
2561
  CHECK_EQ(inputs_shape[2].size(), 1) << "bias dimension size is not required!";
2562 2563 2564 2565
  CHECK_EQ(inputs_shape[3].size(), 1)
      << "moving_mean dimension size is not required!";
  CHECK_EQ(inputs_shape[4].size(), 1)
      << "moving_variance dimension size is not required!";
2566 2567

  if (data_layout == "NCHW") {
2568 2569 2570 2571 2572 2573 2574 2575
    CHECK_EQ(inputs_shape[0][1], inputs_shape[1][0])
        << "x and scale dimension is not equal!";
    CHECK_EQ(inputs_shape[0][1], inputs_shape[2][0])
        << "x and bias dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][1], inputs_shape[3][0])
        << "x and moveing_mean dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][1], inputs_shape[4][0])
        << "x and moveing_variance dimension size is not equal!";
2576
  } else if (data_layout == "NHWC") {
2577 2578 2579 2580 2581 2582 2583 2584
    CHECK_EQ(inputs_shape[0][3], inputs_shape[1][0])
        << "x and scale dimension is not equal!";
    CHECK_EQ(inputs_shape[0][3], inputs_shape[2][0])
        << "x and bias dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][3], inputs_shape[3][0])
        << "x and moveing_mean dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][3], inputs_shape[4][0])
        << "x and moveing_variance dimension size is not equal!";
2585 2586 2587 2588
  } else {
    LOG(FATAL) << "data_layout " << data_layout << " is not support!";
  }

2589 2590 2591 2592 2593
  return {inputs_shape[0],
          inputs_shape[1],
          inputs_shape[1],
          inputs_shape[1],
          inputs_shape[1]};
2594 2595
}

2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
std::vector<Type> InferDtypeForBatchNormTrain(
    const std::vector<Type> &inputs_type, const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_type.size(), 5U) << "The BatchNormTrain input's type size "
                                      "should be 5! Please check again.";
  CHECK_EQ(inputs_type[1], inputs_type[2])
      << "The BatchNormTrain scale type should the same as bias type";
  CHECK_EQ(inputs_type[1], inputs_type[3])
      << "The BatchNormTrain scale type should the same as moving_mean type";
  CHECK_EQ(inputs_type[1], inputs_type[4])
      << "The BatchNormTrain scale type should the same as moving_variance "
         "type";
  return {inputs_type[0],
          inputs_type[1],
          inputs_type[1],
          inputs_type[1],
          inputs_type[1]};
2612 2613
}

2614 2615 2616 2617 2618 2619 2620 2621
std::shared_ptr<OpStrategy> StrategyForGradOp(
    const framework::NodeAttr &attrs,
    const std::vector<ir::Tensor> &inputs,
    const std::vector<Type> &out_type,
    const std::vector<std::vector<int>> &output_shapes,
    const Target &target) {
  LOG(FATAL) << "Gradient operator will be decomposed into several primitive "
                "operators. Please Use Decomposer Program Pass.";
2622 2623 2624
}

// batch norm grad
2625 2626 2627 2628 2629
std::vector<framework::shape_t> InferShapeForBatchNormGrad(
    const std::vector<framework::shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_shape.size(), 5U)
      << "The input's layout size is not 5! Please check again.";
2630 2631 2632 2633 2634 2635 2636 2637 2638
  std::string data_layout = "";
  if (attrs.find("data_layout") != attrs.end()) {
    data_layout = absl::get<std::string>(attrs.at("data_layout"));
  } else {
    LOG(FATAL) << "data_layout is not found, please check!";
  }

  CHECK_EQ(inputs_shape[0].size(), 4) << "dy dimension size is not required!";
  CHECK_EQ(inputs_shape[1].size(), 4) << "x dimension size is not required!";
2639 2640 2641 2642 2643 2644
  CHECK_EQ(inputs_shape[2].size(), 1)
      << "scale dimension size is not required!";
  CHECK_EQ(inputs_shape[3].size(), 1)
      << "save_mean dimension size is not required!";
  CHECK_EQ(inputs_shape[4].size(), 1)
      << "save_variance dimension size is not required!";
2645 2646 2647

  CHECK(inputs_shape[0] == inputs_shape[1]) << "dy and x shape is not equal!";
  if (data_layout == "NCHW") {
2648 2649 2650 2651 2652 2653
    CHECK_EQ(inputs_shape[0][1], inputs_shape[2][0])
        << "dy and bias dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][1], inputs_shape[3][0])
        << "dy and moveing_mean dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][1], inputs_shape[4][0])
        << "dy and moveing_variance dimension size is not equal!";
2654
  } else if (data_layout == "NHWC") {
2655 2656 2657 2658 2659 2660
    CHECK_EQ(inputs_shape[0][3], inputs_shape[2][0])
        << "dy and bias dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][3], inputs_shape[3][0])
        << "dy and moveing_mean dimension size is not equal!";
    CHECK_EQ(inputs_shape[0][3], inputs_shape[4][0])
        << "dy and moveing_variance dimension size is not equal!";
2661 2662 2663 2664 2665 2666 2667
  } else {
    LOG(FATAL) << "data_layout " << data_layout << " is not support!";
  }

  return {inputs_shape[0], inputs_shape[2], inputs_shape[2]};
}

2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
std::vector<Type> InferDtypeForBatchNormGrad(
    const std::vector<Type> &inputs_type, const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_type.size(), 5U)
      << "The BatchNormGrad input's type size should be 5! Please check again.";

  CHECK_EQ(inputs_type[0], inputs_type[1])
      << "The BatchNormGrad y_grad type should the same as x type";
  CHECK_EQ(inputs_type[2], inputs_type[3])
      << "The BatchNormGrad scale type should the same as save_mean type";
  CHECK_EQ(inputs_type[2], inputs_type[4])
      << "The BatchNormGrad scale type should the same as save_variance type";
2679 2680 2681 2682
  return {inputs_type[0], inputs_type[2], inputs_type[2]};
}

// pool2d grad
2683 2684 2685 2686 2687
std::vector<framework::shape_t> InferShapeForPool2dGrad(
    const std::vector<framework::shape_t> &inputs_shape,
    const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_shape.size(), 3U)
      << "The operator pool2d_grad should has 3 inputs! Please check again.";
2688 2689 2690
  return {inputs_shape[0]};
}

2691 2692 2693 2694
std::vector<Type> InferDtypeForPool2dGrad(const std::vector<Type> &inputs_type,
                                          const framework::AttrMapType &attrs) {
  CHECK_EQ(inputs_type.size(), 3U)
      << "The operator pool2d_grad should has 3 inputs! Please check again.";
2695 2696 2697 2698 2699 2700 2701 2702 2703
  return {inputs_type[0]};
}

}  // namespace op
}  // namespace hlir
}  // namespace cinn

CINN_REGISTER_HELPER(nn_ops) {
  CINN_REGISTER_OP(relu)
2704 2705 2706
      .describe(
          "Output 0 for each input element < 0. Output itself for each input "
          "element >= 0.")
2707 2708
      .set_num_inputs(1)
      .set_num_outputs(1)
2709 2710
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForRelu)
2711 2712 2713
      .set_attr("infershape", MakeOpFunction(cinn::hlir::op::InferShapeForRelu))
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForRelu))
#ifndef CINN_WITH_CUDA
2714 2715
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForUnary))
2716
#endif
2717 2718
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kElementWise)
2719 2720 2721
      .set_support_level(4);

  CINN_REGISTER_OP(relu6)
2722 2723 2724
      .describe(
          "Output 0 for each input element < 0. Output itself for each input "
          "element >= 0 and <=6.")
2725 2726
      .set_num_inputs(1)
      .set_num_outputs(1)
2727 2728
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForRelu6)
2729 2730 2731
      .set_attr("infershape", MakeOpFunction(cinn::hlir::op::InferShapeForRelu))
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForRelu))
#ifndef CINN_WITH_CUDA
2732 2733
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForUnary))
2734
#endif
2735 2736
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kElementWise)
2737 2738 2739 2740 2741 2742
      .set_support_level(4);

  CINN_REGISTER_OP(conv2d)
      .describe("Do a 2-D convolution with an NCHW/NHWC layout.")
      .set_num_inputs(2)  // here we consider filter as another input
      .set_num_outputs(4)
2743 2744 2745 2746 2747 2748
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForConv2d)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForConv2d))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForConv2d))
2749
#ifndef CINN_WITH_CUDA
2750 2751
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForConv2d))
2752
#endif
2753 2754
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2755 2756 2757
      .set_support_level(4);

  CINN_REGISTER_OP(conv2d_NCHWc)
2758 2759 2760
      .describe(
          "Do a 2-D convolution with an NCHWc layout. Input is 5D tensor and "
          "weight is 6D tensor.")
2761 2762
      .set_num_inputs(2)  // here we consider filter as another input
      .set_num_outputs(3)
2763 2764 2765 2766 2767 2768
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForConv2dNCHWc)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForConv2dNCHWc))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForConv2dNCHWc))
2769
#ifndef CINN_WITH_CUDA
2770 2771
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForConv2dNCHWc))
2772
#endif
2773 2774
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kOutFusible)
2775 2776 2777 2778 2779 2780
      .set_support_level(4);

  CINN_REGISTER_OP(depthwise_conv2d)
      .describe("Do a 2-D depthwise convolution with an NCHW/NHWC layout.")
      .set_num_inputs(2)  // here we consider filter as another input
      .set_num_outputs(4)
2781 2782 2783 2784 2785 2786
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForDepthwiseConv2d)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForConv2d))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForConv2d))
2787
#ifndef CINN_WITH_CUDA
2788 2789
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForConv2d))
2790 2791
#endif
#ifdef CINN_WITH_CUDNN
2792 2793
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2794
#else
2795 2796
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kOutFusible)
2797 2798 2799 2800
#endif
      .set_support_level(4);

  CINN_REGISTER_OP(batch_norm)
2801 2802 2803 2804 2805
      .describe(
          "Can be used as a normalizer function for convolution or "
          "fully_connected operations.")
      .set_num_inputs(5)  // here we consider batchnorm's 4 attrs(mean,
                          // variance, scale, bias) as other 4 inputs
2806
      .set_num_outputs(1)
2807 2808 2809 2810 2811 2812
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForBatchNorm)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForBatchNorm))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForBatchNorm))
2813
#ifndef CINN_WITH_CUDA
2814 2815
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForBatchNorm))
2816
#endif
2817 2818
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kElementWise)
2819 2820 2821 2822 2823 2824
      .set_support_level(4);

  CINN_REGISTER_OP(pool1d)
      .describe("Do pooling on the width dimension of the input tensor.")
      .set_num_inputs(1)
      .set_num_outputs(1)
2825 2826 2827 2828
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForPool1d)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForPool1d))
2829 2830
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForPool))
#ifndef CINN_WITH_CUDA
2831 2832
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForPool))
2833
#endif
2834 2835
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2836 2837 2838
      .set_support_level(4);

  CINN_REGISTER_OP(pool2d)
2839 2840
      .describe(
          "Do pooling on the height and width dimension of the input tensor.")
2841 2842
      .set_num_inputs(1)
      .set_num_outputs(1)
2843 2844 2845 2846
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForPool2d)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForPool2d))
2847 2848
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForPool))
#ifndef CINN_WITH_CUDA
2849 2850
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForPool))
2851
#endif
2852 2853
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2854 2855 2856
      .set_support_level(4);

  CINN_REGISTER_OP(pool3d)
2857 2858 2859
      .describe(
          "Do pooling on the depth, height and width dimension of the input "
          "tensor.")
2860 2861
      .set_num_inputs(1)
      .set_num_outputs(1)
2862 2863 2864 2865
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForPool3d)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForPool3d))
2866 2867
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForPool))
#ifndef CINN_WITH_CUDA
2868 2869
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForPool))
2870
#endif
2871 2872
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2873 2874 2875 2876 2877 2878
      .set_support_level(4);

  CINN_REGISTER_OP(softmax)
      .describe("This operator implements the softmax layer")
      .set_num_inputs(1)
      .set_num_outputs(1)
2879 2880 2881 2882 2883 2884
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForSoftmax)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForSoftmax))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForSoftmax))
2885
#ifndef CINN_WITH_CUDA
2886 2887
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForSoftmax))
2888
#endif
2889 2890
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kNonFusible)
2891 2892 2893 2894 2895 2896
      .set_support_level(4);

  CINN_REGISTER_OP(dropout_infer)
      .describe("Downgrade the outcome at inference or keep the same.")
      .set_num_inputs(1)
      .set_num_outputs(1)
2897 2898 2899 2900 2901 2902
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForDropoutInfer)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForDropoutInfer))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForDropoutInfer))
2903
#ifndef CINN_WITH_CUDA
2904 2905
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForUnary))
2906
#endif
2907 2908
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kInjective)
2909 2910 2911 2912 2913 2914
      .set_support_level(4);

  CINN_REGISTER_OP(select)
      .describe("This operator implements the meta op 'Select'.")
      .set_num_inputs(3)
      .set_num_outputs(1)
2915 2916 2917 2918 2919 2920
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForSelect)
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForSelect))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForSelect))
2921
#ifndef CINN_WITH_CUDA
2922 2923
      .set_attr("inferlayout",
                MakeOpFunction(cinn::hlir::op::InferLayoutForUnary))
2924
#endif
2925 2926
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kElementWise)
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
      .set_support_level(4);

  return true;
}

CINN_REGISTER_HELPER(nn_grad_ops) {
  CINN_REGISTER_OP(relu_grad)
      .describe("The gradient of relu.")
      .set_num_inputs(2)
      .set_num_outputs(1)
2937 2938
      .set_attr<cinn::hlir::framework::StrategyFunction>(
          "CINNStrategy", cinn::hlir::op::StrategyForGradOp)
2939 2940
      .set_attr("infershape", MakeOpFunction(cinn::hlir::op::InferShapeForRelu))
      .set_attr("inferdtype", MakeOpFunction(cinn::hlir::op::InferDtypeForRelu))
2941 2942
      .set_attr<cinn::hlir::framework::OpPatternKind>(
          "OpPattern", cinn::hlir::framework::OpPatternKind::kElementWise);
2943 2944

  CINN_REGISTER_OP(batch_norm_train)
2945 2946
      .describe(
          "This operator implements the batch normalization training forward.")
2947 2948
      .set_num_inputs(5)
      .set_num_outputs(5)
2949 2950 2951 2952
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForBatchNormTrain))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForBatchNormTrain))
2953 2954 2955 2956 2957 2958
      .set_support_level(4);

  CINN_REGISTER_OP(batch_norm_grad)
      .describe("This operator implements the batch normalization backward.")
      .set_num_inputs(5)
      .set_num_outputs(3)
2959 2960 2961 2962
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForBatchNormGrad))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForBatchNormGrad))
2963 2964 2965 2966 2967 2968
      .set_support_level(4);

  CINN_REGISTER_OP(pool2d_grad)
      .describe("This operator implements the batch normalization backward.")
      .set_num_inputs(3)
      .set_num_outputs(1)
2969 2970 2971 2972
      .set_attr("infershape",
                MakeOpFunction(cinn::hlir::op::InferShapeForPool2dGrad))
      .set_attr("inferdtype",
                MakeOpFunction(cinn::hlir::op::InferDtypeForPool2dGrad))
2973 2974 2975 2976
      .set_support_level(4);

  return true;
}