op_teller.cc 76.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/inference/tensorrt/op_teller.h"
16

17
#include <bitset>
18

19
#include "paddle/fluid/framework/block_desc.h"
20
#include "paddle/fluid/framework/data_layout.h"
21

W
wanghuancoder 已提交
22 23 24 25 26 27
namespace paddle {
namespace framework {
class OpDesc;
}  // namespace framework
}  // namespace paddle

28 29 30 31 32 33
namespace paddle {
namespace inference {
namespace tensorrt {

// Just tell by the op_types.
struct SimpleOpTypeSetTeller : public Teller {
34
  SimpleOpTypeSetTeller() {
35 36 37
#if IS_TRT_VERSION_GE(7130)
    teller_set.insert("group_norm");
#endif
W
wenbin 已提交
38 39
#if IS_TRT_VERSION_GE(7000)
    teller_set.insert("tile");
40
    teller_set.insert("flatten_contiguous_range");
Z
zhoutianzi666 已提交
41 42 43 44
    teller_set.insert("rnn");
    int8_teller_set.insert("rnn");
    teller_set.insert("fill_constant_batch_size_like");
    int8_teller_set.insert("fill_constant_batch_size_like");
W
wenbin 已提交
45
#endif
W
wenbin 已提交
46
#if CUDA_VERSION >= 10020
W
Wangzheee 已提交
47 48
    teller_set.insert("reshape");
    teller_set.insert("reshape2");
49 50
    int8_teller_set.insert("reshape");
    int8_teller_set.insert("reshape2");
51 52 53 54 55 56
#endif
#if IS_TRT_VERSION_GE(8000)
    teller_set.insert("sparse_fc");
    int8_teller_set.insert("sparse_fc");
    teller_set.insert("sparse_multihead_matmul");
    int8_teller_set.insert("sparse_multihead_matmul");
57 58
#endif
  }
59

C
ccrrong 已提交
60 61
  bool operator()(const std::string& op_type,
                  const framework::OpDesc& desc,
62 63 64 65 66 67
                  bool use_no_calib_int8) override {
    if (use_no_calib_int8) {
      return int8_teller_set.count(op_type);
    } else {
      return teller_set.count(op_type);
    }
68 69 70
  }

 private:
71
  // use this set for no calib int8.
72 73 74 75 76 77 78
  std::unordered_set<std::string> int8_teller_set{
      "mul",
      "matmul",
      "conv2d",
      "conv2d_fusion",
      "pool2d",
      "relu",
79 80 81 82 83 84
      "elu",
      "selu",
      "softsign",
      "softplus",
      "stanh",
      "thresholded_relu",
Z
zhupengyang 已提交
85 86
      "exp",
      "log",
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      "sqrt",
      "abs",
      "sin",
      "cos",
      "tan",
      "sinh",
      "cosh",
      "asin",
      "acos",
      "atan",
      "asinh",
      "atanh",
      "ceil",
      "floor",
      "erf",
102 103 104 105 106 107 108 109 110
      "softmax",
      "sigmoid",
      "hard_swish",
      "depthwise_conv2d",
      "batch_norm",
      "concat",
      "tanh",
      "pad",
      "elementwise_add",
111
      "elementwise_sub",
112
      "elementwise_mul",
113
      "elementwise_div",
S
shentanyue 已提交
114
      "elementwise_pow",
C
ccrrong 已提交
115
      "equal",
116 117 118 119 120 121 122 123
      "dropout",
      "prelu",
      "conv2d_transpose",
      "depthwise_conv2d_transpose",
      "leaky_relu",
      "fc",
      "shuffle_channel",
      "swish",
L
LielinJiang 已提交
124
      "silu",
125 126 127 128 129 130 131 132
      "split",
      "instance_norm",
      "gelu",
      "layer_norm",
      "scale",
      "stack",
      "transpose2",
      "transpose",
133 134
      "top_k",
      "top_k_v2",
135 136 137 138 139
      "flatten2",
      "flatten",
      "gather",
      "gather_nd",
      "yolo_box",
140
      "yolo_box_head",
141
      "arg_max",
142 143 144 145 146 147 148 149 150 151
      "roi_align",
      "affine_channel",
      "nearest_interp",
      "anchor_generator",
      "reduce_sum",
      "reduce_mean",
      "conv3d",
      "conv3d_transpose",
      "mish",
      "nearest_interp_v2",
152
      "bilinear_interp_v2",
153 154 155 156 157 158 159 160 161
      "pool3d",
      "deformable_conv",
      "relu6",
      "hard_sigmoid",
      "clip",
      "fused_embedding_eltwise_layernorm",
      "multihead_matmul",
      "skip_layernorm",
      "slice",
F
feng_shuai 已提交
162
      "strided_slice",
163
      "fused_preln_embedding_eltwise_layernorm",
164 165 166 167 168
      "preln_residual_bias",
      "c_allreduce_sum",
      "c_allreduce_min",
      "c_allreduce_max",
      "c_allreduce_prod",
F
feng_shuai 已提交
169
      "roll",
C
ccrrong 已提交
170
      "cast",
171 172 173
      "preln_skip_layernorm",
      "transformer_input_convert",
      "recover_padding",
174
      "remove_padding",
175
      "fill_constant",
176 177
      "sum",
      "shape",
178
      "squeeze2",
W
wenbin 已提交
179 180
      "unsqueeze2",
      "layernorm_shift_partition"};
181 182 183 184 185 186 187
  std::unordered_set<std::string> teller_set{
      "mul",
      "matmul",
      "conv2d",
      "conv2d_fusion",
      "pool2d",
      "relu",
188 189 190 191 192 193
      "elu",
      "selu",
      "softsign",
      "softplus",
      "stanh",
      "thresholded_relu",
Z
zhupengyang 已提交
194 195
      "exp",
      "log",
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
      "sqrt",
      "abs",
      "sin",
      "cos",
      "tan",
      "sinh",
      "cosh",
      "asin",
      "acos",
      "atan",
      "asinh",
      "atanh",
      "ceil",
      "floor",
      "erf",
211 212 213 214 215 216 217 218 219
      "softmax",
      "sigmoid",
      "hard_swish",
      "depthwise_conv2d",
      "batch_norm",
      "concat",
      "tanh",
      "pad",
      "elementwise_add",
220
      "elementwise_sub",
221
      "elementwise_mul",
222
      "elementwise_div",
S
shentanyue 已提交
223
      "elementwise_pow",
C
ccrrong 已提交
224
      "equal",
225 226 227 228 229 230 231 232
      "dropout",
      "prelu",
      "conv2d_transpose",
      "depthwise_conv2d_transpose",
      "leaky_relu",
      "fc",
      "shuffle_channel",
      "swish",
L
LielinJiang 已提交
233
      "silu",
234 235 236 237 238 239 240 241
      "split",
      "instance_norm",
      "gelu",
      "layer_norm",
      "scale",
      "stack",
      "transpose2",
      "transpose",
242 243
      "top_k",
      "top_k_v2",
244 245 246 247 248
      "flatten2",
      "flatten",
      "gather",
      "gather_nd",
      "yolo_box",
249
      "yolo_box_head",
250
      "arg_max",
251 252 253 254 255 256 257 258 259
      "roi_align",
      "affine_channel",
      "nearest_interp",
      "anchor_generator",
      "reduce_sum",
      "reduce_mean",
      "conv3d",
      "conv3d_transpose",
      "mish",
260
      "bilinear_interp_v2",
261 262 263 264 265 266 267 268 269 270
      "nearest_interp_v2",
      "pool3d",
      "deformable_conv",
      "relu6",
      "hard_sigmoid",
      "clip",
      "fused_embedding_eltwise_layernorm",
      "multihead_matmul",
      "skip_layernorm",
      "slice",
F
feng_shuai 已提交
271
      "strided_slice",
272
      "fused_preln_embedding_eltwise_layernorm",
273
      "preln_skip_layernorm",
274 275 276 277 278
      "preln_residual_bias",
      "c_allreduce_sum",
      "c_allreduce_min",
      "c_allreduce_max",
      "c_allreduce_prod",
F
feng_shuai 已提交
279
      "roll",
C
ccrrong 已提交
280
      "cast",
281 282 283
      "multiclass_nms3",
      "transformer_input_convert",
      "recover_padding",
284
      "remove_padding",
285
      "fill_constant",
286 287
      "sum",
      "shape",
288
      "squeeze2",
289
      "unsqueeze2",
W
wenbin 已提交
290 291
      "fused_token_prune",
      "layernorm_shift_partition"};
292 293
};

C
ccrrong 已提交
294 295
bool OpTeller::Tell(const framework::ir::Node* node,
                    bool use_no_calib_int8,
296 297 298
                    bool with_dynamic_shape) {
  const std::string op_type = node->Op()->Type();
  const framework::OpDesc desc = *node->Op();
299
  // do not support the op which is labeled the `skip_quant`
300
  if ((desc.HasAttr("namescope") &&
R
Ruibiao Chen 已提交
301
       PADDLE_GET_CONST(std::string, desc.GetAttr("op_namescope")) ==
302 303
           "/skip_quant_2/") ||
      desc.HasAttr("skip_quant"))
304
    return false;
305

306 307 308
  // do not support Attribute with Variable(s) Type
  if (HasUnsupportAttrVar(desc)) return false;

309
  for (auto& teller : tellers_) {
310 311 312 313 314 315 316 317 318
    std::unordered_set<std::string> act_op_list = {
        "relu",     "relu6", "sigmoid",
        "elu",      "selu",  "softsign",
        "softplus", "stanh", "thresholded_relu",
        "exp",      "log",   "sqrt",
        "abs",      "sin",   "cos",
        "tan",      "tanh",  "sinh",
        "cosh",     "asin",  "acos",
        "atan",     "asinh", "atanh",
L
LielinJiang 已提交
319 320
        "ceil",     "floor", "erf",
        "silu"};
321
    if (act_op_list.find(op_type) != act_op_list.end()) {
J
JingZhuangzhuang 已提交
322
      auto* block = desc.Block();
323 324 325 326 327 328
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
J
JingZhuangzhuang 已提交
329 330 331 332 333 334 335 336
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << op_type
                << " op does not support input's dim is 1 in tensorrt.";
        return false;
      }
337 338 339 340 341 342
#if !IS_TRT_VERSION_GE(7000)
      if (op_type == "erf") {
        VLOG(3) << op_type << " op does not support tensorrt.";
        return false;
      }
#endif
J
JingZhuangzhuang 已提交
343 344
    }

345 346 347 348 349 350
    // In static shape mode in TRT, we can't allow that op's input is a
    // 1D-tensor So we filter it here. Some op like elementwise having "Y" too,
    // but that is dealt with in the specified op, here just the common case
    if (!with_dynamic_shape) {
      std::string X_name;
      auto inputs = desc.Inputs();
351
      if (inputs.count("X") && !desc.Input("X").empty()) {
352
        X_name = desc.Input("X")[0];
353
      } else if (inputs.count("Input") && !desc.Input("Input").empty()) {
354 355 356 357 358 359 360 361 362 363 364 365 366
        X_name = desc.Input("Input")[0];
      }
      auto* block = desc.Block();
      if (block) {
        auto* x_var_desc = block->FindVar(X_name);
        // Can't get feed op's TensorDesc
        if (op_type != "feed" && x_var_desc && !x_var_desc->Persistable()) {
          const auto x_shape = x_var_desc->GetShape();
          if (x_shape.size() == 1) return false;
        }
      }
    }

367 368
    if (op_type == "pool2d") {
      std::vector<int> paddings =
R
Ruibiao Chen 已提交
369
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("paddings"));
370 371
      if (paddings.size() > 2) {
        return false;
372
      }
373 374 375 376 377 378 379 380 381 382
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "TRT Pool2d expect 1 input, but got "
                << desc.Input("X").size();
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "TRT Pool2d has only 1 output, but got "
                << desc.Output("Out").size();
        return false;
      }
W
wenbin 已提交
383 384
      if (desc.HasAttr("data_format")) {
        std::string data_format =
R
Ruibiao Chen 已提交
385
            PADDLE_GET_CONST(std::string, desc.GetAttr("data_format"));
W
wenbin 已提交
386 387 388 389
        if (data_format == "NHWC" || data_format == "NDHWC") {
          return false;
        }
      }
390 391 392 393
      if (!desc.HasAttr("pooling_type")) {
        return false;
      } else {
        std::string pool_type =
R
Ruibiao Chen 已提交
394
            PADDLE_GET_CONST(std::string, desc.GetAttr("pooling_type"));
395 396 397 398 399
        if (pool_type != "max" && pool_type != "avg") {
          VLOG(3) << "Wrong pool op type, the trt do not support the "
                  << pool_type << " pool type.";
          return false;
        }
400 401
        if (pool_type == "avg") {
          if (desc.HasAttr("global_pooling")) {
R
Ruibiao Chen 已提交
402
            if (!PADDLE_GET_CONST(bool, desc.GetAttr("global_pooling"))) {
403
              if (desc.HasAttr("exclusive")) {
R
Ruibiao Chen 已提交
404
                if (PADDLE_GET_CONST(bool, desc.GetAttr("exclusive"))) {
405
                  std::vector<int> ksize =
R
Ruibiao Chen 已提交
406
                      PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("ksize"));
407 408 409 410 411 412 413 414 415 416 417 418 419
                  for (size_t i = 0; i < ksize.size(); i++) {
                    if (ksize[i] <= paddings[i]) {
                      VLOG(3) << "the padding size should be less than the "
                                 "filter size "
                                 "for exclusive-counting pooling.";
                      return false;
                    }
                  }
                }
              }
            }
          }
        }
420 421 422 423
      }
    }

    if (op_type == "conv2d" || op_type == "conv2d_transpose" ||
424 425
        op_type == "conv2d_fusion" || op_type == "depthwise_conv2d" ||
        op_type == "depthwise_conv2d_transpose") {
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
      if (desc.Input("Input").size() != 1) {
        VLOG(3) << "TRT Conv2d expect 1 input, but got "
                << desc.Input("Input").size() << " input.";
        return false;
      }

      if (desc.Input("Filter").size() != 1) {
        VLOG(3) << "TRT Conv2d expect 1 filter, but got "
                << desc.Input("Filter").size() << " filter.";
        return false;
      }

      if (desc.HasAttr("enable_int8")) {
        if (op_type == "conv2d" || op_type == "conv2d_fusion") {
          if (!desc.HasAttr("Input_scale")) {
            VLOG(3) << "Input scale not found. TRT int8"
                       " requires conv/deconv to have "
                       "input quantization scales.";
            return false;
          }
        }
      }

449 450
      if (op_type == "conv2d_transpose" ||
          op_type == "depthwise_conv2d_transpose") {
451 452 453 454
        if (!desc.HasAttr("dilations")) {
          return false;
        } else {
          const std::vector<int> dilations =
R
Ruibiao Chen 已提交
455
              PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("dilations"));
456 457 458 459 460 461 462 463 464 465 466 467 468 469
          if (dilations[0] != 1 || dilations[1] != 1) {
            VLOG(3) << "In conv2d_transpose, Dilations must be (1, 1) for "
                       "tensorRT, but given ("
                    << dilations[0] << ", " << dilations[1] << ")";
            return false;
          }
        }
      }

      if (desc.Output("Output").size() != 1) {
        VLOG(3) << "TRT Conv2d expect 1 output, but got "
                << desc.Output("Output").size() << " output.";
        return false;
      }
470

W
wenbin 已提交
471
// strides > 1 and 'SAME' is only supported by trt7.0 above
472
#if !IS_TRT_VERSION_GE(7000)
W
wenbin 已提交
473 474 475 476
      if (op_type == "conv2d" || op_type == "conv2d_fusion" ||
          op_type == "depthwise_conv2d") {
        if (desc.HasAttr("padding_algorithm") && with_dynamic_shape) {
          auto padding_algorithm =
R
Ruibiao Chen 已提交
477
              PADDLE_GET_CONST(std::string, desc.GetAttr("padding_algorithm"));
W
wenbin 已提交
478 479
          if (padding_algorithm == "SAME" && desc.HasAttr("strides")) {
            const std::vector<int> strides =
R
Ruibiao Chen 已提交
480
                PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("strides"));
W
wenbin 已提交
481 482 483 484 485 486
            // there is no issue if strides.size() less than 2
            if (strides.size() > 1) {
              for (size_t i = 0; i < strides.size(); i++) {
                if (strides[i] > 1) return false;
              }
            }
487 488 489 490
          }
        }
      }
#endif
491 492
    }

W
wangxinxin08 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    if (op_type == "deformable_conv") {
      if (with_dynamic_shape) {
        VLOG(3) << "Deformable conv trt plugin does not support dynamic shape";
        return false;
      }
      auto* block = desc.Block();
      auto input_name = desc.Input("Input")[0];
      auto* input_desc = block->FindVar(input_name);
      const auto input_shape = input_desc->GetShape();

      if (input_shape.size() != 4) {
        VLOG(3) << "Input of deformable conv should be 4-D Tensor, but got "
                << input_shape.size();
        return false;
      }

      auto filter_name = desc.Input("Filter")[0];
      auto* filter_desc = block->FindVar(filter_name);
      const auto filter_shape = filter_desc->GetShape();

R
Ruibiao Chen 已提交
513
      int groups = PADDLE_GET_CONST(int, desc.GetAttr("groups"));
W
wangxinxin08 已提交
514 515 516 517 518 519 520 521
      if (input_shape[1] != filter_shape[1] * groups) {
        VLOG(3) << "The number of input channels should be equal to filter "
                << "channels * groups. But got input channels "
                << input_shape[1] << "filter channels " << filter_shape[1];
        return false;
      }

      const std::vector<int> strides =
R
Ruibiao Chen 已提交
522
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("strides"));
W
wangxinxin08 已提交
523 524 525 526 527 528 529
      if (strides.size() != 2) {
        VLOG(3) << "The size of strides should be 2, but got "
                << strides.size();
        return false;
      }

      const std::vector<int> paddings =
R
Ruibiao Chen 已提交
530
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("paddings"));
W
wangxinxin08 已提交
531 532 533 534 535 536 537
      if (paddings.size() != 2) {
        VLOG(3) << "The size of paddings shoule be 2, but got "
                << paddings.size();
        return false;
      }
    }

538 539
    if (op_type == "matmul") {
      auto* block = desc.Block();
540 541 542 543 544 545
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

      // not support broadcast
      auto* x_var_desc = block->FindVar(desc.Input("X")[0]);
      auto* y_var_desc = block->FindVar(desc.Input("Y")[0]);
      const auto x_shape = x_var_desc->GetShape();
      const auto y_shape = y_var_desc->GetShape();
      if (x_shape.size() != y_shape.size()) {
        VLOG(3)
            << "matmul op not support broadcast, please check inputs'shape. ";
        return false;
      }
      uint64_t dims = 2;
      for (size_t i = 0; i < x_shape.size() - dims; ++i) {
        if (x_shape[i] != y_shape[i] && (x_shape[i] == 1 || y_shape[i] == 1)) {
          VLOG(3) << "matmul op not support broadcast, please check "
                     "inputs'shape[i]. ";
          return false;
        }
      }

566 567 568 569 570
      for (auto& param_name : desc.Inputs()) {
        for (auto& var_name : param_name.second) {
          auto* var_desc = block->FindVar(var_name);
          const auto shape = var_desc->GetShape();
          if (shape.size() < 3) {
571
            VLOG(3)
P
Pei Yang 已提交
572 573
                << "matmul op dims < 3 not supported in tensorrt, but got dims "
                << shape.size() << ", so jump it.";
574 575 576 577 578
            return false;
          }
        }
      }
    }
W
Wilber 已提交
579 580 581 582 583 584 585 586 587 588 589 590
    if (op_type == "softmax") {
      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
    }
591 592 593 594 595
    if (op_type == "group_norm") {
      bool has_attrs = (desc.HasAttr("epsilon") && desc.HasAttr("groups"));
      if (has_attrs == false) return false;
      auto registry = GetPluginRegistry();
      if (registry == nullptr) return false;
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
      std::string layout_str =
          PADDLE_GET_CONST(std::string, desc.GetAttr("data_layout"));
      if (layout_str != "NCHW") {
        VLOG(3) << "Group norm trt plugin only support NCHW layout, but got "
                << layout_str;
        return false;
      }
      auto* block = desc.Block();
      if (block == nullptr) return false;
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      auto dtype = x_var_desc->GetDataType();
      if (dtype != 5) {
        VLOG(3) << "Group norm trt plugin only support float32";
        return false;
      }
612 613 614 615
    }
    if (op_type == "concat") {
      if (!desc.HasAttr("axis")) {
        return false;
W
Wilber 已提交
616
      }
R
Ruibiao Chen 已提交
617
      int axis = PADDLE_GET_CONST(int, desc.GetAttr("axis"));
618 619
      if (!with_dynamic_shape) {
        if (axis == 0) return false;
W
Wilber 已提交
620 621 622 623 624
      }
      auto concat_inputs = desc.Inputs();
      if (concat_inputs.find("AxisTensor") != concat_inputs.end()) {
        if (desc.Input("AxisTensor").size() >= 1) {
          return false;
625
        }
626 627
      }
    }
628 629 630
    if (op_type == "transpose2" || op_type == "transpose") {
      if (!desc.HasAttr("axis")) {
        return false;
631 632
      }
      std::vector<int> axis =
R
Ruibiao Chen 已提交
633
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("axis"));
634 635 636 637
      if (!with_dynamic_shape && axis[0] != 0) return false;
      if (axis.size() >= nvinfer1::Dims::MAX_DIMS) return false;

      auto* block = desc.Block();
638 639 640 641 642 643
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
644 645 646
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
W
wenbin 已提交
647
      if (axis.size() != x_shape.size()) return false;
648
      int dims = x_shape.size();
W
wenbin 已提交
649

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
      std::vector<int> perm(nvinfer1::Dims::MAX_DIMS);
      for (int i = 0; i < dims; i++) {
        perm[i] = axis[i];
      }
      auto is_valid_permutation = [&](int dims,
                                      const std::vector<int>& permutation) {
        std::bitset<nvinfer1::Dims::MAX_DIMS> found;
        for (int i = 0; i < dims; ++i) {
          const int x = permutation[i];
          if ((x < 0) || (x >= dims) || found[x])
            return false;  // Out of bounds or duplicate
          found.set(x);
        }
        return true;
      };
      if (!is_valid_permutation(dims, perm)) {
        VLOG(3) << "Invalid permutation dimensions for trt transpose op "
                   "converter: duplicate or out of bound.";
W
wenbin 已提交
668
        return false;
669 670
      }
    }
671
    if (op_type == "flatten2" || op_type == "flatten") {
672 673 674
      if (!desc.HasAttr("axis")) {
        return false;
      } else {
675 676
#if IS_TRT_VERSION_GE(7130)
#else
677
        if (with_dynamic_shape) return false;
678
#endif
R
Ruibiao Chen 已提交
679
        int axis = PADDLE_GET_CONST(int, desc.GetAttr("axis"));
680 681 682
        if (axis != 1) return false;
      }
    }
683 684
    if (op_type == "flatten_contiguous_range") {
      if (!with_dynamic_shape) {
R
Ruibiao Chen 已提交
685 686
        int start_axis = PADDLE_GET_CONST(int, desc.GetAttr("start_axis"));
        int stop_axis = PADDLE_GET_CONST(int, desc.GetAttr("stop_axis"));
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
        auto x_var_name = desc.Input("X")[0];
        auto* block = desc.Block();
        if (block == nullptr) {
          VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                     "Developers need to check whether block_desc is passed in "
                     "the pass.";
          return false;
        }
        auto* x_var_desc = block->FindVar(x_var_name);
        const auto x_shape = x_var_desc->GetShape();
        int dims = x_shape.size();
        if (start_axis < 0) start_axis += dims;
        if (start_axis == 0) {
          VLOG(3) << "TRT flatten_contiguous_range not support the "
                     "batch-dimension being changed";
          return false;
        }
        if (stop_axis < 0) stop_axis += dims;
        for (int i = start_axis; i <= stop_axis; ++i) {
          if (x_shape[i] < 0) {
            VLOG(3) << "On TRT static shape,flatten_contiguous_range input dim "
                       "should be > 0";
            return false;
          }
        }
      }
    }
714

715
    if (op_type == "gather") {
716 717 718 719 720 721 722 723 724
      auto gather_inputs = desc.Inputs();
      if (gather_inputs.find("Axis") != gather_inputs.end()) {
        if (desc.Input("Axis").size() >= 1) {
          return false;
        }
      }
      if (!with_dynamic_shape) {
        return false;
      } else {
725
        auto* block = desc.Block();
726 727 728 729 730 731
        if (block == nullptr) {
          VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                     "Developers need to check whether block_desc is passed in "
                     "the pass.";
          return false;
        }
F
feng_shuai 已提交
732
#if !IS_TRT_VERSION_GE(7000)
733 734 735 736 737 738
        auto* x_var_desc = block->FindVar(desc.Input("X")[0]);
        const auto x_shape = x_var_desc->GetShape();
        if (x_shape.size() == 1) {
          VLOG(3) << "Gather does not support 1-dimensional input in tensorrt";
          return false;
        }
F
feng_shuai 已提交
739
#endif
740
      }
741
    }
Z
zlsh80826 已提交
742

743
    if (op_type == "gather_nd") {
744 745
      if (!with_dynamic_shape) return false;

746
      auto* block = desc.Block();
747 748 749 750 751 752
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
753 754 755 756 757 758 759 760 761 762 763 764 765 766
      auto x_var_name = desc.Input("X")[0];
      auto index_var_name = desc.Input("Index")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      auto* index_var_desc = block->FindVar(index_var_name);

      // The index input must be int32 datatype.
      if (index_var_desc->GetDataType() !=
          paddle::framework::proto::VarType_Type::VarType_Type_INT32) {
        VLOG(3) << "gather_nd op Index input data type must be int32";
        return false;
      }

      const auto index_shape = index_var_desc->GetShape();
      const auto x_shape = x_var_desc->GetShape();
767 768 769 770 771 772
      if (x_shape.size() <= 2) {
        VLOG(3) << "gather_nd op requires the input's dimension to be greater "
                   "than 2";
        return false;
      }

773 774 775 776 777 778 779
      if (x_shape.size() != index_shape.size()) {
        VLOG(3) << "gather_nd op Index input dims size [" << index_shape.size()
                << " ] not equal to x dims size [" << x_shape.size() << "]";
        return false;
      }
    }

780 781 782 783
    if (op_type == "anchor_generator") {
      if (!with_dynamic_shape) return false;
    }

Z
zlsh80826 已提交
784 785 786 787 788 789
    if (op_type == "yolo_box") {
      if (with_dynamic_shape) return false;
      bool has_attrs =
          (desc.HasAttr("class_num") && desc.HasAttr("anchors") &&
           desc.HasAttr("downsample_ratio") && desc.HasAttr("conf_thresh") &&
           desc.HasAttr("clip_bbox") && desc.HasAttr("scale_x_y"));
Z
zlsh80826 已提交
790
      if (!has_attrs) return false;
Z
zlsh80826 已提交
791 792
    }

793 794 795 796 797 798
    if (op_type == "yolo_box_head") {
      if (with_dynamic_shape) return false;
      bool has_attrs = desc.HasAttr("class_num") && desc.HasAttr("anchors");
      if (!has_attrs) return false;
    }

799 800
    if (op_type == "arg_max") {
      int axis = desc.HasAttr("axis")
R
Ruibiao Chen 已提交
801
                     ? PADDLE_GET_CONST(int64_t, desc.GetAttr("axis"))
802
                     : -1;
R
Ruibiao Chen 已提交
803 804
      bool flatten = PADDLE_GET_CONST(bool, desc.GetAttr("flatten"));
      int dtype = PADDLE_GET_CONST(int, desc.GetAttr("dtype"));
805 806 807
      if (axis == 0 || flatten || dtype != 2) return false;
    }

808 809 810
    if (op_type == "affine_channel") {
      if (!desc.HasAttr("data_layout")) return false;
      auto data_layout = framework::StringToDataLayout(
R
Ruibiao Chen 已提交
811
          PADDLE_GET_CONST(std::string, desc.GetAttr("data_layout")));
812
      if (data_layout != framework::DataLayout::kNCHW) return false;
813 814

      auto* block = desc.Block();
815 816 817 818 819 820
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
821 822 823 824 825 826
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 2) {
        return false;
      }
827 828
    }

829
    if (op_type == "multiclass_nms" || op_type == "multiclass_nms3") {
Z
zlsh80826 已提交
830 831
      if (with_dynamic_shape) return false;
      auto* block = desc.Block();
832 833 834 835 836 837
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
838 839 840 841 842 843 844 845
      auto multiclass_nms_inputs = desc.Inputs();
      if (multiclass_nms_inputs.find("RoisNum") !=
          multiclass_nms_inputs.end()) {
        if (desc.Input("RoisNum").size() >= 1) {
          return false;
        }
      }
      for (auto& param_name : multiclass_nms_inputs) {
Z
zlsh80826 已提交
846 847 848 849
        for (auto& var_name : param_name.second) {
          auto* var_desc = block->FindVar(var_name);
          const auto shape = var_desc->GetShape();
          if (shape.size() != 3) {
850
            VLOG(3) << "multiclass_nms op dims != 3 not supported in tensorrt, "
Z
zlsh80826 已提交
851 852 853 854 855 856 857 858 859 860 861 862
                       "but got dims "
                    << shape.size() << ", so jump it.";
            return false;
          }
        }
      }
      bool has_attrs =
          (desc.HasAttr("background_label") &&
           desc.HasAttr("score_threshold") && desc.HasAttr("nms_top_k") &&
           desc.HasAttr("keep_top_k") && desc.HasAttr("normalized"));
      if (has_attrs == false) return false;

863 864 865
      // TODO(wangxinxin08): tricky solution because the outputs of batchedNMS
      // plugin are not constient with those of multiclass_nms3
      if (desc.HasAttr("nms_eta") == false) return false;
R
Ruibiao Chen 已提交
866
      auto nms_eta = PADDLE_GET_CONST(float, desc.GetAttr("nms_eta"));
867 868
      if (nms_eta <= 1.0) return false;

R
Ruibiao Chen 已提交
869
      auto nms_top_k = PADDLE_GET_CONST(int, desc.GetAttr("nms_top_k"));
Z
zlsh80826 已提交
870 871
      if (nms_top_k < 0) return false;

R
Ruibiao Chen 已提交
872
      auto keep_top_k = PADDLE_GET_CONST(int, desc.GetAttr("keep_top_k"));
Z
zlsh80826 已提交
873 874 875 876 877 878
      if (keep_top_k < 0) return false;

      auto registry = GetPluginRegistry();
      if (registry == nullptr) return false;
    }

879
    if (op_type == "nearest_interp") {
C
ccrrong 已提交
880 881
      std::vector<std::string> attrs{
          "interp_method", "align_corners", "scale", "out_h", "out_w"};
882 883 884
      for (auto const attr : attrs) {
        if (!desc.HasAttr(attr)) return false;
      }
885 886
      if (desc.HasAttr("data_layout")) {
        auto data_layout = framework::StringToDataLayout(
R
Ruibiao Chen 已提交
887
            PADDLE_GET_CONST(std::string, desc.GetAttr("data_layout")));
888 889 890 891
        if (data_layout != framework::DataLayout::kNCHW &&
            data_layout != framework::DataLayout::kNHWC)
          return false;
      }
892
      auto interp_method =
R
Ruibiao Chen 已提交
893
          PADDLE_GET_CONST(std::string, desc.GetAttr("interp_method"));
894
      if (interp_method != "nearest") return false;
R
Ruibiao Chen 已提交
895 896 897 898 899
      auto scale = PADDLE_GET_CONST(float, desc.GetAttr("scale"));
      auto out_h = PADDLE_GET_CONST(int, desc.GetAttr("out_h"));
      auto out_w = PADDLE_GET_CONST(int, desc.GetAttr("out_w"));
      auto align_corners =
          PADDLE_GET_CONST(bool, desc.GetAttr("align_corners"));
900 901 902 903
      if (!(scale > 0.f && (out_h <= 0 && out_w <= 0))) {
        if (out_h <= 0) {
          VLOG(3) << "out_h must be greater than 0 if scale is not set.";
          return false;
904
        }
905 906
        if (out_w <= 0) {
          VLOG(3) << "out_w must be greater than 0 if scale is not set.";
已提交
907 908
          return false;
        }
909
      }
910 911 912 913 914 915 916 917 918
      if ((scale <= 0.f) && with_dynamic_shape) {
        VLOG(3) << "dynamic shape not support scale not set.";
        return false;
      }
      // When align_corners = true, the paddle's and trt_layer's results has
      // diff
      if (align_corners && scale != 1) {
        return false;
      }
919
    }
920

921
    if (op_type == "nearest_interp_v2") {
C
ccrrong 已提交
922 923 924 925 926 927
      std::vector<std::string> attrs{"data_layout",
                                     "interp_method",
                                     "align_corners",
                                     "scale",
                                     "out_h",
                                     "out_w"};
928 929 930 931
      for (auto const attr : attrs) {
        if (!desc.HasAttr(attr)) return false;
      }
      auto data_layout = framework::StringToDataLayout(
R
Ruibiao Chen 已提交
932
          PADDLE_GET_CONST(std::string, desc.GetAttr("data_layout")));
933 934 935 936
      if (data_layout != framework::DataLayout::kNCHW &&
          data_layout != framework::DataLayout::kNHWC)
        return false;
      auto interp_method =
R
Ruibiao Chen 已提交
937
          PADDLE_GET_CONST(std::string, desc.GetAttr("interp_method"));
938
      if (interp_method != "nearest") return false;
R
Ruibiao Chen 已提交
939 940 941
      auto scale = PADDLE_GET_CONST(std::vector<float>, desc.GetAttr("scale"));
      auto out_h = PADDLE_GET_CONST(int, desc.GetAttr("out_h"));
      auto out_w = PADDLE_GET_CONST(int, desc.GetAttr("out_w"));
942
      if (!(out_h > 0 && out_w > 0)) {
W
wenbin 已提交
943
        if (scale.size() < 2) return false;
944 945 946 947 948 949 950 951
        if (scale[0] <= 0.f || scale[1] <= 0.f) {
          VLOG(3) << "scale factor must be greater than 0 if out_h or out_w is "
                     "not set.";
          return false;
        }
      }
    }

952
    if (op_type == "bilinear_interp_v2") {
C
ccrrong 已提交
953 954 955 956 957 958
      std::vector<std::string> attrs{"data_layout",
                                     "interp_method",
                                     "align_corners",
                                     "scale",
                                     "out_h",
                                     "out_w"};
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
      for (auto const attr : attrs) {
        if (!desc.HasAttr(attr)) {
          VLOG(3) << "The op_type " << op_type << " doesn't have the attr "
                  << attr << " and return false";
          return false;
        }
      }

      auto resize_inputs = desc.Inputs();
      if (resize_inputs.find("SizeTensor") != resize_inputs.end()) {
        if (desc.Input("SizeTensor").size() >= 1) {
          VLOG(3)
              << "The Paddle-TRT doesn't support the SizeTensor for op_type "
              << op_type;
          return false;
        }
      }

      if (resize_inputs.find("OutSize") != resize_inputs.end()) {
        if (desc.Input("OutSize").size() >= 1) {
          VLOG(3) << "The Paddle-TRT doesn't support the OutSize for op_type "
                  << op_type;
          return false;
        }
      }

      auto data_layout = framework::StringToDataLayout(
R
Ruibiao Chen 已提交
986
          PADDLE_GET_CONST(std::string, desc.GetAttr("data_layout")));
987 988 989 990 991 992 993
      if (data_layout != framework::DataLayout::kNCHW &&
          data_layout != framework::DataLayout::kNHWC) {
        VLOG(3) << "The op_type " << op_type
                << " is not NCHW or NHWC return false";
        return false;
      }
      auto interp_method =
R
Ruibiao Chen 已提交
994
          PADDLE_GET_CONST(std::string, desc.GetAttr("interp_method"));
995 996 997 998 999 1000
      if (interp_method != "bilinear") {
        VLOG(3) << "The interp_method of op_type " << op_type
                << " is not bilinear";
        return false;
      }

R
Ruibiao Chen 已提交
1001 1002
      auto align_corners =
          PADDLE_GET_CONST(bool, desc.GetAttr("align_corners"));
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
      if (align_corners != false) {
        VLOG(3)
            << "The bilinear_interp_v2 only supports align_corners with false.";
        return false;
      }

      bool has_scale_input_size =
          (resize_inputs.find("Scale") != resize_inputs.end());

      if (has_scale_input_size && desc.Input("Scale").size() != 1) {
        const std::vector<float> scale =
R
Ruibiao Chen 已提交
1014
            PADDLE_GET_CONST(std::vector<float>, desc.GetAttr("scale"));
1015 1016 1017 1018 1019 1020 1021
        if (scale.size() <= 1) {
          if (!desc.HasAttr("out_h") || !desc.HasAttr("out_w")) {
            VLOG(3) << "The op_type " << op_type
                    << " doesn't have Scale and the scale size <=1 and without "
                       "out_h / out_w, it will return false";
            return false;
          }
R
Ruibiao Chen 已提交
1022 1023
          auto out_h = PADDLE_GET_CONST(int, desc.GetAttr("out_h"));
          auto out_w = PADDLE_GET_CONST(int, desc.GetAttr("out_w"));
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
          if (!(out_h <= 0 && out_w <= 0)) {
            if (out_h <= 0) {
              VLOG(3) << "The op_type " << op_type
                      << "'s out_h must be greater than 0 if scale is not set.";
              return false;
            }
            if (out_w <= 0) {
              VLOG(3) << "The op_type " << op_type
                      << "'s out_w must be greater than 0 if scale is not set.";
              return false;
            }
          }
        } else {
          for (size_t i = 0; i < scale.size(); i++) {
            if (scale[i] <= 0 && with_dynamic_shape) {
              VLOG(3) << "dynamic shape not support Attr(scale[" << i << "]) "
                      << scale[i]
                      << " less than 1 and Input(Scale) vector not set.";
              return false;
            }
          }
        }
      }
    }

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    if (op_type == "hard_swish") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "HardSwish op has only 1 input, but got "
                << desc.Input("X").size();
        return false;
      }

      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "HardSwish op has only 1 output, but got "
                << desc.Output("Out").size();
        return false;
      }
    }

1063 1064 1065
    if (op_type == "squeeze2") {
      std::vector<int> axes;
      if (desc.HasAttr("axes")) {
R
Ruibiao Chen 已提交
1066
        axes = PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("axes"));
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
      }
      if (axes.size() == 0) {
        VLOG(3) << "The necessary attributes of the squeeze2 operator axes is "
                   "missing.";
        return false;
      }
      if (!with_dynamic_shape) {
        if (std::find(axes.begin(), axes.end(), 0) != axes.end()) {
          VLOG(3) << "Invalid squeeze axes. Axes having batch axis is not "
                     "supported in static shape";
          return false;
        }
      }
    }

    if (op_type == "unsqueeze2") {
      std::vector<int> axes;
      if (desc.HasAttr("axes")) {
R
Ruibiao Chen 已提交
1085
        axes = PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("axes"));
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
      }
      if (axes.size() == 0) {
        VLOG(3) << "The necessary attributes of the squeeze2 operator axes is "
                   "missing.";
        return false;
      }
      if (!with_dynamic_shape) {
        if (std::find(axes.begin(), axes.end(), 0) != axes.end()) {
          VLOG(3) << "Invalid squeeze axes. Axes having batch axis is not "
                     "supported in static shape";
          return false;
        }
      }
    }

1101
    if (op_type == "batch_norm") {
C
ccrrong 已提交
1102 1103
      const std::vector<std::string> bn_inputs = {
          "X", "Bias", "Mean", "Scale", "Variance"};
1104 1105 1106 1107 1108 1109 1110 1111 1112
      for (unsigned int i = 0; i < bn_inputs.size(); i++) {
        if (desc.Input(bn_inputs[i]).size() != 1) {
          VLOG(3) << "Invalid " << bn_inputs[i]
                  << "'s size of batch_norm TRT "
                     "converter. Expected 1, received "
                  << desc.Input(bn_inputs[i]).size() << ".";
          return false;
        }
      }
1113 1114 1115 1116 1117 1118
      auto batch_norm_inputs = desc.Inputs();
      if (batch_norm_inputs.find("MomentumTensor") != batch_norm_inputs.end()) {
        if (desc.Input("MomentumTensor").size() >= 1) {
          return false;
        }
      }
1119 1120 1121 1122 1123 1124
      if (desc.Output("Y").size() != 1) {
        VLOG(3) << "Invalid output Y's size of batch_norm TRT "
                   "converter. Expected 1, received "
                << desc.Output("Y").size() << ".";
        return false;
      }
W
Wilber 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
1135 1136 1137 1138 1139 1140 1141 1142 1143
    }

    if (op_type == "split") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "Invalid input X's size of split TRT converter. "
                   "Expected 1, received "
                << desc.Input("X").size() << ".";
        return false;
      }
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
      auto split_inputs = desc.Inputs();
      if (split_inputs.find("AxisTensor") != split_inputs.end()) {
        if (desc.Input("AxisTensor").size() >= 1) {
          return false;
        }
      }
      if (split_inputs.find("SectionsTensorList") != split_inputs.end()) {
        if (desc.Input("SectionsTensorList").size() >= 1) {
          return false;
        }
      }
1155 1156
      if (!desc.HasAttr("axis")) {
        return false;
1157
      }
R
Ruibiao Chen 已提交
1158
      int axis = PADDLE_GET_CONST(int, desc.GetAttr("axis"));
1159 1160 1161 1162 1163 1164 1165

      if (axis == 0) {
        VLOG(3) << "Invalid split axis. Split on batch is not supported in "
                   "TensorRT";
        return false;
      }
      auto* block = desc.Block();
1166 1167 1168 1169 1170 1171
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1172 1173 1174 1175 1176 1177 1178
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      size_t output_num = desc.Output("Out").size();
      std::vector<int> output_lengths;
      int num = 0;
      if (desc.HasAttr("num")) {
R
Ruibiao Chen 已提交
1179
        num = PADDLE_GET_CONST(int, desc.GetAttr("num"));
1180 1181 1182
      }
      if (desc.HasAttr("sections")) {
        output_lengths =
R
Ruibiao Chen 已提交
1183
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("sections"));
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
      }
      if (output_lengths.size() == 0 && num == 0) {
        VLOG(3) << "sections and num cannot be equal to 0 at the same time";
        return false;
      }
      if (with_dynamic_shape) {
#if IS_TRT_VERSION_GE(6000)
#else
        VLOG(3) << "You are running the TRT Dynamic Shape mode, need to "
                   "confirm that "
                   "your TRT version is no less than 6.0";
        return false;
#endif
      }
      axis += (axis < 0) ? x_shape.size() : 0;
      if (x_shape[axis] == -1) {
        VLOG(3) << "The (" << axis << ") dim of input should not be -1";
        return false;
      }
      if (output_lengths.size() == 0) {
        if (num > 0) {
          int64_t in_axis_dim = x_shape[axis];
          if (in_axis_dim % num != 0) {
            VLOG(3) << "Invalid number to split. Tensor split does not result"
                       " in an equal division of dimensions. Axis dim = "
                    << in_axis_dim << " num = " << num << "!= 0";
            return false;
          }
          size_t out_axis_dim = in_axis_dim / num;
          for (int i = 0; i < num; ++i) {
            output_lengths.push_back(out_axis_dim);
          }
1216 1217
        }
      }
1218 1219 1220 1221
      if (output_lengths.size() != output_num) {
        VLOG(3) << "The output_length should be equal to the output size.";
        return false;
      }
1222
    }
1223

1224 1225 1226 1227 1228 1229 1230 1231
    if (op_type == "scale") {
      auto scale_inputs = desc.Inputs();
      if (scale_inputs.find("ScaleTensor") != scale_inputs.end()) {
        if (desc.Input("ScaleTensor").size() >= 1) {
          return false;
        }
      }
      auto* block = desc.Block();
1232 1233 1234 1235 1236 1237
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1238 1239 1240
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
1241 1242 1243 1244 1245
      auto dtype = x_var_desc->GetDataType();
      // At present, only support float32 or float16 into trt.
      if (!(dtype == 5 || dtype == 4)) {
        return false;
      }
1246 1247 1248 1249
      if (!with_dynamic_shape && x_shape.size() == 1) {
        VLOG(3) << "Scale op does not support 1-dimensional input in tensorrt";
        return false;
      }
1250
    }
1251

F
feng_shuai 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    if (op_type == "roll") {
#if !IS_TRT_VERSION_GE(7000)
      VLOG(3) << "roll converter does not support trt versions below 7.0";
      return false;
#endif
      if (!with_dynamic_shape) {
        return false;
      }
    }

    if (op_type == "strided_slice") {
1263 1264 1265 1266 1267
#if !IS_TRT_VERSION_GE(7000)
      VLOG(3)
          << "strided_slice converter does not support trt versions below 7.0";
      return false;
#endif
F
feng_shuai 已提交
1268 1269 1270 1271 1272 1273 1274 1275
      if (!desc.HasAttr("axes") || !desc.HasAttr("starts") ||
          !desc.HasAttr("ends") || !desc.HasAttr("strides")) {
        VLOG(3)
            << "The necessary attributes of the strided_slice operator miss ";
        return false;
      }
    }

Z
zhoutianzi666 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    if (op_type == "rnn") {
      if (!with_dynamic_shape) {
        return false;
      }
      if (desc.HasAttr("mode")) {
        std::string mode = PADDLE_GET_CONST(std::string, desc.GetAttr("mode"));
        if (mode != "LSTM") return false;
      }
      if (desc.HasAttr("dropout_prob")) {
        float dropout_prob =
            PADDLE_GET_CONST(float, desc.GetAttr("dropout_prob"));
        if (dropout_prob > 1e-5) return false;
      }
      // not support following four inputs for rnn in paddle-trt
      auto rnn_inputs = desc.Inputs();
      if (rnn_inputs.find("SequenceLength") != rnn_inputs.end()) {
        if (desc.Input("SequenceLength").size()) {
          return false;
        }
      }
    }

    if (op_type == "fill_constant_batch_size_like") {
      if (!with_dynamic_shape) {
        return false;
      }
      if (!desc.HasAttr("input_dim_idx")) {
        return false;
      }
      if (!desc.HasAttr("output_dim_idx")) {
        return false;
      }
      if (!desc.HasAttr("shape")) {
        return false;
      }
      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
      auto x_var_name = desc.Input("Input")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      auto dtype = x_var_desc->GetDataType();
      // At present, only support float32 into trt.
      if (dtype != 5) {
        return false;
      }
    }

1327
    if (op_type == "slice") {
1328 1329
      if (desc.HasAttr("decrease_axis")) {
        std::vector<int> decrease_axis =
R
Ruibiao Chen 已提交
1330
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("decrease_axis"));
1331 1332 1333
        if (!with_dynamic_shape) {
          if (decrease_axis.end() !=
              std::find(decrease_axis.begin(), decrease_axis.end(), 0)) {
1334 1335
            return false;
          }
1336 1337 1338
        }
      }

1339
      if (!desc.HasAttr("axes") || !desc.HasAttr("starts") ||
1340 1341 1342
          !desc.HasAttr("ends")) {
        VLOG(3) << "The necessary attributes of the slice operator axes "
                   "or starts or ends are missing.";
1343 1344 1345
        return false;
      } else {
        std::vector<int> axes =
R
Ruibiao Chen 已提交
1346
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("axes"));
1347
        std::vector<int> starts =
R
Ruibiao Chen 已提交
1348
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("starts"));
1349
        std::vector<int> ends =
R
Ruibiao Chen 已提交
1350
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("ends"));
1351

1352
        if (axes.size() != starts.size() || axes.size() != ends.size()) {
1353 1354
          VLOG(3) << "The shape of attributes of the slice operator axes "
                     "or starts or ends are not equal.";
已提交
1355 1356
          return false;
        }
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        if (!with_dynamic_shape) {
          for (size_t i = 0; i < axes.size(); i++) {
            if (axes[i] == 0) {
              VLOG(3) << "Invalid slice axis. Slice on batch axis is not "
                         "supported in TensorRT";
              return false;
            }
          }
        }
      }
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
      // not support following four inputs for slice in paddle-trt
      auto slice_inputs = desc.Inputs();  // its size == 5
      if (slice_inputs.find("StartsTensor") != slice_inputs.end()) {
        if (desc.Input("StartsTensor").size()) {
          return false;
        }
      }
      if (slice_inputs.find("EndsTensor") != slice_inputs.end()) {
        if (desc.Input("EndsTensor").size()) {
          return false;
        }
      }
      if (slice_inputs.find("StartsTensorList") != slice_inputs.end()) {
        if (desc.Input("StartsTensorList").size()) {
          return false;
        }
      }
      if (slice_inputs.find("EndsTensorList") != slice_inputs.end()) {
        if (desc.Input("EndsTensorList").size()) {
          return false;
        }
      }
1389 1390
    }

1391
    if (op_type == "elementwise_add" || op_type == "elementwise_mul" ||
S
shentanyue 已提交
1392 1393
        op_type == "elementwise_sub" || op_type == "elementwise_div" ||
        op_type == "elementwise_pow") {
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "The input op's Input(\"X\").size() "
                   "should equal to 1, but received Input(\"X\").size() = "
                << desc.Input("X").size() << ".";
        return false;
      }
      if (desc.Input("Y").size() != 1) {
        VLOG(3) << "The input op's Input(\"Y\").size() "
                   "should equal to 1, but received Input(\"Y\").size() = "
                << desc.Input("Y").size() << ".";
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "The input op's Output(\"Out\").size() "
                   "should equal to 1, but reveceid Output(\"Out\").size() = "
                << desc.Output("Out").size() << ".";
        return false;
      }
1412
      auto* block = desc.Block();
1413 1414 1415 1416 1417 1418
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1419 1420 1421 1422
      auto* x_var_desc = block->FindVar(desc.Input("X")[0]);
      auto* y_var_desc = block->FindVar(desc.Input("Y")[0]);
      const auto x_shape = x_var_desc->GetShape();
      const auto y_shape = y_var_desc->GetShape();
1423 1424 1425 1426 1427 1428 1429

      // The case when x_shape.size() == 1 is dealt with in common case
      if (!with_dynamic_shape && (!y_var_desc->Persistable()) &&
          y_shape.size() == 1) {
        VLOG(3) << "Static shape in trt not support y is  a 1D intermediate "
                   "tensor in "
                   "elementwise op.";
1430 1431
        return false;
      }
1432 1433 1434 1435
      if (x_var_desc->Persistable() && !with_dynamic_shape) {
        VLOG(3)
            << "Input X is a parameter which is not supported for "
               "elementwise in tensorrt's static shape, swap x and y will work";
S
shentanyue 已提交
1436
        return false;
1437
      }
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
    }

    if (op_type == "stack") {
      if (!with_dynamic_shape) {
        VLOG(3)
            << "static shape mode is not supported for TRT stack.\n"
               "You can use the config.SetTRTDynamicShapeInfo(...) interface"
               " to set the shape information to run the dynamic shape "
               "mode.";
        return false;
      }
    }
1450 1451 1452 1453 1454 1455 1456 1457
    // remember that 1D input in static shape mode is filtered at the beginning
    if (op_type == "sum") {
      return true;
    }

    if (op_type == "shape" && !with_dynamic_shape) {
      return false;
    }
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

    if (op_type == "fused_embedding_eltwise_layernorm") {
      if (!with_dynamic_shape) {
        VLOG(3) << "fused_embedding_eltwise_layernorm should run on dynamic "
                   "shape mode.";
        return false;
      }
      if (desc.Input("Ids").size() != desc.Input("Embs").size()) {
        return false;
      }
    }

1470 1471
    if (op_type == "fused_preln_embedding_eltwise_layernorm") {
      if (!with_dynamic_shape) {
1472 1473 1474
        VLOG(3) << "fused_preln_embedding_eltwise_layernorm should run on "
                   "dynamic "
                   "shape mode.";
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
        return false;
      }
      if (desc.Input("Ids").size() != desc.Input("Embs").size()) {
        VLOG(3) << "The id and emb size of fused PrelnEmbEltwiseLayerNormOp "
                   "should be same ";
        return false;
      }
      if (!desc.HasAttr("enable_int8")) {
        VLOG(3) << "PrelnEmbEltwiseLayerNormOp must use int8 mode.";
        return false;
      }
    }

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    if (op_type == "gelu") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "gelu op has only 1 input, but got "
                << desc.Input("X").size();
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "gelu op has only 1 output, but got "
                << desc.Output("Out").size();
        return false;
      }
1499

1500
#if IS_TRT_VERSION_LT(7000)
1501
      if (desc.HasAttr("approximate")) {
1502
        VLOG(3) << "approximate gelu op needs TensorRT 7.0 and after";
R
Ruibiao Chen 已提交
1503
        if (PADDLE_GET_CONST(bool, desc.GetAttr("approximate"))) return false;
1504
      }
1505
#endif
1506 1507

      auto* block = desc.Block();
1508 1509 1510 1511 1512 1513
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1514

1515 1516 1517 1518 1519 1520 1521
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << "gelu op does not support input's dim is 1 in tensorrt.";
        return false;
      }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    }

    if (op_type == "layer_norm") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "input of layer_norm op converter should be 1, got "
                << desc.Input("X").size();
        return false;
      }
      if (desc.Input("Bias").size() != 1) {
        VLOG(3) << "Bias of layer_norm op converter should be 1, got "
                << desc.Input("Bias").size();
        return false;
      }
      if (desc.Input("Scale").size() != 1) {
        VLOG(3) << "Scale of layer_norm op converter should be 1, got "
                << desc.Input("Scale").size();
        return false;
      }
      if (desc.Output("Y").size() != 1) {
        VLOG(3) << "output of layer_norm op converter should be 1, got "
                << desc.Output("Y").size();
        return false;
      }
    }

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
    if (op_type == "fill_constant") {
      auto fill_constant_inputs = desc.Inputs();
      if (fill_constant_inputs.find("ValueTensor") !=
          fill_constant_inputs.end()) {
        if (desc.Input("ValueTensor").size()) return false;
      }
      if (fill_constant_inputs.find("ShapeTensor") !=
          fill_constant_inputs.end()) {
        if (desc.Input("ShapeTensor").size()) return false;
      }
      if (fill_constant_inputs.find("ShapeTensorList") !=
          fill_constant_inputs.end()) {
        if (desc.Input("ShapeTensorList").size()) return false;
      }
R
Ruibiao Chen 已提交
1561
      int dtype = PADDLE_GET_CONST(int, desc.GetAttr("dtype"));
1562 1563 1564 1565 1566 1567
      // only support int32, int64, float32
      if (!(dtype == 2 || dtype == 3 || dtype == 5)) {
        return false;
      }
    }

已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    if (op_type == "instance_norm") {
      if (with_dynamic_shape) {
        VLOG(3) << "trt instance_norm op does not support dynamic shape ";
        return false;
      }
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "input of instance_norm op converter should be 1, got "
                << desc.Input("X").size();
        return false;
      }
      if (desc.Input("Bias").size() != 1) {
        VLOG(3) << "Bias of instance_norm op converter should be 1, got "
                << desc.Input("Bias").size();
        return false;
      }
      if (desc.Input("Scale").size() != 1) {
        VLOG(3) << "Scale of instance_norm op converter should be 1, got "
                << desc.Input("Scale").size();
        return false;
      }
      if (desc.Output("Y").size() != 1) {
        VLOG(3) << "output of layer_norm op converter should be 1, got "
                << desc.Output("Y").size();
        return false;
      }
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608

      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() != 4) {
        VLOG(3) << "The instance_norm op only support 4-dimensional input in "
                   "tensorrt.";
        return false;
      }
已提交
1609 1610
    }

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    if (op_type == "leaky_relu") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "Invalid number of TRT leaky_relu op converter "
                   "inputs. Expected 1, but received "
                << desc.Input("X").size();
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "output of leaky_relu op converter should be 1, got "
                << desc.Output("Out").size();
        return false;
      }
    }

    if (op_type == "pad") {
R
Ruibiao Chen 已提交
1626 1627
      const float pad_value =
          PADDLE_GET_CONST(float, desc.GetAttr("pad_value"));
1628 1629 1630 1631
      if (pad_value != 0.0f) {
        VLOG(3) << "The pad layer of TRT only support zero.";
        return false;
      }
已提交
1632 1633
      std::vector<int64_t> shape;
      auto* block = desc.Block();
1634 1635 1636 1637 1638 1639
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
已提交
1640 1641 1642 1643 1644 1645 1646 1647
      for (auto& param_name : desc.Inputs()) {
        for (auto& var_name : param_name.second) {
          auto* var_desc = block->FindVar(var_name);
          shape = var_desc->GetShape();
        }
      }
      int nbDims = shape.size();
      std::vector<int> paddings =
R
Ruibiao Chen 已提交
1648
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("paddings"));
已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
      int pad_size = paddings.size();
      if (nbDims < 2) {
        return false;
      }
      if (nbDims * 2 != pad_size) {
        return false;
      }
      for (int i = 0; i < pad_size - 4; i++) {
        if (paddings[i] != 0) {
          return false;
        }
      }
1661 1662
    }

1663 1664
    if (op_type == "swish") {
      auto* block = desc.Block();
1665 1666 1667 1668 1669 1670
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1671 1672 1673 1674 1675 1676 1677 1678 1679
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << "swish op does not support input's dim is 1 in tensorrt.";
        return false;
      }
    }

1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
    if (op_type == "prelu") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "Invalid input X's size of prelu TRT converter. "
                   "Expected 1, received "
                << desc.Input("X").size() << ".";
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "Invalid output Out's size of prelu TRT converter. "
                   "Expected 1, received "
                << desc.Output("Out").size() << ".";
        return false;
      }
1693 1694

      auto* block = desc.Block();
1695 1696 1697 1698 1699 1700
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1701 1702 1703 1704 1705 1706 1707 1708 1709
      auto* var_desc = block->FindVar(desc.Input("Alpha")[0]);
      if (!var_desc) {
        VLOG(3) << "Variable Alpha of prelu TRT converter not found.";
        return false;
      }

      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
1710 1711 1712
      if (!with_dynamic_shape && x_shape.size() == 1) {
        VLOG(3) << "prelu op does not support input's dim is 1 in tensorrt "
                   "with static shape.";
1713 1714 1715
        return false;
      }

W
Wilber 已提交
1716 1717 1718 1719 1720 1721 1722
#if IS_TRT_VERSION_LT(7000)
      if (!with_dynamic_shape) {
        // TODO(inference): fix trt6 static plugin error.
        VLOG(3) << "prelu static plugin in trt6 has bug.";
        return false;
      }
#endif
1723 1724
    }

W
wangxinxin08 已提交
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
    if (op_type == "mish") {
      if (desc.Input("X").size() != 1) {
        VLOG(3) << "Invalid input X's size of mish TRT converter. "
                   "Expected 1, received "
                << desc.Input("X").size() << ".";
        return false;
      }
      if (desc.Output("Out").size() != 1) {
        VLOG(3) << "Invalid output Out's size of mish TRT converter. "
                   "Expected 1, received "
                << desc.Output("Out").size() << ".";
        return false;
      }

      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }

      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << "mish op does not support input's dim is 1 in tensorrt.";
        return false;
      }
    }

1756 1757 1758 1759 1760 1761 1762
    if (op_type == "roi_align") {
      if (!with_dynamic_shape) {
        VLOG(3) << "TRT roi align plugin only accept the dynamic shape, "
                   "because that "
                   "the roi_align will change the batch size.";
        return false;
      }
C
ccrrong 已提交
1763 1764 1765 1766
      std::vector<std::string> attrs{"pooled_height",
                                     "pooled_width",
                                     "spatial_scale",
                                     "sampling_ratio",
F
fengkuangxiaxia 已提交
1767
                                     "aligned"};
1768 1769 1770 1771 1772
      for (auto const attr : attrs) {
        if (!desc.HasAttr(attr)) return false;
      }

      const auto pooled_height =
R
Ruibiao Chen 已提交
1773
          PADDLE_GET_CONST(int, desc.GetAttr("pooled_height"));
1774 1775 1776
      if (pooled_height <= 0) return false;

      const auto pooled_width =
R
Ruibiao Chen 已提交
1777
          PADDLE_GET_CONST(int, desc.GetAttr("pooled_width"));
1778 1779 1780
      if (pooled_width <= 0) return false;

      const auto spatial_scale =
R
Ruibiao Chen 已提交
1781
          PADDLE_GET_CONST(float, desc.GetAttr("spatial_scale"));
1782 1783 1784 1785 1786 1787 1788 1789
      if (spatial_scale <= 0.f) return false;

      auto roi_align_inputs = desc.Inputs();
      if (roi_align_inputs.find("RoisNum") != roi_align_inputs.end()) {
        if (desc.Input("RoisNum").size() >= 1) {
          return false;
        }
      }
1790 1791 1792
    }

    if (op_type == "shuffle_channel") {
1793
#if !IS_TRT_VERSION_GE(8000)
1794 1795
      if (with_dynamic_shape) {
        VLOG(3) << "You are running the TRT Dynamic Shape mode, "
1796 1797
                   "the shuffle_channel op does not support dynamic shape "
                   "trt versions below 8.0 yet";
1798 1799
        return false;
      }
1800
#endif
1801 1802 1803 1804 1805 1806 1807 1808 1809
    }

    if (op_type == "skip_layernorm") {
      if (!with_dynamic_shape) {
        VLOG(3) << "the skip_layernorm does not support static shape yet";
        return false;
      }
    }

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
    if (op_type == "preln_skip_layernorm") {
      if (!with_dynamic_shape) {
        VLOG(3) << "the preln_skip_layernorm does not support static shape yet";
        return false;
      }
      if (!desc.HasAttr("enable_int8")) {
        VLOG(3) << "PrelnEmbEltwiseLayerNormOp must use int8 mode.";
        return false;
      }
    }

1821 1822 1823 1824 1825
    if (op_type == "multihead_matmul") {
      if (!with_dynamic_shape) {
        VLOG(3) << "the multihead_matmul does not support static shape yet";
        return false;
      }
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

      if (desc.HasAttr("enable_int8") && !desc.HasAttr("Input_scale")) {
        VLOG(3) << "Multihead layers must have input scale in int8 mode.";
        return false;
      }

      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
      auto* input_desc = block->FindVar(desc.Input("Input").front());
      const auto input_shape = input_desc->GetShape();
      const auto head_number =
R
Ruibiao Chen 已提交
1842
          PADDLE_GET_CONST(int, desc.GetAttr("head_number"));
F
feng_shuai 已提交
1843 1844 1845 1846 1847 1848 1849 1850 1851
      auto inputs = desc.Inputs();
      bool has_bias_qk = (inputs.find("BiasQK") == inputs.end()) ? false : true;
      if (has_bias_qk) {
        auto* biasqk_desc = block->FindVar(desc.Input("BiasQK").front());
        const auto biasqk_shape = biasqk_desc->GetShape();
        // The BiasQK's shape requires to be
        // [batch, 1, 1, length] or [batch, head, length, length].
        bool has_same_shape = head_number == biasqk_shape[1] &&
                              input_shape[1] == biasqk_shape[2] &&
1852
                              input_shape[1] == biasqk_shape[3];
F
feng_shuai 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
        bool is_broadcastable = biasqk_shape[1] == 1 && biasqk_shape[2] == 1 &&
                                input_shape[1] == biasqk_shape[3];
        if (!(has_same_shape || is_broadcastable)) {
          VLOG(3) << "The BiasQK's shape is invalid, expect [" << input_shape[0]
                  << ", 1, 1, " << input_shape[1] << "] or [" << input_shape[0]
                  << ", " << head_number << ", " << input_shape[1] << ", "
                  << input_shape[1] << "] but [" << biasqk_shape[0] << ", "
                  << biasqk_shape[1] << ", " << biasqk_shape[2] << ", "
                  << biasqk_shape[3] << "].";
          return false;
        }
      } else {
#if !IS_TRT_VERSION_GE(8000)
        VLOG(3) << "The version of TRT must be greater than 8000";
1867
        return false;
F
feng_shuai 已提交
1868
#endif
1869
      }
1870 1871
    }

1872
    if (op_type == "fc") {
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }

      // y'shapes == 2
      auto fc_inputs = desc.Inputs();
      std::string fc_y = "";
      if (fc_inputs.find("Y") != fc_inputs.end()) {
        fc_y = "Y";
      } else if (fc_inputs.find("W") != fc_inputs.end()) {
        fc_y = "W";
      } else {
        VLOG(3) << " input_y(fc_op) must be Y or W ";
        return false;
      }

      //  There is currently no input: Y(weight) more than two dimensions
      /*
      auto* y_var_desc = block->FindVar(desc.Input(fc_y)[0]);
      const auto y_shape = y_var_desc->GetShape();
      if (y_shape.size() != 2) {
        VLOG(3)
1899 1900
            << " input_y(fc_op)'shapes must be 2, but input_y(fc_op)'shapes =
      "
1901 1902 1903 1904 1905 1906
            << y_shape.size();
        return false;
      }
      // y_num_col_dims ==1
      if (desc.HasAttr("y_num_col_dims")) {
        int y_num_col_dims =
R
Ruibiao Chen 已提交
1907
            PADDLE_GET_CONST(int, desc.GetAttr("y_num_col_dims"));
1908 1909 1910 1911 1912 1913 1914
        if (y_num_col_dims != 1) {
          VLOG(3) << " fc_op'y_num_col_dims must be 1, but y_num_col_dims = "
                  << y_num_col_dims;
          return false;
        }
      }
      */
1915 1916
      int x_num_col_dims =
          desc.HasAttr("x_num_col_dims")
R
Ruibiao Chen 已提交
1917
              ? PADDLE_GET_CONST(int, desc.GetAttr("x_num_col_dims"))
1918
              : (desc.HasAttr("in_num_col_dims")
R
Ruibiao Chen 已提交
1919
                     ? PADDLE_GET_CONST(int, desc.GetAttr("in_num_col_dims"))
1920 1921
                     : 1);
      if (x_num_col_dims < 1) {
1922 1923 1924
        VLOG(3) << "fc_op expects x_num_col_dims >= 1, "
                   "but x_num_col_dims = "
                << x_num_col_dims;
1925 1926 1927
        return false;
      }
    }
1928

W
Wangzheee 已提交
1929
    if (op_type == "reshape" || op_type == "reshape2") {
1930 1931 1932
      if (with_dynamic_shape) {
        return true;
      }
W
Wangzheee 已提交
1933 1934
      if (!desc.HasAttr("shape")) {
        return false;
W
Wilber 已提交
1935 1936
      }
      // Paddle-TRT does not support the input tensors: Shape and ShapeTensor
1937
      auto reshape_inputs = desc.Inputs();
1938 1939 1940 1941 1942 1943 1944 1945 1946
      if (reshape_inputs.find("Shape") != reshape_inputs.end()) {
        if (desc.Input("Shape").size() >= 1) {
          return false;
        }
      }
      if (reshape_inputs.find("ShapeTensor") != reshape_inputs.end()) {
        if (desc.Input("ShapeTensor").size() >= 1) {
          return false;
        }
W
Wangzheee 已提交
1947
      }
W
Wilber 已提交
1948
      std::vector<int> shape =
R
Ruibiao Chen 已提交
1949
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("shape"));
W
Wilber 已提交
1950
      if (shape.size() >= nvinfer1::Dims::MAX_DIMS) return false;
X
xiaoxiaohehe001 已提交
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
      if (!with_dynamic_shape) {
        if (shape.size() == 1) {
          return false;
        }
        if (shape[0] == 0) {
          return true;
        } else {
          auto* block = desc.Block();
          auto x_var_name = desc.Input("X")[0];
          auto* x_var_desc = block->FindVar(x_var_name);
          const auto x_shape = x_var_desc->GetShape();
C
ccrrong 已提交
1962 1963 1964 1965
          int input_num = std::accumulate(
              x_shape.begin() + 1, x_shape.end(), 1, std::multiplies<int>());
          int shape_num = std::accumulate(
              shape.begin() + 1, shape.end(), 1, std::multiplies<int>());
X
xiaoxiaohehe001 已提交
1966 1967 1968 1969
          if (input_num == shape_num) {
            return true;
          }
        }
1970
        return false;
X
xiaoxiaohehe001 已提交
1971
      }
W
Wangzheee 已提交
1972
    }
1973

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    if (op_type == "clip") {
      // Paddle-TRT does not support the input tensors: Min and Max
      auto clip_inputs = desc.Inputs();
      if (clip_inputs.find("Min") != clip_inputs.end()) {
        if (desc.Input("Min").size() >= 1) {
          return false;
        }
      }
      if (clip_inputs.find("Max") != clip_inputs.end()) {
        if (desc.Input("Max").size() >= 1) {
          return false;
        }
      }

      auto* block = desc.Block();
1989 1990 1991 1992 1993 1994
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
1995 1996 1997 1998 1999 2000 2001 2002 2003
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << "clip op does not support input's dim is 1 in tensorrt.";
        return false;
      }
    }

W
wenbin 已提交
2004
    if (op_type == "reduce_sum" || op_type == "reduce_mean") {
2005 2006
      if (!(desc.HasAttr("keep_dim") && desc.HasAttr("dim") &&
            desc.HasAttr("reduce_all"))) {
W
wenbin 已提交
2007 2008
        VLOG(3) << "the " << op_type
                << " does not have attr (keep_dim or dim or "
2009
                   "reduce_all)";
2010 2011 2012 2013 2014 2015 2016 2017
        return false;
      }

      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
2018 2019
        return false;
      }
W
wenbin 已提交
2020 2021

      // The batch size dimension cannot be reduced if it's not dynamic shape.
2022
      auto* x_var_desc = block->FindVar(desc.Input("X")[0]);
W
wenbin 已提交
2023
      if (!with_dynamic_shape) {
R
Ruibiao Chen 已提交
2024
        if (PADDLE_GET_CONST(bool, desc.GetAttr("reduce_all"))) return false;
W
wenbin 已提交
2025
        std::vector<int32_t> dim =
R
Ruibiao Chen 已提交
2026
            PADDLE_GET_CONST(std::vector<int32_t>, desc.GetAttr("dim"));
2027
        const auto input_shape = x_var_desc->GetShape();
W
wenbin 已提交
2028
        for (auto x : dim) {
2029
          if (x == 0 || (x + input_shape.size() == 0)) return false;
W
wenbin 已提交
2030
        }
2031

2032
      } else {
R
Ruibiao Chen 已提交
2033 2034
        if (PADDLE_GET_CONST(bool, desc.GetAttr("reduce_all")) &&
            !PADDLE_GET_CONST(bool, desc.GetAttr("keep_dim")))
2035 2036
          return false;
      }
2037 2038 2039 2040 2041 2042 2043

      auto dtype = x_var_desc->GetDataType();
#if IS_TRT_VERSION_GE(7000)
      if (dtype != framework::proto::VarType::INT32 &&
          dtype != framework::proto::VarType::FP32) {
        VLOG(3) << "reduce op input data type must be int32 or float32";
        return false;
W
wenbin 已提交
2044
      }
2045 2046
#else
      if (dtype != framework::proto::VarType::FP32) {
2047 2048
        VLOG(3) << "reduce op input data type must be float32 using TensorRT "
                   "< 7.0";
2049 2050 2051
        return false;
      }
#endif
2052
    }
W
wenbin 已提交
2053 2054 2055
#if IS_TRT_VERSION_GE(7000)
    if (op_type == "tile") {
      // Paddle-TRT does not support the input tensors.
2056 2057 2058
      auto tile_inputs = desc.Inputs();
      if (tile_inputs.find("repeat_times_tensor") != tile_inputs.end()) {
        if (desc.Input("repeat_times_tensor").size() >= 1) {
W
wenbin 已提交
2059
          return false;
2060 2061 2062 2063
        }
      }
      if (tile_inputs.find("RepeatTimes") != tile_inputs.end()) {
        if (desc.Input("RepeatTimes").size() >= 1) {
W
wenbin 已提交
2064
          return false;
2065
        }
W
wenbin 已提交
2066 2067 2068 2069 2070
      }
      if (with_dynamic_shape) return false;
      if (!with_dynamic_shape && !desc.HasAttr("repeat_times")) return false;
    }
#endif
2071

2072 2073 2074 2075 2076
    // conv3d_transpose
    if (op_type == "conv3d_transpose") {
      // trt doen't support output_padding when < 8406
      // output_padding is usually set when stride > 1
#if !IS_TRT_VERSION_GE(8400)
2077 2078
      if (desc.HasAttr("output_padding")) {
        const std::vector<int> output_padding =
R
Ruibiao Chen 已提交
2079
            PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("output_padding"));
2080 2081 2082 2083 2084 2085
        if (output_padding.size() > 0) {
          int max_padding =
              *std::max_element(output_padding.begin(), output_padding.end());
          if (max_padding > 0) return false;
        }
      }
2086
#endif
2087 2088
    }

W
wenbin 已提交
2089 2090 2091
    if (op_type == "conv3d" || op_type == "conv3d_transpose") {
      if (desc.HasAttr("padding_algorithm")) {
        std::string padding_algorithm =
R
Ruibiao Chen 已提交
2092
            PADDLE_GET_CONST(std::string, desc.GetAttr("padding_algorithm"));
W
wenbin 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107

        // trt error is arised if conv3d_transpose and SAME
        if (op_type == "conv3d_transpose" && padding_algorithm == "SAME" &&
            !with_dynamic_shape) {
          return false;
        }
      }

#if !IS_TRT_VERSION_GE(7000)
      // looks like some issues with trt6.0
      if (with_dynamic_shape) {
        return false;
      }
#endif
      std::vector<int> paddings =
R
Ruibiao Chen 已提交
2108
          PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("paddings"));
W
wenbin 已提交
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129

      // conv3d and conv3d_transpose need padding check
      if (paddings.size() > 3) return false;

      if (desc.Input("Input").size() != 1) {
        VLOG(3) << "TRT Conv3d expect 1 input, but got "
                << desc.Input("Input").size() << " input.";
        return false;
      }

      if (desc.Input("Filter").size() != 1) {
        VLOG(3) << "TRT Conv3d expect 1 filter, but got "
                << desc.Input("Filter").size() << " filter.";
        return false;
      }

      if (op_type == "conv3d_transpose") {
        if (!desc.HasAttr("dilations")) {
          return false;
        } else {
          const std::vector<int> dilations =
R
Ruibiao Chen 已提交
2130
              PADDLE_GET_CONST(std::vector<int>, desc.GetAttr("dilations"));
W
wenbin 已提交
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
          if (dilations[0] != 1 || dilations[1] != 1 || dilations[2] != 1) {
            VLOG(3) << "In conv3d_transpose, Dilations must be (1, 1, 1) for "
                       "tensorRT, but given ("
                    << dilations[0] << ", " << dilations[1] << ", "
                    << dilations[2] << ")";
            return false;
          }
        }
      }

      if (desc.Output("Output").size() != 1) {
        VLOG(3) << "TRT Conv3d expect 1 output, but got "
                << desc.Output("Output").size() << " output.";
        return false;
      }
    }

2148 2149 2150 2151
    if (op_type == "hard_sigmoid") {
      if (!with_dynamic_shape) {
        auto* block = desc.Block();
        if (block == nullptr) {
2152 2153 2154
          VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                     "Developers need to check whether block_desc is passed in "
                     "the pass.";
2155 2156 2157 2158 2159
          return false;
        }
        auto x_var_name = desc.Input("X")[0];
        auto* x_var_desc = block->FindVar(x_var_name);
        const auto x_shape = x_var_desc->GetShape();
2160 2161 2162
        if (x_shape.size() == 1) {
          VLOG(3) << "Hard sigmoid does not support 1-dimensional input in "
                     "tensorrt";
2163 2164 2165 2166 2167
          return false;
        }
      }
    }

C
ccrrong 已提交
2168
    if (op_type == "cast") {
Z
zhoutianzi666 已提交
2169 2170 2171 2172
// trt 6015 result in Windows ppyolo_mbv3 TRT fp32 diff
#if !IS_TRT_VERSION_GE(7000)
      return false;
#endif
C
ccrrong 已提交
2173 2174 2175 2176 2177 2178
      if (!(desc.HasAttr("in_dtype") && desc.HasAttr("out_dtype"))) {
        VLOG(3) << "the " << op_type
                << " does not have attr (in_dtype or "
                   "out_dtype)";
        return false;
      }
R
Ruibiao Chen 已提交
2179 2180
      int in_dtype = PADDLE_GET_CONST(int, desc.GetAttr("in_dtype"));
      int out_dtype = PADDLE_GET_CONST(int, desc.GetAttr("out_dtype"));
C
ccrrong 已提交
2181 2182 2183 2184
      if ((in_dtype == 4 || in_dtype == 5) && out_dtype == 4) {
        VLOG(3) << "unsupport data type conversion";
        return false;
      }
2185 2186 2187 2188 2189
      if (in_dtype == 0) {
        VLOG(3) << "do not support input data type as bool now";
        return false;
      }
      if (!((in_dtype == 5 || in_dtype == 4 || in_dtype == 2) &&
C
ccrrong 已提交
2190
            (out_dtype == 5 || out_dtype == 4 || out_dtype == 2))) {
2191 2192
        VLOG(3) << "only valid conversions are: "
                   "(kFLOAT | kHALF | kINT32) -> (kFLOAT | kHALF | kINT32)";
C
ccrrong 已提交
2193 2194 2195 2196
        return false;
      }
    }

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    if (op_type == "top_k_v2" || op_type == "top_k") {
      auto* block = desc.Block();
      auto x_var_name = desc.Input("X")[0];
      auto* x_var_desc = block->FindVar(x_var_name);
      const auto x_shape = x_var_desc->GetShape();
      if (x_shape.size() == 1) {
        VLOG(3) << "top_k/top_k_v2 does not support 1-dimensional input in "
                   "tensorrt";
        return false;
      }
      if (desc.HasAttr("axis")) {
R
Ruibiao Chen 已提交
2208
        int axis = PADDLE_GET_CONST(int, desc.GetAttr("axis"));
2209 2210 2211 2212 2213 2214 2215
        if (axis == 0) {
          VLOG(3) << "top_k_v2 does not support axis == 0 in "
                     "tensorrt";
          return false;
        }
      }
      if (desc.HasAttr("sorted")) {
R
Ruibiao Chen 已提交
2216
        bool sorted = PADDLE_GET_CONST(bool, desc.GetAttr("sorted"));
2217 2218 2219 2220 2221 2222 2223 2224
        if (!sorted) {
          VLOG(3) << "top_k_v2 does not support results not sorted in "
                     "tensorrt";
          return false;
        }
      }
    }

2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
#if IS_TRT_VERSION_GE(8000)
    if (op_type == "sparse_fc" || op_type == "sparse_multihead_matmul") {
      if (!with_dynamic_shape) {
        VLOG(3) << "the sparse_fc and sparse_multihead_matmul does not support "
                   "static shape yet";
        return false;
      }
    }
#endif

C
ccrrong 已提交
2235 2236 2237 2238 2239
    if (op_type == "equal") {
#if !IS_TRT_VERSION_GE(8000)
      VLOG(3) << "compare is not supported when TensorRT < 8.0";
      return false;
#else
R
Ruibiao Chen 已提交
2240
      int axis = PADDLE_GET_CONST(int, desc.GetAttr("axis"));
C
ccrrong 已提交
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
      if (axis == 0) {
        return false;
      }
      auto* block = desc.Block();
      if (block == nullptr) {
        VLOG(3) << "The block desc is nullptr, we can't continue to analyze. "
                   "Developers need to check whether block_desc is passed in "
                   "the pass.";
        return false;
      }
#endif
    }

W
wenbin 已提交
2254 2255 2256 2257 2258 2259 2260 2261
    if (op_type == "layernorm_shift_partition") {
      if (!with_dynamic_shape) {
        VLOG(3) << "the layernorm_shift_partition does not support "
                   "static shape yet";
        return false;
      }
    }

2262
    if ((*teller)(op_type, desc, use_no_calib_int8)) return true;
2263
  }
W
wenbin 已提交
2264

2265 2266
  return false;
}
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295

bool OpTeller::HasUnsupportAttrVar(const framework::OpDesc& desc) const {
  const std::string op_type = desc.Type();
  auto has_attr_var = [&](const std::string& attr_name) -> bool {
    // If Attribute is Variable(s), HasAttr() will return False
    return !desc.HasAttr(attr_name, /*with_attr_var=*/false);
  };
  std::unordered_map<std::string, std::vector<std::string>> attrs_info = {
      {"dropout", {"dropout_prob"}},
      {"pool2d", {"ksize"}},
      {"arg_max", {"axis"}},
      {"reduce_mean", {"dim"}},
      {"reduce_sum", {"dim"}},
      {"squeeze2", {"axes"}},
  };

  bool flag = false;
  auto iter = attrs_info.find(op_type);
  if (iter != attrs_info.end()) {
    for (auto& attr_name : iter->second) {
      if (has_attr_var(attr_name)) {
        flag = true;
        break;
      }
    }
  }
  return flag;
}

2296 2297 2298 2299
OpTeller::OpTeller() { tellers_.emplace_back(new SimpleOpTypeSetTeller); }
}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle