unary.cc 174.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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. */

15
#include "paddle/phi/infermeta/unary.h"
16

L
Linjie Chen 已提交
17
#include <algorithm>
18
#include <set>
W
WJJ1995 已提交
19

20
#include "gflags/gflags.h"
21
#include "paddle/phi/common/data_type.h"
22
#include "paddle/phi/common/type_traits.h"
23
#include "paddle/phi/core/enforce.h"
W
wanghuancoder 已提交
24
#include "paddle/phi/core/flags.h"
25
#include "paddle/phi/core/infermeta_utils.h"
26
#include "paddle/phi/core/utils/data_type.h"
27
#include "paddle/phi/kernels/funcs/parse_qr_mode.h"
F
From00 已提交
28
#include "paddle/phi/kernels/funcs/pooling.h"
H
hong 已提交
29
#include "paddle/phi/kernels/funcs/slice_utils.h"
30
#include "paddle/phi/kernels/funcs/strided_slice.h"
31
#include "paddle/phi/kernels/funcs/unfold_functor.h"
32
#include "paddle/phi/kernels/funcs/unsqueeze.h"
33
#include "paddle/phi/kernels/impl/einsum_impl.h"
34

35
namespace phi {
36

37 38 39 40 41
namespace detail {
// Used in MatrixRankInferMeta
static DDim CheckAndGetOutputDim(const DDim& dim_x) {
  auto x_vec = phi::vectorize(dim_x);
  if (x_vec.size() == 2) {
42
    return phi::make_ddim({});
43 44 45 46 47 48
  }
  x_vec.erase(x_vec.end() - 2, x_vec.end());
  return phi::make_ddim(x_vec);
}
}  // namespace detail

49 50 51 52 53
void AffineGridInferMeta(const MetaTensor& input,
                         const IntArray& outputShape,
                         bool align_corners,
                         MetaTensor* output) {
  auto theta_dims = input.dims();
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  bool is_from_tensor = outputShape.FromTensor();
  if (!is_from_tensor) {
    PADDLE_ENFORCE_EQ(
        theta_dims.size(),
        3,
        phi::errors::InvalidArgument(
            "The input Theta's dimensions size should be 3. But received "
            "Theta's demensions size=[%d],  Theta's dimensions=[%s].",
            theta_dims.size(),
            theta_dims));

    PADDLE_ENFORCE_GE(
        outputShape.GetData().size(),
        4,
        phi::errors::InvalidArgument(
            "The size of attribute 'output_shape' in AffineGridOp should be >= "
            "4. But received output_shape's size=[%d].",
            outputShape.GetData().size()));

    PADDLE_ENFORCE_LE(
        outputShape.GetData().size(),
        5,
        phi::errors::InvalidArgument(
            "The size of attribute 'output_shape' in AffineGridOp should be <= "
            "5. But received output_shape's size=[%d].",
            outputShape.GetData().size()));
  }
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  PADDLE_ENFORCE_GE(theta_dims[1],
                    2,
                    phi::errors::InvalidArgument(
                        "The second dimesion of input 'theta' in AffineGridOp "
                        "should be >= 2. "
                        "But received second dimesion=[%d], dimesions=[%s]",
                        theta_dims[1],
                        theta_dims));

  PADDLE_ENFORCE_LE(theta_dims[1],
                    3,
                    phi::errors::InvalidArgument(
                        "The second dimesion of input 'theta' in AffineGridOp "
                        "should be <= 3. "
                        "But received second dimesion=[%d], dimesions=[%s]",
                        theta_dims[1],
                        theta_dims));

  PADDLE_ENFORCE_GE(
100 101 102
      theta_dims[2],
      3,
      phi::errors::InvalidArgument(
103
          "The third dimesion of input 'theta' in AffineGridOp should be >= 3. "
104 105 106 107
          "But received third dimesion=[%d], dimesions=[%s]",
          theta_dims[2],
          theta_dims));

108 109 110 111 112 113 114 115
  PADDLE_ENFORCE_LE(
      theta_dims[2],
      4,
      phi::errors::InvalidArgument(
          "The third dimesion of input 'theta' in AffineGridOp should be <= 4. "
          "But received third dimesion=[%d], dimesions=[%s]",
          theta_dims[2],
          theta_dims));
116
  if (outputShape.GetData().size() == 4 && !is_from_tensor) {
117 118 119 120 121 122
    // N * H * W * 2
    output->set_dims(phi::make_ddim({theta_dims[0], -1, -1, 2}));
  } else {
    // N * D * H * W * 3
    output->set_dims(phi::make_ddim({theta_dims[0], -1, -1, -1, 3}));
  }
123 124 125 126
  output->set_dtype(input.dtype());
  output->share_lod(input);
}

TaoTao Li's avatar
TaoTao Li 已提交
127 128 129 130 131 132 133 134
void AllGatherInferMeta(const MetaTensor& x, int nranks, MetaTensor* out) {
  auto dim = x.dims();
  dim[0] = dim[0] * nranks;
  if (dim[0] < 0) dim[0] = -1;
  out->set_dtype(x.dtype());
  out->set_dims(dim);
}

135 136 137 138 139
void AllReduceInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dtype(x.dtype());
  out->set_dims(x.dims());
}

TaoTao Li's avatar
TaoTao Li 已提交
140 141 142 143 144 145 146
void AllToAllInferMeta(const MetaTensor& x, MetaTensor* out) {
  auto dim = x.dims();
  if (dim[0] < 0) dim[0] = -1;
  out->set_dtype(x.dtype());
  out->set_dims(dim);
}

Z
zyfncg 已提交
147
void ArgMinMaxInferMeta(const MetaTensor& x,
148
                        const Scalar& axis,
Z
zyfncg 已提交
149 150 151 152 153 154 155 156 157 158 159
                        bool keepdims,
                        bool flatten,
                        int dtype,
                        MetaTensor* out,
                        MetaConfig config) {
  PADDLE_ENFORCE_EQ(
      (dtype < 0 || dtype == 2 || dtype == 3),
      true,
      phi::errors::InvalidArgument(
          "The attribute of dtype in argmin/argmax must be [%s] or [%s], but "
          "received [%s]",
160 161 162
          DataTypeToString(DataType::INT32),
          DataTypeToString(DataType::INT64),
          DataTypeToString(phi::TransToPhiDataType(dtype))));
Z
zyfncg 已提交
163

164 165 166
  if (!config.is_runtime && axis.FromTensor()) {
    std::vector<int64_t> vec;
    if (flatten) {
167 168 169 170 171
      if (keepdims) {
        vec = std::vector<int64_t>(x.dims().size(), -1);
      } else {
        vec = {};
      }
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    } else {
      if (keepdims) {
        vec = std::vector<int64_t>(x.dims().size(), -1);
      } else {
        vec = std::vector<int64_t>(x.dims().size() - 1, -1);
      }
    }
    out->set_dims(phi::make_ddim(vec));
    if (dtype == 2) {
      out->set_dtype(DataType::INT32);
    } else if (dtype == 3) {
      out->set_dtype(DataType::INT64);
    }
    return;
  }
  auto int_axis = axis.to<int64_t>();
  const auto& x_dims = x.dims();

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  auto x_rank = x.dims().size();
  if (x_rank > 0) {
    PADDLE_ENFORCE_GE(int_axis,
                      -x_rank,
                      phi::errors::InvalidArgument(
                          "'axis'(%d) must be greater than or equal to"
                          " -Rank(X)(%d).",
                          int_axis,
                          -x_rank));
    PADDLE_ENFORCE_LT(
        int_axis,
        x_rank,
        phi::errors::InvalidArgument(
            "'axis'(%d) must be less than Rank(X)(%d) of Input(X).",
            int_axis,
            x_rank));
  } else {
    // 0-dim tensor
208
    PADDLE_ENFORCE_EQ(int_axis == 0 || int_axis == -1,
209 210 211
                      true,
                      phi::errors::InvalidArgument(
                          "'axis'(%d) must be 0 or -1 if input tensor is "
212
                          "0-dim.",
213 214
                          int_axis));
  }
215 216

  if (int_axis < 0) int_axis += x_rank;
217

Z
zyfncg 已提交
218
  if (config.is_runtime) {
219
    if (dtype == phi::TransToProtoVarType(DataType::INT32)) {
Z
zyfncg 已提交
220
      int64_t all_element_num = 0;
221
      if (flatten) {
Z
zyfncg 已提交
222 223
        all_element_num = phi::product(x_dims);
      } else {
224
        all_element_num = x_dims[int_axis];
Z
zyfncg 已提交
225 226 227 228 229 230 231 232 233 234 235 236
      }
      PADDLE_ENFORCE_LE(
          all_element_num,
          INT_MAX,
          phi::errors::InvalidArgument(
              "The element num of the argmin/argmax input at axis is "
              "%d, is larger than int32 maximum value:%d, you must "
              "set the dtype of argmin/argmax to 'int64'.",
              all_element_num,
              INT_MAX));
    }
  }
237

Z
zyfncg 已提交
238
  std::vector<int64_t> vec;
239 240 241 242 243 244
  if (flatten) {
    if (keepdims) {
      vec = std::vector<int64_t>(x.dims().size(), 1);
    } else {
      vec = {};
    }
Z
zyfncg 已提交
245
  } else {
246
    for (int64_t i = 0; i < int_axis; i++) vec.emplace_back(x_dims[i]);
Z
zyfncg 已提交
247 248 249
    if (keepdims) {
      vec.emplace_back(static_cast<int64_t>(1));
    }
250
    for (int64_t i = int_axis + 1; i < x_rank; i++) vec.emplace_back(x_dims[i]);
Z
zyfncg 已提交
251
  }
252

Z
zyfncg 已提交
253 254 255 256 257 258 259 260
  out->set_dims(phi::make_ddim(vec));
  if (dtype == 2) {
    out->set_dtype(DataType::INT32);
  } else if (dtype == 3) {
    out->set_dtype(DataType::INT64);
  }
}

L
Linjie Chen 已提交
261 262 263 264 265 266 267
void ArgsortInferMeta(const MetaTensor& input,
                      int axis,
                      bool descending,
                      MetaTensor* output,
                      MetaTensor* indices) {
  auto in_dims = input.dims();
  auto num_dims = in_dims.size();
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  if (num_dims > 0) {
    PADDLE_ENFORCE_GE(axis,
                      -num_dims,
                      phi::errors::InvalidArgument(
                          "'axis'(%d) must be greater than or equal to"
                          " -num_dims(%d).",
                          axis,
                          -num_dims));
    PADDLE_ENFORCE_LT(
        axis,
        num_dims,
        phi::errors::InvalidArgument(
            "'axis'(%d) must be less than num_dims(%d).", axis, num_dims));
  } else {  // 0-dim tensor
    PADDLE_ENFORCE_EQ(
        axis == 0 || axis == -1,
        1,
        phi::errors::InvalidArgument(
            "'axis'(%d) must be 0 or -1 if input tensor is 0-dim.", axis));
  }
L
Linjie Chen 已提交
288 289 290 291 292 293 294

  output->share_dims(input);
  output->set_dtype(input.dtype());
  indices->share_dims(input);
  indices->set_dtype(DataType::INT64);
  output->share_lod(input);
  indices->share_lod(input);
295 296 297 298 299 300 301
}

void AsRealInferMeta(const MetaTensor& input, MetaTensor* output) {
  auto out_dims_v = phi::vectorize(input.dims());
  out_dims_v.push_back(2);
  auto out_dims = phi::make_ddim(out_dims_v);
  output->set_dims(out_dims);
302
  output->share_lod(input);
张春乔 已提交
303
  output->set_dtype(dtype::ToReal(input.dtype()));
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
}

void AsComplexInferMeta(const MetaTensor& input, MetaTensor* output) {
  auto in_dims = input.dims();
  const int input_rank = in_dims.size();
  PADDLE_ENFORCE_GE(
      input_rank,
      1,
      phi::errors::InvalidArgument(
          "The rank of input(X) is less than 1. "
          "Expected the rank of input(X) to be equal to or greater than 1."
          "But received rank of input(X) = %d",
          input_rank));
  const int last_dim_size = in_dims[input_rank - 1];
  PADDLE_ENFORCE_EQ(
      last_dim_size,
      2,
      phi::errors::InvalidArgument(
          "The size of the last dimension of input(X)"
          "does not equals 2."
          "Expected the size of last dimension of input(X) to be 2."
          "But received %d",
          last_dim_size));

  const phi::DDim out_dims(in_dims.Get(), input_rank - 1);
  output->set_dims(out_dims);
330
  output->share_lod(input);
L
Linjie Chen 已提交
331 332
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
void BatchSizeLikeInferMeta(const MetaTensor& x,
                            const std::vector<int>& shape,
                            int x_batch_size_dim,
                            int out_batch_size_dim,
                            MetaTensor* out) {
  PADDLE_ENFORCE_GT(
      shape.size(),
      0UL,
      phi::errors::InvalidArgument(
          "Shape size must be larger than 0, but received: %s.", shape.size()));
  std::vector<int64_t> shape_int64(shape.size(), 0);
  std::transform(shape.begin(), shape.end(), shape_int64.begin(), [](int a) {
    return static_cast<int64_t>(a);
  });
  auto output_dim = phi::make_ddim(shape_int64);

  int input_dim_size = static_cast<int>(x.dims().size());
  PADDLE_ENFORCE_GE(
      x_batch_size_dim,
      0,
      phi::errors::InvalidArgument("Input dimension index must be larger "
                                   "equal than 0, but received: %s.",
                                   x_batch_size_dim));
W
wanghuancoder 已提交
356 357 358 359 360 361 362
  PADDLE_ENFORCE(input_dim_size > x_batch_size_dim || input_dim_size == -1,
                 phi::errors::InvalidArgument(
                     "Input dimension size must be larger than "
                     "input dimension index, but received input "
                     "dimension size: %s, input dimension index: %s.",
                     input_dim_size,
                     x_batch_size_dim));
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

  int output_dim_size = static_cast<int>(shape.size());
  PADDLE_ENFORCE_GE(
      out_batch_size_dim,
      0,
      phi::errors::InvalidArgument("Output dimension index must be larger "
                                   "equal than 0, but received: %s.",
                                   out_batch_size_dim));
  PADDLE_ENFORCE_GT(
      output_dim_size,
      out_batch_size_dim,
      phi::errors::InvalidArgument(
          "Output dimension size must be larger than output dimension index, "
          "but received output dimension size: %s, output dimension index: "
          "%s.",
          output_dim_size,
          out_batch_size_dim));

  output_dim[out_batch_size_dim] = x.dims()[x_batch_size_dim];
  out->set_dims(output_dim);
}

385 386 387
void CastInferMeta(const MetaTensor& x, DataType out_dtype, MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_layout(x.layout());
388
  out->share_lod(x);
389 390 391 392 393 394
  // In inpalce case, setting the dtype of out will reset the dtype of x at the
  // same time, which will cause bugs, so move the dtype setting of out to the
  // kernel
  if (!(out->is_same_tensor(x))) {
    out->set_dtype(out_dtype);
  }
395 396
}

H
hong 已提交
397 398 399 400 401 402 403 404 405
void CConcatInferMeta(const MetaTensor& x, int nranks, MetaTensor* out) {
  phi::DDim dim = x.dims();
  dim[dim.size() - 1] = dim[dim.size() - 1] * nranks;
  if (dim[dim.size() - 1] < 0) dim[dim.size() - 1] = -1;
  out->set_dims(dim);
  out->set_layout(x.layout());
  out->set_dtype(x.dtype());
}

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
void SendV2InferMeta(const int peer, const int ring_id) {
  PADDLE_ENFORCE_GE(
      peer,
      0,
      errors::InvalidArgument(
          "The peer (%d) for send_v2 op must be non-negative.", peer));
  PADDLE_ENFORCE_GE(
      ring_id,
      0,
      errors::InvalidArgument(
          "The ring_id (%d) for send_v2 op must be non-negative.", ring_id));
}

void RecvV2InferMeta(int peer,
                     DataType dtype,
                     const std::vector<int>& out_shape,
                     MetaTensor* out) {
  PADDLE_ENFORCE_GE(
      peer,
      0,
      errors::InvalidArgument(
          "The peer (%d) for p_recv op must be non-negative.", peer));

  PADDLE_ENFORCE_GE(out_shape.size(),
                    1,
                    errors::InvalidArgument(
                        "The size of the output shape must be greater than 0 "
                        "but the value given is %d.",
                        out_shape.size()));

  for (size_t i = 0; i < out_shape.size(); ++i) {
    PADDLE_ENFORCE_GE(
        out_shape[i],
        1,
        errors::InvalidArgument("The shape attribute for recv must be set "
                                "explicitly, but the %dth element is %d which "
                                "is less than 1. Or dynamic_shape should be "
                                "set to True for both send_v2 and recv_v2.",
                                i,
                                out_shape[i]));
  }
  out->set_dtype(dtype);
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
void CholeskyInferMeta(const MetaTensor& x, bool upper, MetaTensor* out) {
  auto dims = x.dims();
  auto rank = dims.size();
  PADDLE_ENFORCE_GE(rank,
                    2,
                    errors::InvalidArgument(
                        "The Input(X) should have at least 2 dimensions. But "
                        "received a %d dimension tensor.",
                        rank));
  PADDLE_ENFORCE_EQ(
      dims[rank - 2],
      dims[rank - 1],
      errors::InvalidArgument(
          "The inner-most 2 dimensions of Input(X) all should be symmetric "
          "positive-definite matrices and have the same size. But received "
          "X's shape[-2] = %d and shape[-1] = %d.",
          dims[rank - 2],
          dims[rank - 1]));
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
}

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
void ClassCenterSampleInferMeta(const MetaTensor& label,
                                int num_classes,
                                int num_samples,
                                int ring_id,
                                int rank,
                                int nranks,
                                bool fix_seed,
                                int seed,
                                MetaTensor* remapped_label,
                                MetaTensor* sampled_local_class_center) {
  PADDLE_ENFORCE_EQ(
      label.dims().size(),
      1,
      errors::InvalidArgument("Rank of Input(Label) should be equal to 1, "
                              "but the value given is %d.",
                              label.dims().size()));
  PADDLE_ENFORCE_NOT_NULL(remapped_label,
                          phi::errors::InvalidArgument(
                              "output of remapped label should not be null."));
  PADDLE_ENFORCE_NOT_NULL(
      sampled_local_class_center,
      phi::errors::InvalidArgument(
          "output of sampled local class center should not be null."));
  remapped_label->set_dims(label.dims());
  remapped_label->set_dtype(label.dtype());
  sampled_local_class_center->set_dims(phi::make_ddim({num_samples}));
  sampled_local_class_center->set_dtype(label.dtype());
}

L
lyq 已提交
501 502 503 504 505 506 507 508 509 510 511 512
void ClipByNormInferMeta(const MetaTensor& x, float max_norm, MetaTensor* out) {
  PADDLE_ENFORCE_GT(
      max_norm,
      0,
      phi::errors::InvalidArgument("max_norm should be greater than 0. "
                                   "Received max_norm is %f.",
                                   max_norm));
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
  out->share_lod(x);
}

W
Wang Xin 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526
void CIdentityInferMeta(const MetaTensor& x,
                        int ring_id,
                        bool use_calc_stream,
                        bool use_model_parallel,
                        MetaTensor* out) {
  PADDLE_ENFORCE_GE(
      ring_id,
      0,
      errors::InvalidArgument(
          "The ring_id (%d) for c_identity must be non-negative.", ring_id));
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
}

527
void CreateLikeInferMeta(const MetaTensor& x, DataType dtype, MetaTensor* out) {
528 529
  out->set_dims(x.dims());
  out->set_dtype(dtype == DataType::UNDEFINED ? x.dtype() : dtype);
530
  out->set_layout(x.layout());
531 532
}

533 534 535 536 537 538
void CumInferMeta(const MetaTensor& x,
                  int axis,
                  bool flatten,
                  bool exclusive,
                  bool reverse,
                  MetaTensor* out) {
539 540 541 542 543
  auto x_dims = x.dims();
  if (flatten) {
    out->set_dims(phi::make_ddim({phi::product(x_dims)}));
    out->set_dtype(x.dtype());
  } else {
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    if (x_dims.size() > 0) {
      PADDLE_ENFORCE_GE(
          axis,
          -x_dims.size(),
          phi::errors::OutOfRange(
              "axis is out of range (expected to be in range of [%ld, "
              "%ld), but got %ld).",
              -(x_dims.size()),
              x_dims.size(),
              axis));
      PADDLE_ENFORCE_LT(
          axis,
          x_dims.size(),
          phi::errors::OutOfRange(
              "axis is out of range (expected to be in range of [%ld, "
              "%ld), but got %ld).",
              -(x_dims.size()),
              x_dims.size(),
              axis));
    } else {
      PADDLE_ENFORCE_EQ(
          (axis == 0 || axis == -1),
          true,
          errors::InvalidArgument("The axis must be -1 or 0 in 0D Tensor, "
                                  "but the value given is %d.",
                                  axis));
    }
571 572 573
    out->set_dims(x_dims);
    out->set_dtype(x.dtype());
  }
574

575 576 577
  out->share_lod(x);
}

W
WangZhen 已提交
578 579 580 581 582 583 584 585 586
void CumScalarAxisInferMeta(const MetaTensor& x,
                            const Scalar& axis,
                            bool flatten,
                            bool exclusive,
                            bool reverse,
                            MetaTensor* out) {
  CumInferMeta(x, axis.to<int>(), flatten, exclusive, reverse, out);
}

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
void CumWithIndicesInferMeta(const MetaTensor& x,
                             int axis,
                             int dtype,
                             MetaTensor* out,
                             MetaTensor* indices) {
  auto x_dims = x.dims();
  auto indices_type = phi::TransToPhiDataType(dtype);
  PADDLE_ENFORCE_EQ(
      (indices_type == DataType::INT32 || indices_type == DataType::INT64),
      true,
      phi::errors::InvalidArgument("dtype of indices must be int32 or int64"));

  if (indices_type == DataType::INT32) {
    int _axis;
    if (axis < 0) {
      _axis = axis + x_dims.size();
    } else {
      _axis = axis;
    }
    PADDLE_ENFORCE_LT(
        phi::vectorize(x_dims)[_axis],
        INT32_MAX,
        phi::errors::OutOfRange(
            "cummax with axis %ld may be overflow, set dtype int64 to continue",
            axis));
  }

  if (x_dims.size() > 0) {
    PADDLE_ENFORCE_GE(
        axis,
        -x_dims.size(),
        phi::errors::OutOfRange(
            "axis is out of range (expected to be in range of [%ld, "
            "%ld), but got %ld).",
            -(x_dims.size()),
            x_dims.size(),
            axis));
    PADDLE_ENFORCE_LT(
        axis,
        x_dims.size(),
        phi::errors::OutOfRange(
            "axis is out of range (expected to be in range of [%ld, "
            "%ld), but got %ld).",
            -(x_dims.size()),
            x_dims.size(),
            axis));
  } else {
    PADDLE_ENFORCE_EQ(
        (axis == 0 || axis == -1),
        true,
        errors::InvalidArgument("The axis must be -1 or 0 in 0D Tensor, "
                                "but the value given is %d.",
                                axis));
  }

  out->set_dims(x_dims);
  out->set_dtype(x.dtype());
  out->share_lod(x);
  indices->set_dims(x_dims);
  indices->set_dtype(indices_type);
  indices->share_lod(x);
}

650 651 652 653 654
void CropInferMeta(const MetaTensor& x,
                   const IntArray& shape,
                   const IntArray& offsets,
                   MetaTensor* out,
                   MetaConfig config) {
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  PADDLE_ENFORCE_NE(
      out,
      nullptr,
      errors::InvalidArgument("CropTensor should have output tensor out."));

  auto x_dim = x.dims();
  auto shape_dims = shape.GetData();
  auto offsets_vec = offsets.GetData();

  PADDLE_ENFORCE_EQ(shape_dims.size(),
                    x_dim.size(),
                    errors::InvalidArgument(
                        "The number of elements (%d) of attribute 'shape' for "
                        "CropTensor must be equal to the number of "
                        "dimensions (%d) of the input.",
                        shape_dims.size(),
                        x_dim.size()));

  if (config.is_runtime) {
    out->share_lod(x);
  }

  auto out_dims = std::vector<int64_t>(shape.size(), -1);
  for (size_t i = 0; i < shape_dims.size(); ++i) {
    if (shape_dims[i] > 0) {
      out_dims[i] = static_cast<int64_t>(shape_dims[i]);
    } else {
      if (shape_dims[i] == -1 && offsets_vec[i] != -1 && x_dim[i] != -1) {
        out_dims[i] = x_dim[i] - static_cast<int64_t>(offsets_vec[i]);
      }
    }
  }
  out->set_dims(phi::make_ddim(out_dims));
  out->set_dtype(x.dtype());
}

W
wuyefeilin 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
void DecodeJpegInferMeta(const MetaTensor& x,
                         const std::string& mode,
                         MetaTensor* out) {
  std::vector<int> out_dims;

  if (mode == "unchanged") {
    out_dims = {-1, -1, -1};
  } else if (mode == "gray") {
    out_dims = {1, -1, -1};
  } else if (mode == "rgb") {
    out_dims = {3, -1, -1};
  } else {
    errors::Fatal("The provided mode is not supported for JPEG files on GPU: ",
                  mode);
  }
  if (out != nullptr) {
    out->set_dims(phi::make_ddim(out_dims));
    out->set_dtype(x.dtype());
  }
}

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 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
void DiagEmbedInferMeta(
    const MetaTensor& x, int offset, int dim1, int dim2, MetaTensor* out) {
  auto x_dims = x.dims();

  PADDLE_ENFORCE_GE(
      dim1,
      -(x_dims.size() + 1),
      phi::errors::OutOfRange(
          "Dim1 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size() + 1),
          x_dims.size(),
          dim1));
  PADDLE_ENFORCE_LE(
      dim1,
      x_dims.size(),
      phi::errors::OutOfRange(
          "Dim1 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size() + 1),
          x_dims.size(),
          dim1));

  PADDLE_ENFORCE_GE(
      dim2,
      -(x_dims.size() + 1),
      phi::errors::OutOfRange(
          "Dim2 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size() + 1),
          x_dims.size(),
          dim2));
  PADDLE_ENFORCE_LE(
      dim2,
      x_dims.size(),
      phi::errors::OutOfRange(
          "Dim2 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size() + 1),
          x_dims.size(),
          dim2));

  int dim1_ = dim1 < 0 ? x_dims.size() + dim1 + 1 : dim1;
  int dim2_ = dim2 < 0 ? x_dims.size() + dim2 + 1 : dim2;
  int offset_ = std::abs(offset);

  PADDLE_ENFORCE_NE(dim1_,
                    dim2_,
                    phi::errors::InvalidArgument(
                        "diagonal dimensions should not be identical "
                        "%ld vs %ld.",
                        dim1,
                        dim2));

  int new_dim_len = offset_ + x_dims[x_dims.size() - 1];
  auto sizes = vectorize(x_dims);
  sizes.pop_back();
  sizes.insert(sizes.begin() + std::min(dim1_, dim2_), new_dim_len);
  sizes.insert(sizes.begin() + std::max(dim1_, dim2_), new_dim_len);
  out->set_dims(phi::make_ddim(sizes));
  out->set_dtype(x.dtype());
}

Z
zyfncg 已提交
775 776 777 778 779
void DiagInferMeta(const MetaTensor& x,
                   int offset,
                   float padding_value,
                   MetaTensor* out) {
  auto x_dims = x.dims();
780

781 782
  if (x_dims.size() <= 1) {
    int64_t size_ = (x_dims.size() == 1UL ? x_dims[0] : 1) + std::abs(offset);
Z
zyfncg 已提交
783 784 785 786 787 788 789 790 791 792 793 794
    out->set_dims({size_, size_});
    out->set_dtype(x.dtype());
  } else if (x_dims.size() == 2UL) {
    int64_t size_ = 0;
    if (offset >= 0) {
      // Note(LutaoChu): Do not use std::min here, otherwise the calculation
      // of `size_` will have unexpected result on Windows Python3.8
      if (x_dims[0] < x_dims[1] - offset) {
        size_ = x_dims[0];
      } else {
        size_ = x_dims[1] - offset;
      }
795
    } else {
Z
zyfncg 已提交
796 797 798 799 800 801 802
      // Note(LutaoChu): Do not use std::min here, otherwise the calculation
      // of `size_` will have unexpected result on Windows Python3.8
      if (x_dims[0] + offset < x_dims[1]) {
        size_ = x_dims[0] + offset;
      } else {
        size_ = x_dims[1];
      }
803
    }
Z
zyfncg 已提交
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
    out->set_dims({size_});
    out->set_dtype(x.dtype());
  } else {
    PADDLE_THROW(phi::errors::InvalidArgument(
        "The input tensor X's dimensions of DiagV2Op should be either 1 or "
        "2, but received %d.",
        x_dims.size()));
  }
}

void DiagonalInferMeta(const MetaTensor& input,
                       int offset,
                       int axis1,
                       int axis2,
                       MetaTensor* out) {
  auto x_dims = input.dims();
  int offset_ = offset;
  int axis1_ = axis1 < 0 ? x_dims.size() + axis1 : axis1;
  int axis2_ = axis2 < 0 ? x_dims.size() + axis2 : axis2;
  PADDLE_ENFORCE_GE(
      x_dims.size(),
      2,
      phi::errors::OutOfRange("Input's dim is out of range (expected at "
                              "least 2 dimensions, but got %ld).",
                              x_dims.size()));
  PADDLE_ENFORCE_LT(
      axis1_,
      x_dims.size(),
      phi::errors::OutOfRange(
          "Attr(axis1) is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          axis1));
Z
zhangbo9674 已提交
838 839 840 841 842 843 844 845 846
  PADDLE_ENFORCE_GE(
      axis1_,
      0,
      phi::errors::OutOfRange(
          "Attr(axis1) is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          axis1));
Z
zyfncg 已提交
847 848 849 850 851 852 853 854 855
  PADDLE_ENFORCE_LT(
      axis2_,
      x_dims.size(),
      phi::errors::OutOfRange(
          "Attr(axis2) is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          axis2));
Z
zhangbo9674 已提交
856 857 858 859 860 861 862 863 864
  PADDLE_ENFORCE_GE(
      axis2_,
      0,
      phi::errors::OutOfRange(
          "Attr(axis2) is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          axis2));
Z
zyfncg 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
  PADDLE_ENFORCE_NE(
      axis1_,
      axis2_,
      phi::errors::InvalidArgument("The dimensions should not be identical "
                                   "%d vs %d.",
                                   axis1,
                                   axis2));

  auto out_dims = vectorize(x_dims);
  // from out_dims get the dim size of axis1_.
  auto axis1_size = out_dims[axis1_];
  auto axis2_size = out_dims[axis2_];
  // delete two dims by attr axis1 and axis2 from out_dims.
  /* example:
     out_dim = [2, 3, 4];
     axis1 = 0;
     axis2 = 1;
     according to the attr of axis1 and axis2, we get:
     out_dim = [4].
  */
  out_dims.erase(out_dims.begin() + std::max(axis1_, axis2_));
  out_dims.erase(out_dims.begin() + std::min(axis1_, axis2_));

  if (offset_ == 0) {
    out_dims.push_back(std::min(axis1_size, axis2_size));
  } else if (offset_ > 0) {
    if ((axis2_size - offset_) > 0) {
      out_dims.push_back(std::min(axis1_size, axis2_size - offset_));
    } else {
      out_dims.push_back(0);
    }
  } else {
    if ((axis1_size + offset_) > 0) {
      out_dims.push_back(std::min(axis1_size + offset_, axis2_size));
    } else {
      out_dims.push_back(0);
    }
  }
  out->set_dims(phi::make_ddim(out_dims));
W
wanghuancoder 已提交
904
  out->set_dtype(input.dtype());
Z
zyfncg 已提交
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918 919
void DirichletInferMeta(const MetaTensor& alpha, MetaTensor* out) {
  const auto alpha_dim = alpha.dims();
  PADDLE_ENFORCE_GE(alpha_dim.size(),
                    1,
                    phi::errors::InvalidArgument(
                        "ShapeError: The number of dimensions of 'Alpha' "
                        "must be greater than or euqal to 1. "
                        "But received Alpha's dimensions = %d,",
                        alpha_dim.size()));
  out->set_dims(alpha_dim);
  out->set_dtype(alpha.dtype());
}

920 921 922 923 924 925 926 927
void DistConcatInferMeta(const MetaTensor& x, int nranks, MetaTensor* out) {
  auto dim = x.dims();
  dim[dim.size() - 1] = dim[dim.size() - 1] * nranks;
  if (dim[dim.size() - 1] < 0) dim[dim.size() - 1] = -1;
  out->set_dtype(x.dtype());
  out->set_dims(dim);
}

928 929 930 931 932 933 934 935 936 937
void DistReduceInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dtype(x.dtype());
  out->set_dims(x.dims());
}

void DistBroadcastInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dtype(x.dtype());
  out->set_dims(x.dims());
}

938
void EigInferMeta(const MetaTensor& x, MetaTensor* out_w, MetaTensor* out_v) {
939
  phi::DDim x_dims = x.dims();
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
  int rank = x_dims.size();
  PADDLE_ENFORCE_GE(
      rank,
      2,
      phi::errors::InvalidArgument("Expects input tensor x to be not less than "
                                   "2 dimentions, but got dimention %d",
                                   rank));
  PADDLE_ENFORCE_EQ(x_dims[rank - 2],
                    x_dims[rank - 1],
                    phi::errors::InvalidArgument(
                        "The input matrix must be a square matrix, "
                        "but receive a matrix with %d rows and %d colums",
                        x_dims[rank - 2],
                        x_dims[rank - 1]));

  std::vector<int> batch_dims_vec{};
  for (int i = 0; i < rank - 1; ++i) {
    batch_dims_vec.emplace_back(x_dims[i]);
  }
959 960 961
  const DataType& x_dtype = x.dtype();
  const DataType& out_dtype =
      IsComplexType(x_dtype) ? x_dtype : ToComplexType(x_dtype);
962
  out_w->set_dims(phi::make_ddim(batch_dims_vec));
963
  out_w->set_dtype(out_dtype);
964
  out_v->set_dims(x_dims);
965
  out_v->set_dtype(out_dtype);
966 967
}

H
hong 已提交
968 969 970 971 972
void EmbeddingGradSparseInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
}

Z
zyfncg 已提交
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
void EighInferMeta(const MetaTensor& x,
                   const std::string& uplo,
                   MetaTensor* out_w,
                   MetaTensor* out_v) {
  auto input_dim = x.dims();
  auto rank = input_dim.size();

  PADDLE_ENFORCE_GE(rank,
                    2,
                    phi::errors::InvalidArgument(
                        "The Input(X) should have at least 2 dimensions."
                        "But received a %d dimension tensor.",
                        rank));
  PADDLE_ENFORCE_EQ(
      input_dim[rank - 2],
      input_dim[rank - 1],
      phi::errors::InvalidArgument(
          "Eigh op is designed for square matrix, consequently"
          "inner-most 2 dimensions of Input(X) should be symmetric."
          "But received X's shape[-2] = %d and shape[-1] = %d.",
          input_dim[rank - 2],
          input_dim[rank - 1]));

  std::vector<int64_t> values_dim;

  for (auto i = 0; i < rank - 1; i++) {
    values_dim.emplace_back(input_dim[i]);
  }
  out_w->set_dims(phi::make_ddim(values_dim));
1002
  out_w->set_dtype(dtype::ToReal(x.dtype()));
Z
zyfncg 已提交
1003
  out_v->set_dims(input_dim);
1004
  out_v->set_dtype(dtype::ToReal(x.dtype()));
Z
zyfncg 已提交
1005 1006
}

R
Ruibiao Chen 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
void EigvalsInferMeta(const MetaTensor& x, MetaTensor* out, MetaConfig config) {
  auto x_dims = x.dims();
  PADDLE_ENFORCE_GE(x_dims.size(),
                    2,
                    errors::InvalidArgument(
                        "The dimensions of Input(X) for Eigvals operator "
                        "should be at least 2, "
                        "but received X's dimension = %d, X's shape = [%s].",
                        x_dims.size(),
                        x_dims));

  if (config.is_runtime || !phi::contain_unknown_dim(x_dims)) {
    int last_dim = x_dims.size() - 1;
    PADDLE_ENFORCE_EQ(x_dims[last_dim],
                      x_dims[last_dim - 1],
                      errors::InvalidArgument(
                          "The last two dimensions of Input(X) for Eigvals "
                          "operator should be equal, "
                          "but received X's shape = [%s].",
                          x_dims));
  }

  auto out_dims = vectorize(x_dims);
  out_dims.resize(x_dims.size() - 1);

  const DataType& x_dtype = x.dtype();
  const DataType& out_dtype =
      IsComplexType(x_dtype) ? x_dtype : ToComplexType(x_dtype);

  out->set_dims(make_ddim(out_dims));
  out->set_dtype(out_dtype);
}

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
void EigvalshInferMeta(const MetaTensor& x,
                       const std::string& uplo,
                       bool is_test,
                       MetaTensor* out_w,
                       MetaTensor* out_v) {
  auto input_dim = x.dims();
  auto rank = input_dim.size();

  PADDLE_ENFORCE_GE(
      rank,
      2,
      errors::InvalidArgument("The Input(X) should have at least 2 dimensions."
                              "But received a %d dimension tensor.",
                              rank));
  PADDLE_ENFORCE_EQ(
      input_dim[rank - 2],
      input_dim[rank - 1],
      errors::InvalidArgument(
          "Eigvalsh op is designed for square matrix, consequently"
          "inner-most 2 dimensions of Input(X) should be symmetric."
          "But received X's shape[-2] = %d and shape[-1] = %d.",
          input_dim[rank - 2],
          input_dim[rank - 1]));

  std::vector<int64_t> values_dim;

  for (auto i = 0; i < rank - 1; i++) {
    values_dim.emplace_back(input_dim[i]);
  }

  if (out_w != nullptr) {
    out_w->set_dims(phi::make_ddim(values_dim));
    out_w->set_dtype(dtype::ToReal(x.dtype()));
  }
  if (out_v != nullptr) {
    out_v->set_dims(input_dim);
    out_v->set_dtype(x.dtype());
  }
}

1080 1081
void EinsumInferMeta(const std::vector<const MetaTensor*>& inputs,
                     const std::string& equation,
1082
                     MetaTensor* out) {
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  // collect the following informations to prepare einsum.
  LabelMap labelshape(0);
  LabelMap labeltype(LabelType::Reduction);
  std::vector<LabelMap> label2perms(inputs.size(), LabelMap(-1));
  std::vector<char> all_labels;
  std::vector<int> broadcast_dims;
  std::vector<int> output_dims;
  std::vector<std::vector<int>> ellipsis_dims(2);

  std::vector<DDim> input_dims;
  for (auto& i : inputs) {
    input_dims.push_back(i->dims());
  }
1096
  std::vector<std::string> input_strs;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  std::string right;
  ParseEinsumEquation(equation,
                      input_dims,
                      &labelshape,
                      &labeltype,
                      &all_labels,
                      &label2perms,
                      &ellipsis_dims,
                      &broadcast_dims,
                      &output_dims,
1107 1108
                      &right,
                      &input_strs);
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

  VLOG(3) << "Einsum Infershape: input dims:"
          << paddle::string::join_strings(input_dims, "\n");
  VLOG(3) << "Einsum Infershape: equation:" << equation;
  VLOG(3) << "Einsum Infershape: all_labels:"
          << paddle::string::join_strings(all_labels, ",");
  VLOG(3) << "Einsum Infershape: output dims:"
          << paddle::string::join_strings(output_dims, ",");
  VLOG(3) << "Label Type is : " << label_to_string(all_labels, labeltype);
  VLOG(3) << "Label Shape is : " << label_to_string(all_labels, labelshape);
1119 1120
  out->set_dims(make_ddim(output_dims));
  out->set_dtype(inputs[0]->dtype());
1121 1122 1123 1124 1125 1126 1127 1128
}

void EinsumRawInferMeta(const std::vector<const MetaTensor*>& inputs,
                        const std::string& equation,
                        MetaTensor* out,
                        std::vector<MetaTensor*> inner_cache,
                        std::vector<MetaTensor*> xshape) {
  EinsumInferMeta(inputs, equation, out);
1129 1130 1131 1132 1133 1134
  for (size_t i = 0; i < xshape.size(); ++i) {
    if (xshape[i] != nullptr) {
      xshape[i]->set_dims(inputs[i]->dims());
      xshape[i]->set_dtype(inputs[i]->dtype());
    }
  }
1135 1136
}

H
hong 已提交
1137 1138 1139 1140 1141 1142 1143
void ExpandInferMeta(const MetaTensor& x,
                     const IntArray& shape,
                     MetaTensor* out) {
#define MAX_RANK_SUPPORTED 6
  auto x_dims = x.dims();
  auto expand_shape = shape.GetData();

1144
  if (expand_shape.empty()) {
H
hong 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    expand_shape = std::vector<int64_t>(x_dims.size(), -1);
  }

  PADDLE_ENFORCE_GE(
      expand_shape.size(),
      static_cast<size_t>(x_dims.size()),
      phi::errors::InvalidArgument(
          "The number of elements (%d) of 'shape' for "
          "expand_v2 op must be greater than or equal to the rank "
          "(%d) of the input.",
          expand_shape.size(),
          static_cast<size_t>(x_dims.size())));
  PADDLE_ENFORCE_LE(
      expand_shape.size(),
      MAX_RANK_SUPPORTED,
      phi::errors::InvalidArgument("The number of elements (%d) of 'shape' for "
                                   "must not be greater than %d.",
                                   expand_shape.size(),
                                   MAX_RANK_SUPPORTED));
  PADDLE_ENFORCE_GE(
      expand_shape.size(),
1166
      0,
H
hong 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
      phi::errors::InvalidArgument("The number of elements (%d) of 'shape' for "
                                   "must be a positive integer.",
                                   expand_shape.size()));

  auto out_rank =
      std::max(static_cast<size_t>(x_dims.size()), expand_shape.size());
  std::vector<int64_t> out_shape(out_rank);
  for (size_t i = 0; i < expand_shape.size(); ++i) {
    if (x_dims[i] == -1) {
      out_shape[i] = -1;
    } else if (expand_shape[i] == -1) {
      if (static_cast<size_t>(x_dims.size()) > i) {
        out_shape[i] = x_dims[i];
      } else {
        out_shape[i] = -1;
      }
    } else if (expand_shape[i] == -2) {
      // We use -2 to represent the element in expand_shape is a var.
      out_shape[i] = -1;
    } else {
      PADDLE_ENFORCE_GT(
          expand_shape[i],
          0,
          phi::errors::InvalidArgument(
              "The %uth element of 'shape' for expand_v2 op must be "
              "greater than 0, but the value given is %d.",
              i,
              expand_shape[i]));
      out_shape[i] = expand_shape[i];
    }
  }

  out->set_dims(make_ddim(out_shape));
  out->set_dtype(x.dtype());
1201
  if (out_rank > 0 && out_shape[0] == x_dims[0]) {
H
hong 已提交
1202 1203 1204 1205
    out->share_lod(x);
  }
}

1206 1207 1208 1209 1210 1211 1212 1213 1214
void FillAnyLikeInferMeta(const MetaTensor& x,
                          const Scalar& value,
                          DataType dtype,
                          MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(dtype == DataType::UNDEFINED ? x.dtype() : dtype);
  out->share_lod(x);
}

Z
zhiboniu 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
void FillDiagonalInferMeta(
    const MetaTensor& x, float value, int offset, bool wrap, MetaTensor* out) {
  PADDLE_ENFORCE_NE(
      out,
      nullptr,
      phi::errors::InvalidArgument("Tensor out should not be null if "));
  auto x_dims = x.dims();
  out->set_dims(x_dims);
  out->set_dtype(x.dtype());
}

F
Feiyu Chan 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
void FFTC2CInferMeta(const MetaTensor& x,
                     const std::vector<int64_t>& axes,
                     const std::string& normalization,
                     bool forward,
                     MetaTensor* out,
                     MetaConfig config) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      phi::errors::InvalidArgument("Output of fft_c2c should not be null."));
  // only ensure that fft axes' size greater than zero at runtime
  // they might be -1 to indicate unknown size ar compile time
  if (config.is_runtime) {
    const phi::DDim x_dim = x.dims();
1239 1240
    for (auto axis : axes) {
      PADDLE_ENFORCE_GT(x_dim[axis],
F
Feiyu Chan 已提交
1241 1242
                        0,
                        phi::errors::InvalidArgument(
1243
                            "Invalid fft n-point (%d).", x_dim[axis]));
F
Feiyu Chan 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 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
    }
  }
  out->share_meta(x);
}

void FFTC2RInferMeta(const MetaTensor& x,
                     const std::vector<int64_t>& axes,
                     const std::string& normalization,
                     bool forward,
                     int64_t last_dim_size,
                     MetaTensor* out,
                     MetaConfig config) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      phi::errors::InvalidArgument("Output of fft_c2r should not be null."));
  const phi::DDim x_dim = x.dims();
  const int64_t last_fft_axis = axes.back();

  // only ensure that fft axes' size greater than zero at runtime
  // they might be -1 to indicate unknown size ar compile time
  if (config.is_runtime) {
    size_t signal_dims = axes.size();
    for (size_t i = 0; i < signal_dims - 1; i++) {
      PADDLE_ENFORCE_GT(x_dim[axes[i]],
                        0,
                        phi::errors::InvalidArgument(
                            "Invalid fft n-point (%d).", x_dim[axes[i]]));
    }
  }

  out->set_layout(x.layout());
  out->set_dtype(ToRealType(x.dtype()));
  phi::DDim out_dim = x_dim;

  if (last_dim_size > 0) {
    out_dim.at(last_fft_axis) = last_dim_size;
  } else if (config.is_runtime) {
    const int64_t input_last_dim_size = x_dim[last_fft_axis];
    const int64_t fft_n_point = (input_last_dim_size - 1) * 2;
    PADDLE_ENFORCE_GT(
        fft_n_point,
        0,
        phi::errors::InvalidArgument("Invalid fft n-point (%d).", fft_n_point));
    out_dim.at(last_fft_axis) = fft_n_point;
  } else {
    const int64_t input_last_dim_size = x_dim[last_fft_axis];
    out_dim.at(last_fft_axis) =
        input_last_dim_size == -1 ? -1 : (input_last_dim_size - 1) * 2;
  }
  out->set_dims(out_dim);
}

void FFTR2CInferMeta(const MetaTensor& x,
                     const std::vector<int64_t>& axes,
                     const std::string& normalization,
                     bool forward,
                     bool onesided,
                     MetaTensor* out,
                     MetaConfig config) {
  PADDLE_ENFORCE_NOT_NULL(
      out,
      phi::errors::InvalidArgument("Output of fft_r2c should not be null."));
  const phi::DDim x_dim = x.dims();

  // only ensure that fft axes' size greater than zero at runtime
  // they might be -1 to indicate unknown size ar compile time
  if (config.is_runtime) {
1311 1312
    for (auto axis : axes) {
      PADDLE_ENFORCE_GT(x_dim[axis],
F
Feiyu Chan 已提交
1313 1314
                        0,
                        phi::errors::InvalidArgument(
1315
                            "Invalid fft n-point (%d).", x_dim[axis]));
F
Feiyu Chan 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    }
  }

  out->set_layout(x.layout());
  out->set_dtype(ToComplexType(x.dtype()));
  if (!onesided) {
    out->share_dims(x);
  } else {
    phi::DDim out_dim = x.dims();
    const int64_t last_fft_axis = axes.back();
    const int64_t last_fft_dim_size = x_dim[last_fft_axis];
    out_dim.at(last_fft_axis) = last_fft_dim_size / 2 + 1;
    out->set_dims(out_dim);
  }
}

Z
zyfncg 已提交
1332 1333 1334 1335
void FlattenInferMeta(const MetaTensor& x,
                      int start_axis,
                      int stop_axis,
                      MetaTensor* out) {
1336 1337 1338 1339 1340 1341 1342 1343
  FlattenWithXShapeInferMeta(x, start_axis, stop_axis, out, nullptr);
}

void FlattenWithXShapeInferMeta(const MetaTensor& x,
                                int start_axis,
                                int stop_axis,
                                MetaTensor* out,
                                MetaTensor* xshape) {
Z
zyfncg 已提交
1344 1345
  auto x_dims = x.dims();
  int in_dims_size = x_dims.size();
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

  if (in_dims_size == 0) {
    PADDLE_ENFORCE_EQ(
        start_axis == 0 || start_axis == -1,
        true,
        phi::errors::InvalidArgument("The start_axis should be 0 or -1 when "
                                     "the input tensor is a 0D-Tensor"));
    PADDLE_ENFORCE_EQ(
        stop_axis == 0 || stop_axis == -1,
        true,
        phi::errors::InvalidArgument("The stop_axis should be 0 or -1 when the "
                                     "input tensor is a 0D-Tensor"));
    // this can ensure out shape {1}
    start_axis = 0;
    stop_axis = -1;
  }

Z
zyfncg 已提交
1363 1364 1365 1366 1367 1368
  if (start_axis < 0) {
    start_axis = start_axis + in_dims_size;
  }
  if (stop_axis < 0) {
    stop_axis = stop_axis + in_dims_size;
  }
1369 1370 1371 1372 1373 1374 1375
  if (in_dims_size > 0) {
    PADDLE_ENFORCE_GE(
        stop_axis,
        start_axis,
        phi::errors::InvalidArgument("The stop_axis should be greater"
                                     "than or equal to start_axis."));
  }
Z
zyfncg 已提交
1376 1377 1378

  int64_t outer = 1;
  std::vector<int32_t> out_shape;
1379
  out_shape.reserve(in_dims_size - stop_axis + start_axis + 1);
Z
zyfncg 已提交
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

  for (int i = 0; i < start_axis; ++i) {
    out_shape.push_back(x_dims[i]);
  }
  for (int i = start_axis; i <= stop_axis; i++) {
    if (x_dims[i] == -1 || outer == -1) {
      outer = -1;
    } else {
      outer *= x_dims[i];
    }
  }
  out_shape.push_back(outer);
  for (int i = stop_axis + 1; i < in_dims_size; i++) {
    out_shape.push_back(x_dims[i]);
  }
  const auto& out_dims = phi::make_ddim(out_shape);
  out->set_dims(out_dims);
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());

  if (x_dims[0] == out_dims[0]) {
    // Only pass LoD when the first dimension of output and Input(X)
    // are the same.
    out->share_lod(x);
  }
1405 1406 1407 1408 1409 1410 1411 1412
  if (xshape == nullptr) return;
  std::vector<int64_t> xshape_dims(x_dims.size() + 1);
  xshape_dims[0] = 0;
  for (int i = 0; i < x_dims.size(); ++i) {
    xshape_dims[i + 1] = x_dims[i];
  }
  xshape->set_dims(phi::make_ddim(xshape_dims));
  xshape->share_lod(x);
Z
zyfncg 已提交
1413 1414
}

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 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 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
void FlipInferMeta(const MetaTensor& x,
                   const std::vector<int>& axis,
                   MetaTensor* out) {
  auto x_dims = x.dims();
  auto flip_dims = axis;
  size_t flip_dims_size = axis.size();

  if (flip_dims_size > 0) {
    // check if dims axis within range
    auto min_max_d = std::minmax_element(flip_dims.begin(), flip_dims.end());
    PADDLE_ENFORCE_LT(*min_max_d.first,
                      x_dims.size(),
                      phi::errors::InvalidArgument(
                          "min(axes) should be less than the input tensor X's "
                          "axes of FlipOp. But received min(axes) = %d,  "
                          "X's axes = %d, X's shape = [%s]",
                          *min_max_d.first,
                          x_dims.size(),
                          x_dims));
    PADDLE_ENFORCE_GE(*min_max_d.first,
                      x_dims.size() * -1,
                      phi::errors::InvalidArgument(
                          "min(axes) should be greater than or equal to the "
                          "input tensor X's "
                          "axes of FlipOp times -1. But received "
                          "min(axes) = %d,  X's "
                          "axes = %d, X's shape = [%s]",
                          *min_max_d.first,
                          x_dims.size() * -1,
                          x_dims));
    PADDLE_ENFORCE_LT(*min_max_d.second,
                      x_dims.size(),
                      phi::errors::InvalidArgument(
                          "max(axes) should be less than the input tensor X's "
                          "axes of FlipOp. But received max(axes) = %d,  "
                          "X's axes = %d, X's shape = [%s]",
                          *min_max_d.second,
                          x_dims.size(),
                          x_dims));
    PADDLE_ENFORCE_GE(*min_max_d.second,
                      x_dims.size() * -1,
                      phi::errors::InvalidArgument(
                          "max(axes) should be greater than or equal to the "
                          "input tensor X's "
                          "axes of FlipOp times -1. But received "
                          "max(axes) = %d,  X's "
                          "axes = %d, X's shape = [%s]",
                          *min_max_d.second,
                          x_dims.size() * -1,
                          x_dims));

    // check duplicates in dims
    flip_dims.erase(std::unique(flip_dims.begin(), flip_dims.end()),
                    flip_dims.end());
    PADDLE_ENFORCE_EQ(flip_dims.size(),
                      flip_dims_size,
                      phi::errors::InvalidArgument(
                          "axes has duplicates, original flip axes size=%d, "
                          "but unique flip axes size=%d.)",
                          flip_dims_size,
                          flip_dims.size()));
  }

  VLOG(3) << "flip operator x.shape=" << x_dims;

  std::vector<int64_t> output_dims(x_dims.size());
  for (int i = 0; i < x_dims.size(); ++i) {
    output_dims[i] = x_dims[i];
  }

  out->set_dims(phi::make_ddim(output_dims));
  out->set_dtype(x.dtype());
  out->share_lod(x);
}

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 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 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 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 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
void FoldInferMeta(const MetaTensor& x,
                   const std::vector<int>& output_sizes,
                   const std::vector<int>& kernel_sizes,
                   const std::vector<int>& strides,
                   const std::vector<int>& paddings,
                   const std::vector<int>& dilations,
                   MetaTensor* out) {
  auto in_dims = x.dims();

  PADDLE_ENFORCE_EQ(
      output_sizes.size(),
      2,
      phi::errors::InvalidArgument(
          "It is expected output_size equals to 2, but got size %d",
          output_sizes.size()));
  PADDLE_ENFORCE_EQ(
      kernel_sizes.size(),
      2,
      phi::errors::InvalidArgument(
          "It is expected kernel_size equals to 2, but got size %d",
          kernel_sizes.size()));
  PADDLE_ENFORCE_EQ(
      strides.size(),
      2,
      phi::errors::InvalidArgument(
          "It is expected strides_size equals to 2, but got size %d",
          strides.size()));
  PADDLE_ENFORCE_EQ(
      paddings.size(),
      4,
      phi::errors::InvalidArgument(
          "It is expected paddings_size equals to 4, but got size %d",
          paddings.size()));

  PADDLE_ENFORCE_EQ(
      dilations.size(),
      2,
      phi::errors::InvalidArgument(
          "It is expected dilations_size equals to 2, but got size %d",
          dilations.size()));

  int output_height = output_sizes[0];
  int output_width = output_sizes[1];
  int kernel_height = kernel_sizes[0];
  int kernel_width = kernel_sizes[1];
  int dilation_height = dilations[0];
  int dilation_width = dilations[1];
  int stride_height = strides[0];
  int stride_width = strides[1];

  // check kernel_sizes
  PADDLE_ENFORCE_GT(kernel_height,
                    0,
                    phi::errors::InvalidArgument(
                        "The `kernel_sizes` should be greater than zero, "
                        "but received kernel_height: %d kernel_width: %d.",
                        kernel_sizes[0],
                        kernel_sizes[1]));
  PADDLE_ENFORCE_GT(kernel_width,
                    0,
                    phi::errors::InvalidArgument(
                        "The `kernel_sizes` should be greater than zero, "
                        "but received kernel_height: %d kernel_width: %d.",
                        kernel_sizes[0],
                        kernel_sizes[1]));
  // check strides
  PADDLE_ENFORCE_GT(stride_height,
                    0,
                    phi::errors::InvalidArgument(
                        "The `strides` should be greater than zero, "
                        "but received strides_height: %d strides_width: %d.",
                        strides[0],
                        strides[1]));
  PADDLE_ENFORCE_GT(stride_width,
                    0,
                    phi::errors::InvalidArgument(
                        "The `strides` should be greater than zero, "
                        "but received strides_height: %d strides_width: %d.",
                        strides[0],
                        strides[1]));
  // check dilations
  PADDLE_ENFORCE_GT(output_height,
                    1,
                    phi::errors::InvalidArgument(
                        "The `output_height` should be greater than one, "
                        "but received output_height: %d .",
                        output_height));
  PADDLE_ENFORCE_GT(output_width,
                    1,
                    phi::errors::InvalidArgument(
                        "The `output_width` should be greater than one, "
                        "but received output_width: %d .",
                        output_width));
  // check output size
  PADDLE_ENFORCE_GT(
      dilation_height,
      0,
      phi::errors::InvalidArgument(
          "The `dilations` should be greater than zero, "
          "but received dilations_height: %d dilations_width: %d.",
          dilations[0],
          dilations[1]));
  PADDLE_ENFORCE_GT(
      dilation_width,
      0,
      phi::errors::InvalidArgument(
          "The `dilations` should be greater than zero, "
          "but received dilations_height: %d dilations_width: %d.",
          dilations[0],
          dilations[1]));

  std::vector<int> out_dims;
  // batch_size
  out_dims.push_back(in_dims[0]);
  // output_plane
  int output_channels = in_dims[1] / (kernel_width * kernel_height);
  out_dims.push_back(output_channels);

  int blocks_height = (output_sizes[0] + 2 * paddings[0] -
                       (dilations[0] * (kernel_sizes[0] - 1) + 1)) /
                          strides[0] +
                      1;
  int blocks_width = (output_sizes[1] + 2 * paddings[1] -
                      (dilations[1] * (kernel_sizes[1] - 1) + 1)) /
                         strides[1] +
                     1;

  // check output height and width
  PADDLE_ENFORCE_GT(
      blocks_height,
      0,
      phi::errors::InvalidArgument(
          "The sliding blocks calculated from input spatial size (%d, %d), "
          "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
          "is (%d, %d), which should be a positive integer.",
          in_dims[2],
          in_dims[3],
          kernel_sizes[0],
          kernel_sizes[1],
          strides[0],
          strides[1],
          dilations[0],
          dilations[1],
          output_height,
          output_width));

  PADDLE_ENFORCE_GT(
      blocks_width,
      0,
      phi::errors::InvalidArgument(
          "The sliding blocks calculated from input spatial size (%d, %d), "
          "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
          "is (%d, %d), which should be a positive integer.",
          in_dims[2],
          in_dims[3],
          kernel_sizes[0],
          kernel_sizes[1],
          strides[0],
          strides[1],
          dilations[0],
          dilations[1],
          output_height,
          output_width));

  PADDLE_ENFORCE_EQ(
      blocks_height * blocks_width,
      in_dims[2],
      phi::errors::InvalidArgument(
          "Given input output_size (%d, %d), "
          "kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
          "which should be expected size of input's dimension "
          "2 to match the calculated number of %d * %d = %d, but got %d",
          output_height,
          output_width,
          kernel_sizes[0],
          kernel_sizes[1],
          strides[0],
          strides[1],
          dilations[0],
          dilations[1],
          blocks_height,
          blocks_width,
          blocks_height * blocks_width,
          in_dims[2]));

  PADDLE_ENFORCE_EQ(
      in_dims[1] % (kernel_sizes[0] * kernel_sizes[1]),
      0,
      phi::errors::InvalidArgument(
          "Expected size of input's dimension 1 to be divisible by the"
          "product of kernel_size, but got input.size(1)=%d and "
          "kernel_size=( %d"
          ", %d).",
          in_dims[1],
          kernel_sizes[0],
          kernel_sizes[1]));

  out_dims.push_back(output_height);
  out_dims.push_back(output_width);
  if (out != nullptr) {
    out->set_dims(phi::make_ddim(out_dims));
    out->set_dtype(x.dtype());
  }
}

C
Charles-hit 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 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 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
void FrameInferMeta(const MetaTensor& x,
                    int frame_length,
                    int hop_length,
                    int axis,
                    MetaTensor* out,
                    MetaConfig config) {
  PADDLE_ENFORCE_NOT_NULL(out,
                          phi::errors::InvalidArgument(
                              "Output(Out) of FrameOp should not be null."));
  const auto x_dims = x.dims();
  const int x_rank = x_dims.size();

  PADDLE_ENFORCE_GE(x_rank,
                    1,
                    phi::errors::InvalidArgument(
                        "Input(X) of FrameOp should be a tensor which contains "
                        "at least 1 dimension, but got rank %s.",
                        x_rank));
  PADDLE_ENFORCE_GT(hop_length,
                    0,
                    phi::errors::InvalidArgument(
                        "Attribute(hop_length) of FrameOp should be greater "
                        "than 0, but got %s.",
                        hop_length));
  PADDLE_ENFORCE_EQ(
      (axis == 0 || axis == -1),
      true,
      phi::errors::InvalidArgument(
          "Attribute(axis) of FrameOp should 0 or -1, but got %s.", axis));

  std::vector<int64_t> output_shape;
  int seq_length;
  int n_frames;

  int start_axis;
  int end_axis;

  if (axis == 0) {
    seq_length = x_dims[0];
    start_axis = 1;
    end_axis = x_rank - 1;
  } else {
    seq_length = x_dims[x_rank - 1];
    start_axis = 0;
    end_axis = x_rank - 2;
  }

  bool contain_unknown_dim = phi::contain_unknown_dim(x_dims);
  bool check = config.is_runtime || !contain_unknown_dim;
  if (check) {
    PADDLE_ENFORCE_LE(frame_length,
                      seq_length,
                      phi::errors::InvalidArgument(
                          "Attribute(frame_length) of FrameOp should be less "
                          "equal than sequence length, but got (%s) > (%s).",
                          frame_length,
                          seq_length));
  }

  // It won't go into for loop when x_rank == 1U.
  for (int i = start_axis; i <= end_axis; i++) {
    output_shape.push_back(x_dims[i]);
  }

  if (seq_length == -1) {
    n_frames = -1;
  } else {
    n_frames = 1 + (seq_length - frame_length) / hop_length;
  }

  if (axis == 0) {
    // (n_frames, frame_length, ...)
    output_shape.insert(output_shape.begin(), frame_length);
    output_shape.insert(output_shape.begin(), n_frames);
  } else {
    // (..., frame_length, n_frames)
    output_shape.push_back(frame_length);
    output_shape.push_back(n_frames);
  }

  out->set_dims(phi::make_ddim(output_shape));
  out->set_dtype(x.dtype());
}

1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
void FullBatchSizeLikeInferMeta(const MetaTensor& x,
                                const std::vector<int>& shape,
                                const Scalar& val,
                                DataType dtype,
                                int x_batch_size_dim,
                                int out_batch_size_dim,
                                MetaTensor* out) {
  BatchSizeLikeInferMeta(x, shape, x_batch_size_dim, out_batch_size_dim, out);
  out->set_dtype(dtype);
}

Z
zyfncg 已提交
1790 1791 1792 1793 1794 1795 1796 1797
void GumbelSoftmaxInferMeta(const MetaTensor& x,
                            float temperature,
                            bool hard,
                            int axis,
                            MetaTensor* out) {
  UnchangedInferMetaCheckAxis(x, axis, out);
}

H
hong 已提交
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
void HistogramInferMeta(
    const MetaTensor& input, int64_t bins, int min, int max, MetaTensor* out) {
  PADDLE_ENFORCE_GE(bins,
                    1,
                    phi::errors::InvalidArgument(
                        "The bins should be greater than or equal to 1."
                        "But received nbins is %d",
                        bins));
  PADDLE_ENFORCE_GE(
      max,
      min,
      phi::errors::InvalidArgument("max must be larger or equal to min."
                                   "But received max is %d, min is %d",
                                   max,
                                   min));

  out->set_dims({bins});
  out->share_lod(input);
1816
  out->set_dtype(DataType::INT64);
H
hong 已提交
1817 1818
}

1819 1820 1821 1822 1823 1824 1825
void IdentityLossInferMeta(const MetaTensor& x,
                           int reduction,
                           MetaTensor* out) {
  if (reduction == 2) {
    out->set_dtype(x.dtype());
    out->set_dims(x.dims());
  } else {
1826
    out->set_dims(phi::make_ddim({}));
1827 1828 1829 1830
    out->set_dtype(x.dtype());
  }
}

Z
zyfncg 已提交
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
void IncrementInferMeta(const MetaTensor& x, float value, MetaTensor* out) {
  PADDLE_ENFORCE_EQ(
      product(x.dims()),
      1UL,
      errors::InvalidArgument("The number of elements in Input(X) should be 1."
                              "Now the number is %d.",
                              product(x.dims())));
  out->set_dims(x.dims());
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

static phi::DDim ValidateShape(const std::vector<int64_t> shape,
                               const phi::DDim& in_dims) {
  const int64_t in_size = phi::product(in_dims);
  auto in_dims_vec = phi::vectorize(in_dims);
  std::vector<int64_t> output_shape(shape.size(), 0);
  int64_t capacity = 1;
  int unk_dim_idx = -1;
1850

Z
zyfncg 已提交
1851
  for (size_t i = 0; i < shape.size(); ++i) {
1852 1853
    if (shape[i] == -1) {
      // only one dimension can be set to -1, whose size will be infered.
Z
zyfncg 已提交
1854 1855 1856 1857 1858 1859 1860 1861 1862
      PADDLE_ENFORCE_EQ(
          unk_dim_idx,
          -1,
          phi::errors::InvalidArgument(
              "Only one dimension value of 'shape' in ReshapeOp can "
              "be -1. But received shape = [%s], shape[%d] is also -1.",
              phi::make_ddim(shape),
              i));
      unk_dim_idx = i;
1863
      output_shape[i] = shape[i];
1864
    } else if (shape[i] == 0) {
1865
      if (static_cast<int>(i) < in_dims.size()) {
1866 1867
        output_shape[i] = in_dims[i];
      } else {
1868 1869 1870 1871 1872 1873
        PADDLE_ENFORCE_EQ(
            in_size,
            0,
            phi::errors::InvalidArgument("If The index of 0 in `shape` >= "
                                         "the input tensor X's dimensions, "
                                         "It can only be Zero-Sized Tensor"));
1874 1875
      }
      capacity *= output_shape[i];
Z
zyfncg 已提交
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
    } else {
      PADDLE_ENFORCE_GT(
          shape[i],
          0,
          phi::errors::InvalidArgument(
              "Each dimension value of 'shape' in ReshapeOp must not "
              "be negative except one unknown dimension. "
              "But received  shape = [%s], shape[%d] = %d.",
              phi::make_ddim(shape),
              i,
              shape[i]));
1887 1888
      output_shape[i] = shape[i];
      capacity *= output_shape[i];
Z
zyfncg 已提交
1889
    }
1890
  }
Z
zyfncg 已提交
1891

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
  if (capacity == 0) {
    PADDLE_ENFORCE_EQ(in_size,
                      0,
                      phi::errors::InvalidArgument(
                          "Only Zero-Size Tensor'shape can contain 0"));
    PADDLE_ENFORCE_EQ(unk_dim_idx,
                      -1,
                      phi::errors::InvalidArgument(
                          "can not rehsape %s to %s, because the unspecified "
                          "dimension %i can be any number and is ambiguous",
                          in_dims,
                          phi::make_ddim(shape),
                          unk_dim_idx));
1905 1906
  }

1907 1908 1909
  bool no_negative = std::all_of(in_dims_vec.cbegin(),
                                 in_dims_vec.cend(),
                                 [](int64_t i) { return i >= 0; });
1910
  if (unk_dim_idx != -1) {
1911 1912 1913
    // in compile time, no_negative may be False.
    if (no_negative) {
      output_shape[unk_dim_idx] = in_size / capacity;
1914 1915
      PADDLE_ENFORCE_EQ(
          output_shape[unk_dim_idx] * capacity,
1916
          in_size,
1917
          phi::errors::InvalidArgument(
1918 1919 1920 1921 1922 1923 1924
              "The 'shape' attribute in ReshapeOp is invalid. "
              "The input tensor X'size must be divisible by known "
              "capacity of 'shape'. "
              "But received X's shape = [%s], X's size = %d, "
              "'shape' is [%s], known capacity of 'shape' is %d.",
              in_dims,
              in_size,
1925
              phi::make_ddim(shape),
1926 1927
              capacity));
    } else {
1928
      // such as [-1, 8, 3]->[-1, 8], out_shape will remain [-1, 8]
1929 1930 1931
      output_shape[unk_dim_idx] = -1;
    }
  } else {
1932
    if (no_negative) {
1933 1934 1935
      PADDLE_ENFORCE_EQ(
          capacity,
          in_size,
1936
          phi::errors::InvalidArgument(
1937 1938 1939 1940 1941 1942 1943
              "The 'shape' in ReshapeOp is invalid. "
              "The input tensor X'size must be equal to the capacity of "
              "'shape'. "
              "But received X's shape = [%s], X's size = %d, 'shape' is "
              "[%s], the capacity of 'shape' is %d.",
              in_dims,
              in_size,
1944
              phi::make_ddim(shape),
1945 1946 1947 1948
              capacity));
    }
  }

1949
  return phi::make_ddim(output_shape);
1950 1951
}

1952 1953 1954 1955
void InferMetaFromVecValue(const MetaTensor& x,
                           const std::vector<int64_t>& shape,
                           MetaTensor* out) {
  auto x_dims = x.dims();
1956
  auto out_dims = ValidateShape(shape, x_dims);
1957 1958 1959
  out->set_dims(out_dims);
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());
1960
  if (x_dims.size() > 0 && (x_dims[0] == out_dims[0])) {
1961 1962
    // Only pass LoD when the first dimension of output and Input(X)
    // are the same.
1963
    out->share_lod(x);
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
void InverseInferMeta(const MetaTensor& x, MetaTensor* out) {
  auto input_dims = x.dims();
  int64_t input_rank = input_dims.size();
  PADDLE_ENFORCE_GE(
      input_rank,
      2,
      errors::InvalidArgument(
          "The dimension of Input(Input) is expected to be no less than 2. "
          "But received: Input(Input)'s dimension = %d, shape = [%s].",
          input_rank,
          input_dims));
  for (int64_t i = 0; i < input_rank; ++i) {
    PADDLE_ENFORCE_EQ(
        (input_dims[i] == -1) || (input_dims[i] > 0),
        true,
        errors::InvalidArgument(
            "Each dimension of input tensor is expected to be -1 or a "
            "positive number, but received %d. Input's shape is [%s].",
            input_dims[i],
            input_dims));
  }
  if (input_dims[input_rank - 2] > 0 && input_dims[input_rank - 1] > 0) {
    PADDLE_ENFORCE_EQ(input_dims[input_rank - 2],
                      input_dims[input_rank - 1],
                      errors::InvalidArgument(
                          "The last two dimensions are expected to be equal. "
                          "But received: %d and %d; "
                          "Input(Input)'s shape = [%s].",
                          input_dims[input_rank - 2],
                          input_dims[input_rank - 1],
                          input_dims));
  }

  out->set_dims(input_dims);
2001
  out->set_dtype(x.dtype());
2002 2003 2004
  out->share_lod(x);
}

W
WJJ1995 已提交
2005
void IsEmptyInferMeta(const MetaTensor& x, MetaTensor* out) {
2006
  out->set_dims(phi::make_ddim({}));
W
WJJ1995 已提交
2007 2008 2009
  out->set_dtype(DataType::BOOL);
}

Z
zyfncg 已提交
2010 2011 2012 2013 2014
void IsfiniteInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(DataType::BOOL);
}

2015 2016 2017 2018 2019 2020 2021 2022 2023
void KthvalueInferMeta(const MetaTensor& x,
                       int k,
                       int axis,
                       bool keepdim,
                       MetaTensor* out,
                       MetaTensor* indices,
                       MetaConfig config) {
  auto input_dims = x.dims();
  const int& dim_size = input_dims.size();
2024
  if (dim_size > 0) {
2025 2026 2027 2028 2029 2030 2031
    PADDLE_ENFORCE_LT(axis,
                      dim_size,
                      phi::errors::InvalidArgument(
                          "the axis must be [-%d, %d), but received %d .",
                          dim_size,
                          dim_size,
                          axis));
2032 2033 2034 2035 2036 2037 2038
    PADDLE_ENFORCE_GE(axis,
                      -dim_size,
                      phi::errors::InvalidArgument(
                          "the axis must be [-%d, %d), but received %d .",
                          dim_size,
                          dim_size,
                          axis));
2039 2040 2041 2042 2043 2044 2045 2046
  } else if (dim_size == 0) {
    // 0-dim tensor
    PADDLE_ENFORCE_EQ(axis == 0 || axis == -1,
                      true,
                      phi::errors::InvalidArgument(
                          "'axis'(%d) must be 0 or -1 if input tensor is "
                          "0-dim.",
                          axis));
2047
  }
2048 2049 2050 2051 2052 2053 2054 2055
  if (axis < 0) axis += dim_size;
  PADDLE_ENFORCE_GE(
      k,
      1,
      phi::errors::InvalidArgument(
          "the k in the kthvalue must >= 1, but received %d .", k));
  PADDLE_ENFORCE_GE(
      input_dims.size(),
2056 2057 2058
      0,
      phi::errors::InvalidArgument("input of kthvalue must have >= 0d shape"));
  if (dim_size > 0 && config.is_runtime) {
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
    PADDLE_ENFORCE_GE(
        input_dims[axis],
        k,
        phi::errors::InvalidArgument(
            "input of kthvalue must have >= %d columns in axis of %d",
            k,
            axis));
  }
  std::vector<int64_t> dimvec;
  for (int64_t i = 0; i < axis; i++) {
    dimvec.emplace_back(input_dims[i]);
  }
2071
  if (keepdim && dim_size > 0) {
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    dimvec.emplace_back(static_cast<int64_t>(1));
  }
  for (int64_t i = axis + 1; i < dim_size; i++) {
    dimvec.emplace_back(input_dims[i]);
  }
  DDim dims = phi::make_ddim(dimvec);
  out->set_dims(dims);
  out->share_lod(x);
  out->set_dtype(x.dtype());
  indices->set_dims(dims);
  indices->share_lod(x);
  indices->set_dtype(x.dtype());
}

2086 2087 2088 2089 2090
void LogsumexpInferMeta(const MetaTensor& input,
                        const std::vector<int64_t>& axis,
                        bool keepdim,
                        bool reduce_all,
                        MetaTensor* out) {
2091 2092 2093 2094 2095 2096 2097 2098
  auto input_rank = input.dims().size();
  // only supoort 0~4D, due to eigen template compile slow
  PADDLE_ENFORCE_LE(
      input_rank,
      4,
      errors::InvalidArgument("The input tensor X's dimensions of logsumexp "
                              "should be less or equal than 4. "));
  ReduceInferMetaBase(input, axis, keepdim, reduce_all, out);
2099 2100
}

2101 2102 2103 2104 2105 2106 2107 2108 2109
void MatrixPowerInferMeta(const MetaTensor& x, int n, MetaTensor* out) {
  auto dims = x.dims();
  auto n_dim = dims.size();
  PADDLE_ENFORCE_GE(n_dim,
                    2,
                    phi::errors::InvalidArgument(
                        "The Input(X) should have at least 2 dimensions. But "
                        "received a %d dimension tensor.",
                        n_dim));
2110 2111 2112 2113 2114
  for (int i = 0; i < n_dim; ++i)
    PADDLE_ENFORCE_NE(
        dims[i],
        0,
        phi::errors::InvalidArgument("The size of Input(X) should not be 0."));
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
  PADDLE_ENFORCE_EQ(dims[n_dim - 2],
                    dims[n_dim - 1],
                    phi::errors::InvalidArgument(
                        "The inner-most 2 dimensions of Input(X) all should "
                        "be square matrices "
                        "But received X's shape[-2] = %d and shape[-1] = %d.",
                        dims[n_dim - 2],
                        dims[n_dim - 1]));
  out->set_dims(dims);
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

L
Lin Manhui 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
void LUInferMeta(const MetaTensor& x,
                 bool pivot,
                 MetaTensor* out,
                 MetaTensor* pivots,
                 MetaTensor* infos) {
  auto x_dims = x.dims();
  int x_rank = x_dims.size();

  PADDLE_ENFORCE_NOT_NULL(
      out, phi::errors::InvalidArgument("Output(Out) should not be nullptr."));
  PADDLE_ENFORCE_GE(
      x_rank,
      2,
      phi::errors::InvalidArgument("The rank of input must greater than 2."));
  out->set_dims(x_dims);
  out->set_dtype(x.dtype());
  int m = x_dims[x_rank - 1];
  int n = x_dims[x_rank - 2];
  int min_mn = std::min(m, n);
  auto dims_vec = phi::vectorize(x_dims);
  PADDLE_ENFORCE_NOT_NULL(
      infos,
      phi::errors::InvalidArgument("Output(Infos) should not be nullptr."));
  if (x_rank == 2) {
    auto Infos_dim = std::vector<int>(1);
    infos->set_dims(phi::make_ddim(Infos_dim));
  } else {
    auto Infos_dim =
        std::vector<int>(dims_vec.begin(), dims_vec.begin() + x_rank - 2);
    infos->set_dims(phi::make_ddim(Infos_dim));
  }
  infos->set_dtype(DataType::INT32);
  if (pivot) {
    PADDLE_ENFORCE_NOT_NULL(
        pivots,
        phi::errors::InvalidArgument("Output(Pivots) should not be nullptr."));
    auto Pivots_dim =
        std::vector<int>(dims_vec.begin(), dims_vec.begin() + x_rank - 1);
    Pivots_dim[x_rank - 2] = min_mn;
    pivots->set_dims(phi::make_ddim(Pivots_dim));
    pivots->set_dtype(DataType::INT32);
  }
}

2172
void MatrixRankInferMeta(const MetaTensor& x,
2173
                         bool use_default_tol,
Z
zhangyuqin1998 已提交
2174
                         bool hermitian,
2175 2176
                         MetaTensor* out) {
  auto dim_x = x.dims();
L
Lin Manhui 已提交
2177 2178 2179 2180
  PADDLE_ENFORCE_GE(dim_x.size(),
                    2,
                    phi::errors::InvalidArgument(
                        "The dims of input must be greater than 2."));
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194

  if (hermitian) {
    int rows = dim_x[dim_x.size() - 2];
    int cols = dim_x[dim_x.size() - 1];
    PADDLE_ENFORCE_EQ(rows,
                      cols,
                      phi::errors::InvalidArgument(
                          "if hermitian == true, matrix should be n*n"));
  }
  DDim dim_x_batch = detail::CheckAndGetOutputDim(dim_x);
  out->set_dims(dim_x_batch);
  out->share_lod(x);
}

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
void MaxOutInferMeta(const MetaTensor& x,
                     int groups,
                     int axis,
                     MetaTensor* out) {
  auto in_x_dims = x.dims();
  // check groups > 1
  PADDLE_ENFORCE_GT(
      groups,
      1,
      phi::errors::InvalidArgument("Attr(groups) of Op(maxout) should be "
                                   "larger than 1. But received %d.",
                                   groups));
  PADDLE_ENFORCE_EQ(
      axis == 1 || axis == -1 || axis == 3,
      true,
      phi::errors::InvalidArgument(
L
Lin Manhui 已提交
2211
          "axis only supported 1, -1 or 3, but recevied axis is: %d.", axis));
2212 2213 2214
  PADDLE_ENFORCE_EQ(in_x_dims.size(),
                    4,
                    phi::errors::InvalidArgument(
L
Lin Manhui 已提交
2215
                        "x's dims should be 4, but received x's dims is: %d.",
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
                        in_x_dims.size()));

  if (axis < 0) {
    axis += in_x_dims.size();
  }
  PADDLE_ENFORCE_EQ(
      in_x_dims[axis] % groups,
      0,
      phi::errors::InvalidArgument(
          "The number of input channels for Op(maxout) "
          "should be divisible by Attr(groups). But received: the "
          "input's channels is [%d], the shape of input is [%s], "
          "the Attr(groups) is [%d], the Attr(axis) is [%d]. The "
          "error may come from wrong Attr(groups) or Attr(axis) setting.",
          in_x_dims[axis],
          in_x_dims,
          groups,
          axis));
  std::vector<int64_t> output_shape(
      {in_x_dims[0], in_x_dims[1], in_x_dims[2], in_x_dims[3]});
  output_shape[axis] = in_x_dims[axis] / groups;
  out->set_dims(phi::make_ddim(output_shape));
  out->set_dtype(x.dtype());
}

F
From00 已提交
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
void MaxPoolWithIndexInferMeta(const MetaTensor& x,
                               const std::vector<int>& kernel_size,
                               const std::vector<int>& strides,
                               const std::vector<int>& paddings,
                               bool global_pooling,
                               bool adaptive,
                               MetaTensor* out,
                               MetaTensor* mask,
                               MetaConfig config) {
  std::vector<int> paddings_ = paddings;
  std::vector<int> kernel_size_ = kernel_size;

  auto x_dims = x.dims();

2255 2256 2257 2258 2259 2260
  PADDLE_ENFORCE_EQ(
      (x_dims.size() == 4 || x_dims.size() == 5),
      true,
      errors::InvalidArgument("Pooling intput should be 4-D or "
                              "5-D tensor but received %dD-Tensor",
                              x_dims.size()));
F
From00 已提交
2261 2262 2263 2264 2265 2266 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 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310

  if (global_pooling) {
    kernel_size_.resize(static_cast<size_t>(x_dims.size()) - 2);
    for (size_t i = 0; i < kernel_size_.size(); ++i) {
      paddings_[i] = 0;
      kernel_size_[i] = static_cast<int>(x_dims[i + 2]);
    }
  }

  PADDLE_ENFORCE_EQ(
      x_dims.size() - kernel_size_.size(),
      2U,
      errors::InvalidArgument(
          "The input size %d minus the kernel size %d should equal to 2.",
          x_dims.size(),
          kernel_size_.size()));
  PADDLE_ENFORCE_EQ(
      kernel_size_.size(),
      strides.size(),
      errors::InvalidArgument(
          "Strides size %d and pooling size %d should be the same.",
          strides.size(),
          kernel_size_.size()));
  PADDLE_ENFORCE_EQ(
      kernel_size_.size(),
      paddings_.size(),
      errors::InvalidArgument(
          "Paddings size %d and pooling size %d should be the same.",
          paddings_.size(),
          kernel_size_.size()));

  std::vector<int64_t> output_shape({x_dims[0], x_dims[1]});
  if (adaptive) {
    output_shape.insert(
        output_shape.end(), kernel_size_.begin(), kernel_size_.end());
  } else {
    for (size_t i = 0; i < kernel_size_.size(); ++i) {
      if ((!config.is_runtime) && (x_dims[i + 2] < 0)) {
        output_shape.push_back(x_dims[i + 2]);
      } else {
        output_shape.push_back(funcs::MaxPoolOutputSize(
            x_dims[i + 2], kernel_size_[i], paddings_[i], strides[i]));
      }
    }
  }

  out->set_dims(make_ddim(output_shape));
  out->set_dtype(x.dtype());

  mask->set_dims(make_ddim(output_shape));
2311
  mask->set_dtype(phi::CppTypeToDataType<int>::Type());
F
From00 已提交
2312 2313
}

2314
void MeanAllInferMeta(const MetaTensor& x, MetaTensor* out) {
2315
  out->set_dims(phi::make_ddim({}));
2316 2317 2318 2319
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());
}

2320 2321 2322 2323 2324 2325 2326
void ModeInferMeta(const MetaTensor& x,
                   int axis,
                   bool keepdim,
                   MetaTensor* out,
                   MetaTensor* indices) {
  auto input_dims = x.dims();
  const int& dim_size = input_dims.size();
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
  PADDLE_ENFORCE_LE(axis,
                    dim_size,
                    phi::errors::InvalidArgument(
                        "the axis must be [-%d, %d), but received %d .",
                        dim_size,
                        dim_size,
                        axis));
  if (dim_size > 0) {
    PADDLE_ENFORCE_GE(axis,
                      -dim_size,
                      phi::errors::InvalidArgument(
                          "the axis must be [-%d, %d), but received %d .",
                          dim_size,
                          dim_size,
                          axis));
  }
2343 2344
  PADDLE_ENFORCE_GE(
      input_dims.size(),
2345 2346
      0,
      errors::InvalidArgument("input of ModeOp must have >= 0d shape"));
W
wanghuancoder 已提交
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
  if (axis < 0) {
    axis += dim_size;
    if (dim_size != 0) {
      PADDLE_ENFORCE_GE(axis,
                        0,
                        phi::errors::InvalidArgument(
                            "the axis must be [-%d, %d), but received %d .",
                            dim_size,
                            dim_size,
                            axis - dim_size));
    }
  }

2360 2361 2362 2363
  std::vector<int64_t> dimvec;
  for (int64_t i = 0; i < axis; i++) {
    dimvec.emplace_back(input_dims[i]);
  }
2364
  if (keepdim && dim_size > 0) {
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
    dimvec.emplace_back(static_cast<int64_t>(1));
  }
  for (int64_t i = axis + 1; i < dim_size; i++) {
    dimvec.emplace_back(input_dims[i]);
  }
  DDim dims = phi::make_ddim(dimvec);
  out->set_dims(dims);
  out->share_lod(x);
  out->set_dtype(x.dtype());

  indices->set_dims(dims);
  indices->share_lod(x);
  indices->set_dtype(x.dtype());
}

2380
void MultinomialInferMeta(const MetaTensor& x,
2381
                          const Scalar& num_samples,
2382
                          bool replacement,
2383 2384 2385
                          MetaTensor* out,
                          MetaConfig config) {
  auto int_num_samples = num_samples.to<int>();
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
  auto x_dim = x.dims();
  int64_t x_rank = x_dim.size();
  PADDLE_ENFORCE_GT(x_rank,
                    0,
                    errors::InvalidArgument(
                        "The number of dimensions of the input probability "
                        "distribution should be > 0, but got %d.",
                        x_rank));
  PADDLE_ENFORCE_LE(x_rank,
                    2,
                    errors::InvalidArgument(
                        "The number of dimensions of the input probability "
                        "distribution should be <= 2, but got %d.",
                        x_rank));

  std::vector<int64_t> out_dims(x_rank);
  for (int64_t i = 0; i < x_rank - 1; i++) {
    out_dims[i] = x_dim[i];
  }

2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
  if (config.is_runtime || !num_samples.FromTensor()) {
    PADDLE_ENFORCE_GT(int_num_samples,
                      0,
                      errors::InvalidArgument(
                          "The number of samples should be > 0, but got %d.",
                          int_num_samples));
    out_dims[x_rank - 1] = int_num_samples;
  } else {
    out_dims[x_rank - 1] = -1;
  }
2416 2417 2418 2419 2420

  out->set_dims(make_ddim(out_dims));
  out->set_dtype(DataType::INT64);
}

2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
void NanmedianInferMeta(const MetaTensor& x,
                        const IntArray& axes,
                        bool keep_dim,
                        MetaTensor* out,
                        MetaTensor* median_index) {
  std::vector<int64_t> axis_list = axes.GetData();
  auto x_dim = x.dims();
  int64_t x_rank = x_dim.size();
  out->set_dtype(x.dtype());
  median_index->set_dtype(DataType::INT64);
  median_index->set_dims(make_ddim({x.numel() * 2}));

  std::vector<int32_t> out_dim;
  if (axis_list.empty()) {
    if (keep_dim) {
      for (int64_t i = 0; i < x_rank; i++) {
        out_dim.push_back(1);
      }
    }
  } else {
2441
    std::vector<int64_t> formated_axis;
2442
    for (auto& axis : axis_list) {
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
      if (x_rank == 0) {
        PADDLE_ENFORCE_EQ(axis == 0 || axis == -1,
                          true,
                          phi::errors::InvalidArgument(
                              "When input 0D Tensor, each element of the axis "
                              "can only be -1, 0, None"));
      } else {
        PADDLE_ENFORCE_LT(axis,
                          x_rank,
                          errors::InvalidArgument(
                              "each element of the axis should be in the "
                              "range [ -dimension(X), dimension(X) ) "
                              "which dimesion = %d. But received axis = %d.",
                              x_rank,
                              axis));
        PADDLE_ENFORCE_GE(axis,
                          -x_rank,
                          errors::InvalidArgument(
                              "each element of the axis should be in the "
                              "range [ -dimension(X), dimension(X) ) "
                              "which dimesion = %d. But received axis = %d.",
                              x_rank,
                              axis));
      }
2467 2468
      if (axis < 0) axis += x_rank;
      PADDLE_ENFORCE_EQ(
2469 2470
          std::find(formated_axis.begin(), formated_axis.end(), axis),
          formated_axis.end(),
2471 2472 2473
          errors::InvalidArgument("Attr(axes) has duplicated elements: %d.",
                                  static_cast<int>(axis)));

2474
      formated_axis.push_back(axis);
2475 2476 2477
    }

    for (int64_t i = 0; i < x_rank; i++) {
2478 2479
      if (std::find(formated_axis.begin(), formated_axis.end(), i) ==
          formated_axis.end()) {
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
        out_dim.push_back(x_dim[i]);
      } else if (keep_dim) {
        out_dim.push_back(1);
      }
    }
  }

  out->set_dims(make_ddim(out_dim));
}

2490 2491 2492 2493 2494 2495 2496 2497 2498
void NMSInferMeta(const MetaTensor& x, float threshold, MetaTensor* out) {
  auto boxes_dim = x.dims();
  PADDLE_ENFORCE_EQ(boxes_dim.size(),
                    2,
                    phi::errors::InvalidArgument(
                        "The Input Boxes must be 2-dimention "
                        "whose shape must be [N, 4] "
                        "N is the number of boxes "
                        "in last dimension in format [x1, x2, y1, y2]. "));
2499 2500
  out->set_dims(phi::make_ddim({-1}));
  out->set_dtype(DataType::INT64);
2501 2502
}

2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
void NonZeroInferMeta(const MetaTensor& condition, MetaTensor* out) {
  auto rank = condition.dims().size();
  PADDLE_ENFORCE_GE(
      rank,
      1UL,
      phi::errors::InvalidArgument(
          "Input(Condition) should have number of dimension at least 1"));
  out->set_dims(phi::make_ddim({-1, rank}));
  out->set_dtype(DataType::INT64);
}

H
hong 已提交
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
void NormInferMeta(const MetaTensor& x,
                   int axis,
                   float epsilon,
                   bool is_test,
                   MetaTensor* out,
                   MetaTensor* norm) {
  auto xdim = x.dims();
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());

  if (is_test == false) {
    if (axis < 0) axis = xdim.size() + axis;
    xdim[axis] = 1;
    norm->set_dims(xdim);
    norm->set_dtype(x.dtype());
  }
}

2532 2533 2534 2535 2536 2537 2538 2539
void OneHotRawInferMeta(const MetaTensor& x,
                        const Scalar& depth,
                        DataType dtype,
                        bool allow_out_of_range,
                        MetaTensor* out) {
  auto x_dims = x.dims();
  PADDLE_ENFORCE_GE(
      x_dims.size(),
2540 2541
      0,
      phi::errors::InvalidArgument("Rank of Input(X) should be at least 0."));
2542 2543 2544 2545 2546 2547 2548
  auto out_dims_vec = phi::vectorize(x_dims);
  out_dims_vec.push_back(depth.to<int>());
  auto out_dims = phi::make_ddim(out_dims_vec);
  out->set_dims(out_dims);
  out->share_lod(x);
  out->set_dtype(dtype);
}
2549

2550 2551 2552 2553
void OneHotInferMeta(const MetaTensor& x,
                     const Scalar& depth_t,
                     MetaTensor* out) {
  auto x_dims = x.dims();
2554
  PADDLE_ENFORCE_GE(
2555
      x_dims.size(),
2556 2557
      0,
      phi::errors::InvalidArgument("Rank of Input(X) should be at least 0."));
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578

  int depth = depth_t.to<int>();
  auto out_dims_vec = phi::vectorize(x_dims);
  out_dims_vec.push_back(depth);
  auto out_dims = phi::make_ddim(out_dims_vec);
  out->set_dims(out_dims);
  out->share_lod(x);

  out->set_dtype(phi::DataType::FLOAT32);
}

void OverlapAddInferMeta(const MetaTensor& x,
                         int hop_length,
                         int axis,
                         MetaTensor* out,
                         MetaConfig config) {
  const auto x_dims = x.dims();
  const int x_rank = x_dims.size();

  PADDLE_ENFORCE_GE(
      x_rank,
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
      2,
      errors::InvalidArgument(
          "Input(X) of OverlapAddOp should be a tensor which contains "
          "at least 2 dimensions, but got rank %s.",
          x_rank));

  PADDLE_ENFORCE_GT(
      hop_length,
      0,
      errors::InvalidArgument(
          "Attribute(hop_length) of OverlapAddOp should be greater "
          "than 0, but got %s.",
          hop_length));

  PADDLE_ENFORCE_EQ(
      (axis == 0 || axis == -1),
      true,
      errors::InvalidArgument(
          "Attribute(axis) of OverlapAddOp should 0 or -1, but got %s.", axis));

  std::vector<int64_t> output_shape;
  int n_frames;
  int frame_length;
  int seq_length;

  int start_axis;
  int end_axis;
  if (axis == 0) {
    n_frames = x_dims[0];
    frame_length = x_dims[1];
    start_axis = 2;
    end_axis = x_rank - 1;
  } else {
    n_frames = x_dims[x_rank - 1];
    frame_length = x_dims[x_rank - 2];
    start_axis = 0;
    end_axis = x_rank - 3;
  }

  bool contain_unknown_dim = phi::contain_unknown_dim(x_dims);
  bool check = config.is_runtime || !contain_unknown_dim;
  if (check) {
    PADDLE_ENFORCE_LE(
        hop_length,
        frame_length,
        errors::InvalidArgument(
            "Attribute(hop_length) of OverlapAddOp should be less or equal "
            "than frame_length, but got hop_length(%s) > frame_length(%s).",
            hop_length,
            frame_length));
  }

  if (n_frames == -1) {
    seq_length = -1;
  } else {
    seq_length = (n_frames - 1) * hop_length + frame_length;
  }

  // It won't go into for loop when x_rank == 2U.
  for (int i = start_axis; i <= end_axis; i++) {
    output_shape.push_back(x_dims[i]);
  }

  if (axis == 0) {
    // (seq_length, ...)
    output_shape.insert(output_shape.begin(), seq_length);
  } else {
    // (..., seq_length)
    output_shape.push_back(seq_length);
  }

  out->set_dims(phi::make_ddim(output_shape));
}

Z
zyfncg 已提交
2653 2654
void PadInferMeta(const MetaTensor& input,
                  const std::vector<int>& paddings,
2655
                  const Scalar& padding_value,
Z
zyfncg 已提交
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
                  MetaTensor* out,
                  MetaConfig config) {
  auto x_dim = input.dims();
  PADDLE_ENFORCE_EQ(
      static_cast<int>(paddings.size()),
      x_dim.size() * 2,
      phi::errors::InvalidArgument(
          "Size of 'paddings' dimension should be equal to 2 * size of "
          "Input(X)'s dimension, but received (size of 'paddings' dimension "
          "is) %d vs (2 * size of Input(X)'s dimension is) %d.",
          static_cast<int>(paddings.size()),
          x_dim.size() * 2));
  for (size_t i = 0; i < paddings.size(); ++i) {
    PADDLE_ENFORCE_GE(paddings[i],
                      0,
                      phi::errors::InvalidArgument(
                          "The element of 'paddings' should >= 0, but "
                          "received %d for index %d.",
                          paddings[i],
                          static_cast<int>(i)));
2676
  }
Z
zyfncg 已提交
2677 2678 2679 2680
  std::vector<int64_t> out_dims(x_dim.size());
  for (int i = 0; i < x_dim.size(); ++i) {
    if ((!config.is_runtime) && (x_dim[i] == -1)) {
      out_dims[i] = -1;
2681
    } else {
Z
zyfncg 已提交
2682
      out_dims[i] = x_dim[i] + paddings[i * 2] + paddings[i * 2 + 1];
2683 2684
    }
  }
Z
zyfncg 已提交
2685 2686 2687 2688 2689
  out->set_dims(phi::make_ddim(out_dims));
  if (out_dims[0] == x_dim[0]) {
    // Only pass LoD when the first dimension is equal between
    // output and input.
    out->share_lod(input);
2690
  }
Z
zyfncg 已提交
2691
  out->set_dtype(input.dtype());
2692 2693
}

2694
void Pad3dInferMeta(const MetaTensor& x,
2695
                    const IntArray& paddings_int_array,
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
                    const std::string& mode,
                    float value,
                    const std::string& data_format,
                    MetaTensor* out,
                    MetaConfig config) {
  auto x_dim = x.dims();
  PADDLE_ENFORCE_EQ(x_dim.size(),
                    5,
                    errors::InvalidArgument(
                        "The size of Input(X)'s dimension should be equal to "
                        "5, but received %d. ",
                        x_dim.size()));

2709
  std::vector<int64_t> out_dims(x_dim.size(), -1);
2710
  out_dims[0] = x_dim[0];
2711 2712 2713 2714 2715 2716
  auto& paddings = paddings_int_array.GetData();
  if (data_format == "NCDHW") {
    out_dims[1] = x_dim[1];
  } else {
    out_dims[4] = x_dim[4];
  }
2717
  if (paddings_int_array.FromTensor()) {
2718 2719
    if (config.is_runtime) {
      PADDLE_ENFORCE_EQ(
2720
          paddings.size(),
2721 2722 2723
          6,
          errors::InvalidArgument("Shape of Input(Paddings) should be equal to "
                                  "[6], but received [%d].",
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
                                  paddings.size()));
      if (data_format == "NCDHW") {
        out_dims[2] = x_dim[2] + paddings[4] + paddings[5];
        out_dims[3] = x_dim[3] + paddings[2] + paddings[3];
        out_dims[4] = x_dim[4] + paddings[0] + paddings[1];
      } else {
        out_dims[1] = x_dim[1] + paddings[4] + paddings[5];
        out_dims[2] = x_dim[2] + paddings[2] + paddings[3];
        out_dims[3] = x_dim[3] + paddings[0] + paddings[1];
      }
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
    }
  } else {
    PADDLE_ENFORCE_EQ(
        paddings.size(),
        6,
        errors::InvalidArgument(
            "Size of paddings should be equal to 6, but received %d.",
            static_cast<int>(paddings.size())));
    if (data_format == "NCDHW") {
      out_dims[2] = ((!config.is_runtime) && (x_dim[2] < 0))
                        ? x_dim[2]
                        : (x_dim[2] + paddings[4] + paddings[5]);  // depth

      out_dims[3] = ((!config.is_runtime) && (x_dim[3] < 0))
                        ? x_dim[3]
                        : (x_dim[3] + paddings[2] + paddings[3]);  // height

      out_dims[4] = ((!config.is_runtime) && (x_dim[4] < 0))
                        ? x_dim[4]
                        : (x_dim[4] + paddings[0] + paddings[1]);  // width
    } else {                                                       // NDHWC
      out_dims[1] = ((!config.is_runtime) && (x_dim[1] < 0))
                        ? x_dim[1]
                        : (x_dim[1] + paddings[4] + paddings[5]);  // depth
      out_dims[2] = ((!config.is_runtime) && (x_dim[2] < 0))
                        ? x_dim[2]
                        : (x_dim[2] + paddings[2] + paddings[3]);  // height
      out_dims[3] = ((!config.is_runtime) && (x_dim[3] < 0))
                        ? x_dim[3]
                        : (x_dim[3] + paddings[0] + paddings[1]);  // width
    }
  }

  out->set_dims(phi::make_ddim(out_dims));
  out->set_dtype(x.dtype());
  out->share_lod(x);
}

Z
zyfncg 已提交
2772 2773 2774 2775 2776 2777 2778
void PixelShuffleInferMeta(const MetaTensor& x,
                           int upscale_factor,
                           const std::string& data_format,
                           MetaTensor* out) {
  auto input_dims = x.dims();
  PADDLE_ENFORCE_EQ(input_dims.size(),
                    4,
2779
                    phi::errors::InvalidArgument(
Z
zyfncg 已提交
2780 2781 2782
                        "Input should be a 4-D tensor of format [N, C, H, W] "
                        "or [N, H, W, C], but got %u.",
                        input_dims.size()));
2783 2784 2785 2786
  PADDLE_ENFORCE_NE(
      upscale_factor,
      0,
      phi::errors::InvalidArgument("upscale_factor should not be 0."));
2787

Z
zyfncg 已提交
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
  const bool channel_last = (data_format == "NHWC");

  if (!channel_last) {
    PADDLE_ENFORCE_EQ(input_dims[1] % (upscale_factor * upscale_factor),
                      0,
                      phi::errors::InvalidArgument(
                          "The square of upscale_factor[%u] should divide the "
                          "number of channel[%u]",
                          upscale_factor * upscale_factor,
                          input_dims[1]));
  } else {
    PADDLE_ENFORCE_EQ(input_dims[3] % (upscale_factor * upscale_factor),
                      0,
                      phi::errors::InvalidArgument(
                          "The square of upscale_factor[%u] should divide the "
                          "number of channel[%u]",
                          upscale_factor * upscale_factor,
                          input_dims[3]));
2806
  }
Z
zyfncg 已提交
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
  auto output_dims = input_dims;
  output_dims[0] = input_dims[0];
  if (!channel_last) {
    output_dims[1] = input_dims[1] / (upscale_factor * upscale_factor);
    output_dims[2] = input_dims[2] * upscale_factor;
    output_dims[3] = input_dims[3] * upscale_factor;
  } else {
    output_dims[1] = input_dims[1] * upscale_factor;
    output_dims[2] = input_dims[2] * upscale_factor;
    output_dims[3] = input_dims[3] / (upscale_factor * upscale_factor);
  }
  out->set_dtype(x.dtype());
  out->set_dims(output_dims);
2820 2821
}

H
hong 已提交
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
void PixelShuffleGradInferMeta(const MetaTensor& out_grad,
                               int upscale_factor,
                               const std::string& data_format,
                               MetaTensor* x_grad) {
  auto do_dims = out_grad.dims();
  PADDLE_ENFORCE_EQ(do_dims.size(),
                    4,
                    phi::errors::InvalidArgument(
                        "Input should be a 4-D tensor of format [N, C, H, W] "
                        "or [N, H, W, C], but got %u.",
                        do_dims.size()));

  const bool channel_last = (data_format == "NHWC");

  auto dx_dims = do_dims;
  dx_dims[0] = do_dims[0];

  if (!channel_last) {
    dx_dims[1] = do_dims[1] * (upscale_factor * upscale_factor);
    dx_dims[2] = do_dims[2] / upscale_factor;
    dx_dims[3] = do_dims[3] / upscale_factor;
  } else {
    dx_dims[1] = do_dims[1] / upscale_factor;
    dx_dims[2] = do_dims[2] / upscale_factor;
    dx_dims[3] = do_dims[3] * (upscale_factor * upscale_factor);
  }
  x_grad->set_dims(dx_dims);
  x_grad->set_dtype(out_grad.dtype());
}

2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
void PixelUnshuffleInferMeta(const MetaTensor& x,
                             int downscale_factor,
                             const std::string& data_format,
                             MetaTensor* out) {
  auto input_dims = x.dims();
  PADDLE_ENFORCE_EQ(input_dims.size(),
                    4,
                    phi::errors::InvalidArgument(
                        "Input should be a 4-D tensor of format [N, C, H, W] "
                        "or [N, H, W, C], but got %u.",
                        input_dims.size()));
  PADDLE_ENFORCE_GE(downscale_factor,
                    1,
                    phi::errors::InvalidArgument(
                        "downscale_factor should be larger than 0."));
  PADDLE_ENFORCE_EQ(data_format == "NCHW" || data_format == "NHWC",
                    true,
                    phi::errors::InvalidArgument(
                        "data_format must be one of "
                        "NCHW and NHWC. But recevied data_format: %s",
                        data_format));

  const bool channel_last = (data_format == "NHWC");

  if (!channel_last) {
    PADDLE_ENFORCE_EQ(
        (input_dims[2] % downscale_factor) == 0 &&
            (input_dims[3] % downscale_factor) == 0,
        true,
        phi::errors::InvalidArgument("Downscale factor[%u] should divide both "
                                     "height[%u] and width[%u]",
                                     downscale_factor,
                                     input_dims[2],
                                     input_dims[3]));
  } else {
    PADDLE_ENFORCE_EQ(
        (input_dims[1] % downscale_factor) == 0 &&
            (input_dims[2] % downscale_factor) == 0,
        true,
        phi::errors::InvalidArgument("Downscale factor[%u] should divide both "
                                     "height[%u] and width[%u]",
                                     downscale_factor,
                                     input_dims[1],
                                     input_dims[2]));
  }
  auto output_dims = input_dims;
  output_dims[0] = input_dims[0];
  if (!channel_last) {
    output_dims[1] = input_dims[1] * (downscale_factor * downscale_factor);
    output_dims[2] = input_dims[2] / downscale_factor;
    output_dims[3] = input_dims[3] / downscale_factor;
  } else {
    output_dims[1] = input_dims[1] / downscale_factor;
    output_dims[2] = input_dims[2] / downscale_factor;
    output_dims[3] = input_dims[3] * (downscale_factor * downscale_factor);
  }
  out->set_dtype(x.dtype());
  out->set_dims(output_dims);
}

2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
void PNormInferMeta(const MetaTensor& x,
                    float porder,
                    int axis,
                    float epsilon,
                    bool keepdim,
                    bool asvector,
                    MetaTensor* out) {
  auto x_dim = x.dims();
  auto x_rank = x_dim.size();

  PADDLE_ENFORCE_GE(axis,
                    -x_rank,
                    errors::InvalidArgument(
                        "Attr(axis) value should be in range [-R, R-1], R is "
                        "the rank of Input(X). But received axis: %d, R: %d. "
                        "Current Input(X)'s shape is=[%s].",
                        axis,
                        x_rank,
                        x_dim));
  PADDLE_ENFORCE_LT(axis,
                    x_rank,
                    errors::InvalidArgument(
                        "Attr(axis) value should be in range [-R, R-1], R is "
                        "the rank of Input(X). But received axis: %d, R: %d. "
                        "Current Input(X)'s shape is=[%s].",
                        axis,
                        x_rank,
                        x_dim));

2941
  std::vector<int> out_dim_vector;
2942 2943
  if (asvector) {
    if (keepdim) {
2944 2945
      for (int i = 0; i < x_rank; ++i) {
        out_dim_vector.emplace_back(1);
2946
      }
2947 2948
    } else {
      out_dim_vector = {};
2949 2950
    }
  } else {
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
    if (axis < 0) axis = axis + x_rank;
    if (keepdim) {
      for (int i = 0; i < x_dim.size(); ++i) {
        if (i != axis) {
          out_dim_vector.emplace_back(x_dim[i]);
        } else {
          out_dim_vector.emplace_back(1);
        }
      }
    } else {
      for (int i = 0; i < x_dim.size(); ++i) {
        if (i != axis) out_dim_vector.emplace_back(x_dim[i]);
      }
2964 2965 2966
    }
  }

2967
  out->set_dims(phi::make_ddim(out_dim_vector));
2968 2969 2970
  out->set_dtype(x.dtype());
}

2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
void Pool2DInferMeta(const MetaTensor& x,
                     const IntArray& kernel_size,
                     const std::vector<int>& strides,
                     const std::vector<int>& paddings,
                     bool ceil_mode,
                     bool exclusive,
                     const std::string& data_format,
                     const std::string& pooling_type,
                     bool global_pooling,
                     bool adaptive,
                     const std::string& padding_algorithm,
                     MetaTensor* out,
                     MetaConfig config) {
  const bool channel_last = (config.is_run_mkldnn_kernel == false) &&
                            (data_format == "NHWC" || data_format == "NDHWC");
  if (!config.is_runtime && kernel_size.FromTensor()) {
    auto x_dims = x.dims();
    std::vector<int64_t> output_shape = std::move(phi::vectorize(x_dims));
    // set dims of HW -1
    output_shape[x_dims.size() - 2] = -1;
    if (channel_last) {  // for NHWC, NDHWC
      output_shape[x_dims.size() - 3] = -1;
    } else {  // for NCHW
      output_shape[x_dims.size() - 1] = -1;
    }
    out->set_dims(make_ddim(output_shape));
    out->share_lod(x);
    out->set_dtype(x.dtype());
  } else {
    std::vector<int> kernel_size_val(kernel_size.GetData().begin(),
                                     kernel_size.GetData().end());
    PoolInferMeta(x,
                  kernel_size_val,
                  strides,
                  paddings,
                  ceil_mode,
                  exclusive,
                  data_format,
                  pooling_type,
                  global_pooling,
                  adaptive,
                  padding_algorithm,
                  out,
                  config);
  }
}

3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
void PSendInferMeta(const MetaTensor& x, int peer) {
  LOG(INFO) << "SendBaseInferMeta begin";
  PADDLE_ENFORCE_GE(
      peer,
      0,
      errors::InvalidArgument(
          "The peer (%d) for p_send op must be non-negative.", peer));
}

void PSendArrayInferMeta(const MetaTensor& x, int peer) {
  PADDLE_ENFORCE_GE(
      peer,
      0,
      errors::InvalidArgument(
          "The peer (%d) for p_send op must be non-negative.", peer));
}

F
From00 已提交
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
void PoolInferMeta(const MetaTensor& x,
                   const std::vector<int>& kernel_size,
                   const std::vector<int>& strides,
                   const std::vector<int>& paddings,
                   bool ceil_mode,
                   bool exclusive,
                   const std::string& data_format,
                   const std::string& pooling_type,
                   bool global_pooling,
                   bool adaptive,
                   const std::string& padding_algorithm,
                   MetaTensor* out,
                   MetaConfig config) {
  std::vector<int> paddings_ = paddings;
  std::vector<int> kernel_size_ = kernel_size;

  auto x_dims = x.dims();
  PADDLE_ENFORCE_EQ(
      x_dims.size() == 4 || x_dims.size() == 5,
      true,
      errors::InvalidArgument(
          "the input of Op(pool) should be 4-D or 5-D Tensor. But "
          "received: %u-D Tensor and it's shape is [%s].",
          x_dims.size(),
          x_dims));

  PADDLE_ENFORCE_EQ(x_dims.size() - kernel_size_.size(),
                    2U,
                    errors::InvalidArgument(
                        "the dimension of input minus the size of "
                        "Attr(kernel_size_) must be euqal to 2 in Op(pool). "
                        "But received: the dimension of input minus the size "
                        "of Attr(kernel_size_) is %d, the "
                        "input's dimension is %d, the shape of input "
                        "is [%s], the Attr(kernel_size_)'s size is %d, the "
                        "Attr(kernel_size_) is [%s].",
                        x_dims.size() - kernel_size_.size(),
                        x_dims.size(),
                        x_dims,
                        kernel_size_.size(),
                        make_ddim(kernel_size_)));

  PADDLE_ENFORCE_EQ(
      kernel_size_.size(),
      strides.size(),
      errors::InvalidArgument(
          "the size of Attr(kernel_size_) and Attr(strides) in "
          "Op(pool) must be equal. "
          "But received: Attr(kernel_size_)'s size is %d, Attr(strides)'s "
          "size is %d, Attr(kernel_size_) is [%s], Attr(strides)is [%s].",
          kernel_size_.size(),
          strides.size(),
          make_ddim(kernel_size_),
          make_ddim(strides)));

  // MKL-DNN Kernels are using NCHW order of dims description
  // so we ignore data_format consideration for MKL-DNN kernel
  const bool channel_last = (config.is_run_mkldnn_kernel == false) &&
                            (data_format == "NHWC" || data_format == "NDHWC");

  // update paddings if "SAME" or global_pooling
  DDim data_dims;
  if (channel_last) {
    data_dims = slice_ddim(x_dims, 1, x_dims.size() - 1);
  } else {
    data_dims = slice_ddim(x_dims, 2, x_dims.size());
  }
  funcs::UpdatePadding(&paddings_,
                       global_pooling,
                       adaptive,
                       padding_algorithm,
                       data_dims,
                       strides,
                       kernel_size_);

  if (global_pooling) {
    funcs::UpdateKernelSize(&kernel_size_, data_dims);
  }

  std::vector<int64_t> output_shape;
  if (adaptive) {
    output_shape.insert(
        output_shape.end(), kernel_size_.begin(), kernel_size_.end());
  } else {
    for (int i = 0; i < data_dims.size(); ++i) {
      if ((!config.is_runtime) && (data_dims[i] < 0)) {
        output_shape.push_back(data_dims[i]);
      } else {
        output_shape.push_back(funcs::PoolOutputSize(data_dims[i],
                                                     kernel_size_[i],
                                                     paddings_[2 * i],
                                                     paddings_[2 * i + 1],
                                                     strides[i],
                                                     ceil_mode));
      }
    }
  }

  // output_N = input_N
  output_shape.insert(output_shape.begin(), x_dims[0]);
  // output_C = input_C
  if (channel_last) {
    output_shape.push_back(x_dims[x_dims.size() - 1]);
  } else {
    output_shape.insert(output_shape.begin() + 1, x_dims[1]);
  }

  out->set_dims(make_ddim(output_shape));
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

Z
zyfncg 已提交
3147 3148 3149 3150
void RealAndImagInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(dtype::ToReal(x.dtype()));
  out->set_layout(x.layout());
3151 3152
}

3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
void QrInferMeta(const MetaTensor& x,
                 const std::string& mode,
                 MetaTensor* q,
                 MetaTensor* r) {
  auto x_dims = x.dims();
  int x_rank = x_dims.size();
  PADDLE_ENFORCE_GE(
      x_dims.size(),
      2,
      phi::errors::InvalidArgument("the rank of input must greater than 2"));
  bool compute_q;
  bool reduced_mode;
  int m = x_dims[x_rank - 2];
  int n = x_dims[x_rank - 1];
  int min_mn = std::min(m, n);
  std::tie(compute_q, reduced_mode) = phi::funcs::ParseQrMode(mode);

  if (compute_q) {
    int k = reduced_mode ? min_mn : m;
    auto q_dims_vec = phi::vectorize(x_dims);
    q_dims_vec[q_dims_vec.size() - 1] = k;
    q->set_dims(phi::make_ddim(q_dims_vec));
  } else {
    q->set_dims(phi::make_ddim({0}));
  }

  int k = reduced_mode ? min_mn : m;
  auto r_dims_vec = phi::vectorize(x_dims);
  r_dims_vec[r_dims_vec.size() - 2] = k;
  r_dims_vec[r_dims_vec.size() - 1] = n;
  r->set_dims(phi::make_ddim(r_dims_vec));

  q->share_lod(x);
  r->share_lod(x);
  q->set_dtype(x.dtype());
  r->set_dtype(x.dtype());
}

3191 3192 3193 3194
DDim ReduceInferDim(const MetaTensor& x,
                    const std::vector<int64_t>& axis,
                    bool keep_dim,
                    bool reduce_all) {
3195 3196 3197 3198
  auto x_rank = x.dims().size();

  std::vector<int64_t> formated_axis = axis;
  for (size_t i = 0; i < axis.size(); ++i) {
zhouweiwei2014's avatar
zhouweiwei2014 已提交
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
    if (x_rank == 0) {
      PADDLE_ENFORCE_EQ(
          axis[i] == 0 || axis[i] == -1,
          true,
          phi::errors::InvalidArgument(
              "When input 0D Tensor, the axis can only be -1, 0, None or []"));
    } else {
      PADDLE_ENFORCE_LT(axis[i],
                        x_rank,
                        errors::InvalidArgument(
                            "The reduce dim index %d should be in the "
                            "range [ -dimension(X), dimension(X) ) "
                            "which dimesion = %d. But received dim index = %d.",
                            i,
                            x_rank,
                            axis[i]));
      PADDLE_ENFORCE_GE(axis[i],
                        -x_rank,
                        errors::InvalidArgument(
                            "The reduce dim index %d should be in the "
                            "range [ -dimension(X), dimension(X) )  "
                            "which dimesion = %d. But received dim index = %d.",
                            i,
                            x_rank,
                            axis[i]));
    }
3225 3226 3227 3228 3229 3230 3231 3232

    if (axis[i] < 0) {
      formated_axis[i] = axis[i] + x_rank;
    }
  }

  bool full_dim = true;
  std::set<int64_t> dims_set(formated_axis.begin(), formated_axis.end());
3233
  for (int64_t i = 0; i < x_rank; ++i) {
3234
    if (dims_set.find(i) == dims_set.end()) {
3235
      full_dim = false;
3236 3237 3238
      break;
    }
  }
3239
  reduce_all = reduce_all || full_dim;
3240 3241

  std::vector<int64_t> out_dim_vector;
3242 3243 3244
  for (int64_t i = 0; i < x_rank; ++i) {
    if (reduce_all || dims_set.find(i) != dims_set.end()) {
      if (keep_dim) {
3245 3246 3247 3248
        out_dim_vector.push_back(1);
      } else {
        continue;
      }
3249 3250
    } else {
      out_dim_vector.push_back(x.dims().at(i));
3251 3252 3253
    }
  }

3254
  DDim out_dim = phi::make_ddim(out_dim_vector);
3255 3256 3257
  return out_dim;
}

3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
void ReduceInferMetaBase(const MetaTensor& x,
                         const std::vector<int64_t>& axis,
                         bool keep_dim,
                         bool reduce_all,
                         MetaTensor* out) {
  DDim out_dim = ReduceInferDim(x, axis, keep_dim, reduce_all);
  out->set_dims(out_dim);
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());
}

void ReduceInferMeta(const MetaTensor& x,
                     const std::vector<int64_t>& axis,
                     bool keep_dim,
                     MetaTensor* out) {
  bool reduce_all = false;
3274
  if (axis.empty()) {
3275 3276 3277 3278 3279
    reduce_all = true;
  }
  ReduceInferMetaBase(x, axis, keep_dim, reduce_all, out);
}

3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
DDim ReduceInferDimForIntArrayAxis(const MetaTensor& x,
                                   const IntArray& axis,
                                   bool keep_dim,
                                   bool reduce_all) {
  std::vector<int64_t> vec_axis = axis.GetData();
  std::vector<int64_t> vec_dim;
  if (reduce_all) {
    if (keep_dim) {
      vec_dim = std::vector<int64_t>(x.dims().size(), 1);
    } else {
3290
      vec_dim = {};
3291 3292 3293 3294 3295 3296
    }
  } else {
    if (keep_dim) {
      vec_dim = std::vector<int64_t>(x.dims().size(), -1);
    } else {
      auto x_rank = static_cast<size_t>(x.dims().size());
3297
      if (vec_axis.size() > x_rank) {
3298 3299 3300 3301 3302 3303 3304 3305 3306
        vec_dim = {-1};
      } else {
        vec_dim = std::vector<int64_t>(x.dims().size() - vec_axis.size(), -1);
      }
    }
  }
  return phi::make_ddim(vec_dim);
}

3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
void ReduceIntArrayAxisInferMetaBase(const MetaTensor& x,
                                     const IntArray& axis,
                                     bool keep_dim,
                                     bool reduce_all,
                                     MetaTensor* out,
                                     MetaConfig config) {
  DDim out_dim;
  if (config.is_runtime || !axis.FromTensor()) {
    out_dim = ReduceInferDim(x, axis.GetData(), keep_dim, reduce_all);
  } else {
    out_dim = ReduceInferDimForIntArrayAxis(x, axis, keep_dim, reduce_all);
3318
  }
3319 3320 3321
  out->set_dims(out_dim);
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());
3322 3323
}

3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
void ReduceIntArrayAxisInferMeta(const MetaTensor& x,
                                 const IntArray& axis,
                                 bool keep_dim,
                                 MetaTensor* out,
                                 MetaConfig config) {
  bool reduce_all = false;
  if (axis.size() == 0) {
    reduce_all = true;
  }
  ReduceIntArrayAxisInferMetaBase(x, axis, keep_dim, reduce_all, out, config);
}

3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349
void ReduceScatterInferMeta(const MetaTensor& x, int nranks, MetaTensor* out) {
  auto dim = x.dims();
  if (dim[0] > 0 || dim[0] < -1) {
    PADDLE_ENFORCE_EQ(
        dim[0] % nranks,
        0,
        errors::InvalidArgument(
            "dim[0] (%d) is not divisible by nranks(%d)", dim[0], nranks));
    dim[0] /= nranks;
  }
  out->set_dims(dim);
  out->set_dtype(x.dtype());
}

S
seemingwang 已提交
3350 3351 3352 3353 3354 3355
void RepeatInterleaveInferMeta(const MetaTensor& x,
                               int repeats,
                               int dim,
                               MetaTensor* out) {
  const auto& input_dim = x.dims();
  auto output_dim = phi::vectorize(input_dim);
3356
  auto n_dim = dim;
S
seemingwang 已提交
3357

3358 3359 3360 3361 3362
  if (n_dim < 0) n_dim += input_dim.size();

  PADDLE_ENFORCE_LT(
      dim,
      input_dim.size(),
S
seemingwang 已提交
3363 3364
      phi::errors::OutOfRange(
          "Attr(dim) is out of range, It's expected "
3365 3366
          "to be in range of [%d, %d]. But received Attr(dim) = %d.",
          -input_dim.size(),
S
seemingwang 已提交
3367 3368
          input_dim.size() - 1,
          dim));
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
  PADDLE_ENFORCE_GE(
      dim,
      (0 - input_dim.size()),
      phi::errors::OutOfRange(
          "Attr(dim) is out of range, It's expected "
          "to be in range of [%d, %d]. But received Attr(dim) = %d.",
          -input_dim.size(),
          input_dim.size() - 1,
          dim));

  PADDLE_ENFORCE_GT(
      repeats,
      0,
S
seemingwang 已提交
3382 3383
      phi::errors::InvalidArgument("repeats should be larger than zero"));

3384 3385 3386 3387
  PADDLE_ENFORCE_NOT_NULL(
      out,
      phi::errors::InvalidArgument(
          "repeat_interleave's output tensor can't be nullptr"));
S
seemingwang 已提交
3388

3389
  output_dim[n_dim] = input_dim[n_dim] * repeats;
S
seemingwang 已提交
3390 3391 3392 3393
  out->set_dims(phi::make_ddim(output_dim));
  out->share_lod(x);
  out->set_dtype(x.dtype());
}
3394

Z
zyfncg 已提交
3395
void ReshapeInferMeta(const MetaTensor& x,
3396
                      const IntArray& shape,
Z
zyfncg 已提交
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
                      MetaTensor* out,
                      MetaConfig config) {
  auto& shape_data = shape.GetData();
  PADDLE_ENFORCE_NOT_NULL(out,
                          phi::errors::InvalidArgument(
                              "Output(Out) of ReshapeOp should not be null."));
  if (!config.is_runtime && shape.FromTensor()) {
    out->set_dims(phi::make_ddim(shape_data));
    out->share_lod(x);
    return;
  }
  InferMetaFromVecValue(x, shape_data, out);
3409 3410
}

Z
zyfncg 已提交
3411
void ReshapeWithXShapeInferMeta(const MetaTensor& x,
3412
                                const IntArray& shape,
Z
zyfncg 已提交
3413
                                MetaTensor* out,
3414
                                MetaTensor* xshape,
Z
zyfncg 已提交
3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
                                MetaConfig config) {
  PADDLE_ENFORCE_NOT_NULL(
      xshape,
      phi::errors::InvalidArgument(
          "Output(XShape) of ReshapeOp should not be null."));
  const auto& x_dims = x.dims();
  std::vector<int64_t> xshape_dims(x_dims.size() + 1);
  xshape_dims[0] = 0;
  for (int i = 0; i < x_dims.size(); ++i) {
    xshape_dims[i + 1] = x_dims[i];
  }
  xshape->set_dims(phi::make_ddim(xshape_dims));
  xshape->share_lod(x);
W
wanghuancoder 已提交
3428
  xshape->set_strides(x.strides());
Z
zyfncg 已提交
3429
  ReshapeInferMeta(x, shape, out, config);
3430 3431
}

3432
void ReverseInferMeta(const MetaTensor& x,
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
                      const IntArray& axis,
                      MetaTensor* out,
                      MetaConfig config) {
  // NOTE(Aurelius84): In Reverse Op, output TensorMeta is always same
  // as input, so we only verify axis when it is not from Tensor or in
  // runtime.
  if (!config.is_runtime && axis.FromTensor()) {
    out->share_meta(x);
    return;
  }
  auto& axis_data = axis.GetData();
  PADDLE_ENFORCE_NE(axis_data.empty(),
3445 3446 3447
                    true,
                    phi::errors::InvalidArgument("'axis' can not be empty."));
  const auto& x_dims = x.dims();
3448
  for (int a : axis_data) {
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
    PADDLE_ENFORCE_LT(a,
                      x_dims.size(),
                      phi::errors::OutOfRange(
                          "The axis must be less than input tensor's rank. "
                          "but got %d >= %d",
                          a,
                          x_dims.size()));
    PADDLE_ENFORCE_GE(
        a,
        -x_dims.size(),
        phi::errors::OutOfRange(
            "The axis must be greater than the negative number of "
            "input tensor's rank, but got %d < %d",
            a,
            -x_dims.size()));
  }
  out->share_meta(x);
}

W
wanghuancoder 已提交
3468
void ReverseArrayInferMeta(const std::vector<const phi::MetaTensor*>& x,
3469 3470 3471 3472 3473 3474 3475
                           const IntArray& axis,
                           std::vector<phi::MetaTensor*> out,
                           MetaConfig config) {
  if (!config.is_runtime && axis.FromTensor()) {
    return;
  }
  auto& axis_data = axis.GetData();
W
wanghuancoder 已提交
3476
  PADDLE_ENFORCE_EQ(
3477
      axis_data.size(),
W
wanghuancoder 已提交
3478 3479 3480 3481
      1,
      phi::errors::InvalidArgument(
          "The size of axis must be 1 when the Input(X) is LoDTensorArray, "
          "but received %d.",
3482
          axis_data.size()));
W
wanghuancoder 已提交
3483
  PADDLE_ENFORCE_EQ(
3484
      axis_data[0],
W
wanghuancoder 已提交
3485 3486 3487 3488
      0,
      phi::errors::InvalidArgument("The value of axis should be 1 when "
                                   "the Input(X) is LoDTensorArray, "
                                   "but received %d.",
3489
                                   axis_data[0]));
W
wanghuancoder 已提交
3490 3491
}

C
chenenquan 已提交
3492
void RollInferMeta(const MetaTensor& x,
3493
                   const IntArray& shifts,
C
chenenquan 已提交
3494 3495 3496 3497
                   const std::vector<int64_t>& axis,
                   MetaTensor* out) {
  auto shifts_data = shifts.GetData();

3498
  if (!axis.empty()) {
C
chenenquan 已提交
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
    PADDLE_ENFORCE_EQ(
        axis.size(),
        shifts_data.size(),
        phi::errors::InvalidArgument("When dims.size() != 0, dims.size() "
                                     "should be equal to "
                                     "shifts.size(). But received "
                                     "dims.size() = %d, shifts.size() = %d",
                                     axis.size(),
                                     shifts_data.size()));
  } else {
    PADDLE_ENFORCE_EQ(
        shifts_data.size(),
        1,
        phi::errors::InvalidArgument("When dims.size() == 0, shifts.size() "
                                     "should be equal to 1, But received "
                                     "shifts.size() = %d",
                                     shifts_data.size()));
  }

  out->set_dims(x.dims());
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
void RReluInferMeta(const MetaTensor& x,
                    float lower,
                    float upper,
                    bool is_test,
                    MetaTensor* out,
                    MetaTensor* noise) {
  auto x_dims = x.dims();
  PADDLE_ENFORCE_GE(lower,
                    0,
                    phi::errors::InvalidArgument(
                        "The lower value should be greater than or equal to 0. "
                        "But received lower value = %f.",
                        lower));
  PADDLE_ENFORCE_LE(upper,
                    1,
                    phi::errors::InvalidArgument(
                        "The upper value should be less than or equal to 1. "
                        "But received upper value = %f.",
                        upper));
  PADDLE_ENFORCE_GE(
      upper,
      lower,
      phi::errors::InvalidArgument(
          "The upper value should be greater than or equal to lower value "
          "But received upper value = %f, lower value = %f.",
          upper,
          lower));

  out->set_dims(x_dims);
  out->set_dtype(x.dtype());
  out->set_layout(x.layout());
  out->share_lod(x);

  if (noise != nullptr) {
    noise->set_dims(x_dims);
    noise->set_dtype(x.dtype());
    noise->set_layout(x.layout());
  }
}

void RReluGradInferMeta(const MetaTensor& out_grad,
                        const MetaTensor& noise,
                        MetaTensor* x_grad) {
  auto do_dims = out_grad.dims();
  x_grad->set_dims(do_dims);
  x_grad->set_dtype(out_grad.dtype());
  x_grad->share_lod(out_grad);
}

3572 3573 3574 3575 3576 3577 3578 3579
void SetValueInferMeta(const MetaTensor& x, MetaTensor* out) {
  auto in_dims = x.dims();
  PADDLE_ENFORCE_LT(
      in_dims.size(),
      7,
      phi::errors::InvalidArgument(
          "The rank of input should be less than 7, but received %d.",
          in_dims.size()));
3580
  out->set_dims(in_dims);
3581 3582
}

3583 3584 3585 3586 3587 3588
void ShapeInferMeta(const MetaTensor& input, MetaTensor* out) {
  auto in_dim = input.dims();
  out->set_dims(phi::make_ddim({in_dim.size()}));
  out->set_dtype(DataType::INT32);
}

Z
zyfncg 已提交
3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616
void ShardIndexInferMeta(const MetaTensor& in,
                         int index_num,
                         int nshards,
                         int shard_id,
                         int ignore_value,
                         MetaTensor* out,
                         MetaConfig config) {
  auto x_dims = in.dims();
  PADDLE_ENFORCE_GE(
      x_dims.size(),
      2,
      phi::errors::InvalidArgument("Rank of Input(X) should be at least 2, "
                                   "but the value given is %d.",
                                   x_dims.size()));
  if (config.is_runtime || x_dims[x_dims.size() - 1] > 0) {
    PADDLE_ENFORCE_EQ(x_dims[x_dims.size() - 1],
                      1U,
                      phi::errors::InvalidArgument(
                          "The last dimension of Input(X) should be 1, "
                          "but the value given is %d.",
                          x_dims[x_dims.size() - 1]));
  }

  out->set_dims(x_dims);
  out->share_lod(in);
  out->set_dtype(in.dtype());
}

3617
void NumelInferMeta(const MetaTensor& input, MetaTensor* out) {
Z
zyfncg 已提交
3618
  out->set_dtype(DataType::INT64);
zhouweiwei2014's avatar
zhouweiwei2014 已提交
3619
  out->set_dims(phi::make_ddim({}));
Z
zyfncg 已提交
3620 3621
}

H
hong 已提交
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
void SliceRawInferMeta(const MetaTensor& input,
                       const std::vector<int64_t>& axes,
                       const IntArray& starts_arr,
                       const IntArray& ends_arr,
                       const std::vector<int64_t>& infer_flags_t,
                       const std::vector<int64_t>& decrease_axis,
                       MetaTensor* out,
                       MetaConfig config) {
  auto in_dims = input.dims();
  PADDLE_ENFORCE_LT(
      in_dims.size(),
      7,
      phi::errors::InvalidArgument("The rank of input should be less than 7."));
  DDim out_dims(in_dims);

  std::vector<int64_t> infer_flags = infer_flags_t;
  if (infer_flags.empty()) {
    // Initialize infer_flags with 1.
    // To be compatible with other op tests in which infer_flags is not set.
    infer_flags = std::vector<int64_t>(axes.size(), 1);
  }
3643 3644 3645 3646 3647 3648
  auto new_axes = axes;
  for (auto& axis : new_axes) {
    if (axis < 0) {
      axis = std::max(int64_t(0), axis + int64_t(in_dims.size()));
    }
  }
H
hong 已提交
3649

3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
  PADDLE_ENFORCE_EQ(
      axes.size(),
      starts_arr.size(),
      phi::errors::InvalidArgument(
          "The length of axes (%d) and length of starts (%d) should be same.",
          axes.size(),
          starts_arr.size()));
  PADDLE_ENFORCE_EQ(
      axes.size(),
      ends_arr.size(),
      phi::errors::InvalidArgument(
          "The length of axes (%d) and length of ends (%d) should be same.",
          axes.size(),
          ends_arr.size()));

H
hong 已提交
3665 3666 3667 3668 3669
  // 2.1 Check attrs.
  std::vector<int64_t> starts = starts_arr.GetData();
  std::vector<int64_t> ends = ends_arr.GetData();

  phi::funcs::CheckAndUpdateSliceAttrs<int64_t>(
3670
      in_dims, new_axes, &starts, &ends, nullptr, &infer_flags);
H
hong 已提交
3671 3672

  auto slice_dims = phi::funcs::GetSliceDims<int64_t>(
3673
      in_dims, new_axes, starts, ends, nullptr, &infer_flags);
H
hong 已提交
3674 3675 3676 3677 3678 3679 3680 3681 3682
  if (config.is_runtime) {
    out_dims = phi::funcs::GetDecreasedDims<int64_t>(
        slice_dims, decrease_axis, &infer_flags);
  } else {
    out_dims = phi::funcs::GetDecreasedDims<int64_t>(
        slice_dims, decrease_axis, nullptr);
  }

  out->set_dims(out_dims);
3683
  if (!new_axes.empty() && new_axes[0] != 0) {
H
hong 已提交
3684 3685
    out->share_lod(input);
  }
W
wanghuancoder 已提交
3686
  out->set_dtype(input.dtype());
H
hong 已提交
3687 3688
}

Z
zyfncg 已提交
3689 3690 3691
void SoftmaxInferMeta(const MetaTensor& x, int axis, MetaTensor* out) {
  auto dim_x = x.dims();
  auto rank_x = dim_x.size();
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714
  if (rank_x > 0) {
    PADDLE_ENFORCE_GE(axis,
                      -rank_x,
                      phi::errors::InvalidArgument(
                          "Attr(axis) value should be in range [-R, R-1], "
                          "R is the rank of Input(X)."));
    PADDLE_ENFORCE_LT(axis,
                      rank_x,
                      phi::errors::InvalidArgument(
                          "Attr(axis) value should be in range [-R, R-1], "
                          "R is the rank of Input(X)."));
  } else {
    PADDLE_ENFORCE_GE(
        axis,
        -1,
        phi::errors::InvalidArgument("Attr(axis) value should be in range [-1, "
                                     "0] when input is 0D Tensor "));
    PADDLE_ENFORCE_LE(
        axis,
        0,
        phi::errors::InvalidArgument("Attr(axis) value should be in range [-1, "
                                     "0] when input is 0D Tensor "));
  }
Z
zyfncg 已提交
3715 3716 3717 3718 3719 3720

  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
  out->share_lod(x);
}

C
Charles-hit 已提交
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
int GetSplitAxisValue(const MetaTensor& x,
                      const Scalar& axis,
                      MetaConfig config) {
  // Tensor has no value in static graph compile time
  if (axis.FromTensor() && !config.is_runtime) {
    return -1;
  } else {
    if (axis.dtype() == DataType::FLOAT32 ||
        axis.dtype() == DataType::FLOAT64) {
      PADDLE_THROW(
          phi::errors::InvalidArgument("%s(): argument (position 3) must be "
                                       "int, but got %s",
                                       "split",
                                       "float"));  // NOLINT
    }
    int axis_value = axis.to<int>();
    int rank = x.dims().size();
    PADDLE_ENFORCE_EQ(
        axis_value >= -rank && axis_value < rank,
        true,
        phi::errors::InvalidArgument(
            "The axis is expected to be in range of [%d, %d), but got %d",
            -rank,
            rank,
            axis_value));
    if (axis_value < 0) {
      axis_value = axis_value + rank;
    }
    return axis_value;
  }
}

void FillSplitOutDims(const MetaTensor& x,
                      const int axis_value,
                      const std::vector<int64_t>& sections_vec,
                      std::vector<MetaTensor*>* out) {
  std::vector<phi::DDim> out_dims(sections_vec.size(), x.dims());
  if (x.dims().at(axis_value) > 0) {
    for (size_t i = 0; i < sections_vec.size(); ++i) {
      out_dims[i][axis_value] = sections_vec[i];
    }
  } else {
    for (size_t i = 0; i < sections_vec.size(); ++i) {
      out_dims[i][axis_value] = -1;
    }
  }
  for (size_t i = 0; i < sections_vec.size(); ++i) {
    if (axis_value != 0) {
      // Only pass LoD when not spliting along the first dim.
      (*out)[i]->set_dtype(x.dtype());
      (*out)[i]->set_dims(out_dims[i]);
      (*out)[i]->set_layout(x.layout());
X
xiaoxiaohehe001 已提交
3773
      (*out)[i]->share_lod(x);
C
Charles-hit 已提交
3774 3775 3776 3777 3778 3779 3780 3781
    } else {
      (*out)[i]->set_dtype(x.dtype());
      (*out)[i]->set_dims(out_dims[i]);
      (*out)[i]->set_layout(x.layout());
    }
  }
}

Z
zyfncg 已提交
3782
void SplitInferMeta(const MetaTensor& x,
C
Charles-hit 已提交
3783
                    const IntArray& sections,
Z
zyfncg 已提交
3784 3785 3786
                    const Scalar& axis,
                    std::vector<MetaTensor*> out,
                    MetaConfig config) {
C
Charles-hit 已提交
3787 3788 3789 3790 3791 3792 3793
  // get axis value
  int axis_value = GetSplitAxisValue(x, axis, config);

  auto sections_data = sections.GetData();
  // fill out dims with -1
  if ((sections.FromTensor() && !config.is_runtime) || axis_value == -1 ||
      (axis_value >= 0 && x.dims().at(axis_value) <= 0)) {
3794 3795 3796 3797 3798 3799 3800 3801
    std::vector<phi::DDim> out_dims;
    if ((sections.FromTensor() && !config.is_runtime) || axis_value == -1) {
      out_dims = std::vector<phi::DDim>(
          sections_data.size(),
          phi::make_ddim(std::vector<int>(x.dims().size(), -1)));
    } else {
      out_dims = std::vector<phi::DDim>(sections_data.size(), x.dims());
    }
C
Charles-hit 已提交
3802 3803 3804 3805 3806 3807
    for (size_t i = 0; i < sections_data.size(); ++i) {
      if (axis_value != 0) {
        // Only pass LoD when not spliting along the first dim.
        out[i]->set_dtype(x.dtype());
        out[i]->set_dims(out_dims[i]);
        out[i]->set_layout(x.layout());
X
xiaoxiaohehe001 已提交
3808
        out[i]->share_lod(x);
C
Charles-hit 已提交
3809 3810 3811 3812 3813
      } else {
        out[i]->set_dtype(x.dtype());
        out[i]->set_dims(out_dims[i]);
        out[i]->set_layout(x.layout());
      }
C
chentianyu03 已提交
3814 3815
    }
  } else {
C
Charles-hit 已提交
3816 3817
    auto input_axis_dim = x.dims().at(axis_value);
    std::vector<int64_t> sections_vec;
C
chentianyu03 已提交
3818 3819 3820 3821 3822
    const int unknow_dim_val = -1;
    int unknow_dim_idx = -1;
    int num_of_unknow = 0;
    int sum_of_section = 0;

C
Charles-hit 已提交
3823 3824
    for (size_t i = 0; i < sections_data.size(); ++i) {
      sections_vec.push_back(sections_data[i]);
3825

C
Charles-hit 已提交
3826
      if (sections_data[i] == unknow_dim_val) {
C
chentianyu03 已提交
3827 3828 3829
        num_of_unknow++;
        unknow_dim_idx = i;
      } else {
C
Charles-hit 已提交
3830
        sum_of_section += sections_data[i];
C
chentianyu03 已提交
3831 3832 3833
      }
    }

C
Charles-hit 已提交
3834 3835 3836 3837 3838 3839 3840
    PADDLE_ENFORCE_LE(num_of_unknow,
                      1,
                      phi::errors::InvalidArgument(
                          "Only one dimension value of Attr(num_or_sections) "
                          "in SplitOp can be -1. "
                          "But received Attr(num_or_sections) = [%s].",
                          phi::make_ddim(sections_data)));
C
chentianyu03 已提交
3841 3842 3843 3844 3845 3846 3847 3848

    if (unknow_dim_idx != -1) {
      // for example, input shape = [4 ,5], axis = 1, sections = [2, 3, -1].
      // input_axis_dim = 5, sum_of_sections = 5.
      // the following check will fail.
      PADDLE_ENFORCE_LT(
          sum_of_section,
          input_axis_dim,
3849
          phi::errors::InvalidArgument(
C
chentianyu03 已提交
3850 3851 3852 3853 3854
              "Sum of Attr(num_or_sections) other than unknown section "
              "must be less than the input's "
              "size "
              "along the split dimension. But received Attr(num_or_sections) "
              "= [%s], input(X)'s shape = [%s], Attr(dim) = %d.",
C
Charles-hit 已提交
3855
              phi::make_ddim(sections_data),
C
chentianyu03 已提交
3856 3857 3858
              x.dims(),
              axis_value));

C
Charles-hit 已提交
3859
      sections_vec[unknow_dim_idx] = input_axis_dim - sum_of_section;
C
chentianyu03 已提交
3860 3861 3862 3863
    } else {
      PADDLE_ENFORCE_EQ(
          sum_of_section,
          input_axis_dim,
3864
          phi::errors::InvalidArgument(
C
chentianyu03 已提交
3865 3866 3867 3868
              "Sum of Attr(num_or_sections) must be equal to the input's "
              "size "
              "along the split dimension. But received Attr(num_or_sections)"
              " = [%s], input(X)'s shape = [%s], Attr(dim) = %d.",
C
Charles-hit 已提交
3869
              phi::make_ddim(sections_data),
C
chentianyu03 已提交
3870 3871 3872
              x.dims(),
              axis_value));
    }
C
Charles-hit 已提交
3873 3874
    // fill out dims
    FillSplitOutDims(x, axis_value, sections_vec, &out);
3875
  }
C
Charles-hit 已提交
3876 3877 3878 3879 3880 3881 3882 3883 3884 3885
}

void SplitWithNumInferMeta(const MetaTensor& x,
                           int num,
                           const Scalar& axis,
                           std::vector<MetaTensor*> out,
                           MetaConfig config) {
  int axis_value = GetSplitAxisValue(x, axis, config);
  // fill out dims with -1
  if (axis_value == -1 || (axis_value >= 0 && x.dims().at(axis_value) <= 0)) {
3886 3887 3888 3889 3890 3891 3892
    std::vector<phi::DDim> out_dims;
    if (axis_value == -1) {
      out_dims = std::vector<phi::DDim>(
          num, phi::make_ddim(std::vector<int>(x.dims().size(), -1)));
    } else {
      out_dims = std::vector<phi::DDim>(num, x.dims());
    }
C
Charles-hit 已提交
3893 3894 3895 3896 3897 3898
    for (int i = 0; i < num; ++i) {
      if (axis_value != 0) {
        // Only pass LoD when not spliting along the first dim.
        out[i]->set_dtype(x.dtype());
        out[i]->set_dims(out_dims[i]);
        out[i]->set_layout(x.layout());
X
xiaoxiaohehe001 已提交
3899
        out[i]->share_lod(x);
C
Charles-hit 已提交
3900 3901 3902 3903 3904
      } else {
        out[i]->set_dtype(x.dtype());
        out[i]->set_dims(out_dims[i]);
        out[i]->set_layout(x.layout());
      }
C
chentianyu03 已提交
3905
    }
3906
  } else {
C
Charles-hit 已提交
3907 3908 3909
    auto input_axis_dim = x.dims().at(axis_value);
    // step1: get formated sections
    std::vector<int64_t> sections_vec;
张春乔 已提交
3910 3911 3912 3913
    PADDLE_ENFORCE_NE(
        num,
        0,
        phi::errors::InvalidArgument("Attr(num_or_sections) should not be 0."));
C
Charles-hit 已提交
3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
    PADDLE_ENFORCE_EQ(input_axis_dim % num,
                      0,
                      phi::errors::InvalidArgument(
                          "The input's size along the split dimension "
                          "must be evenly divisible by Attr(num_or_sections). "
                          "But received Attr(num_or_sections) "
                          "= %d, input(X)'s shape = [%s], Attr(dim) = %d.",
                          num,
                          x.dims(),
                          axis_value));
C
chentianyu03 已提交
3924

C
Charles-hit 已提交
3925 3926
    for (int i = 0; i < num; ++i) {
      sections_vec.push_back(input_axis_dim / num);
C
chentianyu03 已提交
3927
    }
C
Charles-hit 已提交
3928 3929
    // setp2: fill out dims
    FillSplitOutDims(x, axis_value, sections_vec, &out);
C
chentianyu03 已提交
3930
  }
C
Chen Weihang 已提交
3931 3932
}

3933 3934 3935 3936
void SquaredL2NormInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dims({1});
}

3937
void SqueezeInferMeta(const MetaTensor& x,
3938 3939 3940
                      const IntArray& axes,
                      MetaTensor* out,
                      MetaConfig config) {
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
  const auto& x_dims = x.dims();
  // Check input tensor dims (<6) Eigen limit.
  PADDLE_ENFORCE_LE(x_dims.size(),
                    6,
                    phi::errors::InvalidArgument(
                        "The dimensions of Input(X) "
                        "should be in the range of [1, 6] (Eigen limit)."
                        "But received X's dimensions = %d, X's shape = [%s].",
                        x_dims.size(),
                        x_dims));

3952 3953 3954
  if (!config.is_runtime && axes.FromTensor()) {
    // compile time infershape, set all elements to -1.
    int output_size = x.dims().size() - axes.GetData().size();
3955 3956 3957
    if (x.dims().size() == 0 && output_size == -1) {
      output_size = 0;
    }
3958
    std::vector<int64_t> vec_out_dims(output_size, -1);
W
wanghuancoder 已提交
3959

3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
    out->set_dims(phi::make_ddim(vec_out_dims));
  } else {
    std::vector<int32_t> tmp;
    tmp.reserve(axes.GetData().size());
    std::for_each(axes.GetData().begin(),
                  axes.GetData().end(),
                  [&tmp](const int64_t& t) { tmp.push_back(t); });
    auto out_dims = funcs::GetOutputSqueezeShape(tmp, x_dims, false);
    out->set_dims(out_dims);
    if (x_dims[0] == out_dims[0]) {
      // Only pass LoD when the first dimension of output and Input(X)
      // are the same.
      out->share_lod(x);
    }
3974
  }
3975 3976 3977 3978
  out->set_dtype(x.dtype());
}

void SqueezeWithXShapeInferMeta(const MetaTensor& x,
3979
                                const IntArray& axes,
3980
                                MetaTensor* out,
3981 3982 3983
                                MetaTensor* xshape,
                                MetaConfig config) {
  SqueezeInferMeta(x, axes, out, config);
3984
  const auto& x_dims = x.dims();
3985 3986 3987 3988 3989
  std::vector<int64_t> xshape_dims(x_dims.size() + 1);
  xshape_dims[0] = 0;
  for (int i = 0; i < x_dims.size(); ++i) {
    xshape_dims[i + 1] = x_dims[i];
  }
3990 3991 3992 3993 3994
  if (xshape) {
    xshape->set_dims(phi::make_ddim(xshape_dims));
    xshape->share_lod(x);
    xshape->set_dtype(x.dtype());
  }
3995 3996
}

3997 3998 3999 4000 4001 4002 4003 4004 4005
void StridedSliceRawInferMeta(const MetaTensor& x,
                              const std::vector<int>& axes,
                              const IntArray& starts,
                              const IntArray& ends,
                              const IntArray& strides,
                              const std::vector<int>& infer_flags,
                              const std::vector<int>& decrease_axis,
                              MetaTensor* out,
                              MetaConfig config) {
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
  auto in_dims = x.dims();
  PADDLE_ENFORCE_LT(
      in_dims.size(),
      7,
      errors::InvalidArgument(
          "The dimension of StridedSlice operator's input should be less "
          "than 7, but received dimension is %d.",
          in_dims.size()));

  auto starts_ = starts.GetData();
  auto ends_ = ends.GetData();
  auto strides_ = strides.GetData();

  auto starts_size = starts_.size();
  auto ends_size = ends_.size();
  auto strides_size = strides_.size();

  for (size_t i = 0; i < axes.size(); ++i) {
    PADDLE_ENFORCE_GE(
        axes[i],
        0,
        errors::InvalidArgument("The axis should be greater than or equal to 0."
                                "But received %d of axes[%d]",
                                axes[i],
                                i));
    PADDLE_ENFORCE_LT(
        axes[i],
        in_dims.size(),
        errors::InvalidArgument(
            "The axes should be less than or equal to input tensor's rank."
            "But received %d of axes[%d], input tensor shape [%d]",
            axes[i],
            i,
            in_dims.size()));
  }

  auto tensor_input = false;
4043
  auto HasInput = [](const IntArray& arr) { return arr.FromTensor(); };
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
  if (HasInput(starts) || HasInput(ends) || HasInput(strides)) {
    tensor_input = true;
  }
  if (!HasInput(ends)) {
    PADDLE_ENFORCE_EQ(
        ends_size,
        axes.size(),
        errors::InvalidArgument(
            "The size of ends attribute in StridedSlice operator is not "
            "equal to the size of axes attribute. The ends attribute's size "
            "is %d, axes attribute's size is %d.",
            ends_size,
            axes.size()));
  }
  if (!HasInput(starts)) {
    PADDLE_ENFORCE_EQ(
        starts_size,
        axes.size(),
        errors::InvalidArgument(
            "The size of starts attribute in StridedSlice operator is not "
            "equal to the size of axes attribute. The starts attribute's "
            "size is %d, axes attribute's size is %d.",
            starts_size,
            axes.size()));
  }
  if (!HasInput(strides)) {
    PADDLE_ENFORCE_EQ(
        strides_size,
        axes.size(),
        errors::InvalidArgument(
            "The size of strides attribute in StridedSlice operator is not "
            "equal to the size of axes attribute. The strides attribute's "
            "size is %d, axes attribute's size is %d.",
            strides_size,
            axes.size()));
  }
  // we need to analysis strided slice op is valid for
  // the parameter that we get from python front
  std::vector<int64_t> out_dims_vector(in_dims.size(), -1);
  if (!tensor_input || config.is_runtime) {
    phi::funcs::StridedSliceOutDims(starts_,
                                    ends_,
                                    strides_,
                                    axes,
                                    infer_flags,
                                    in_dims,
                                    decrease_axis,
                                    out_dims_vector.data(),
                                    axes.size(),
                                    true);
  }
  DDim out_dims(phi::make_ddim(out_dims_vector));
  // generate new shape
4097
  if (!decrease_axis.empty()) {
4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
    std::vector<int64_t> new_out_shape;
    for (size_t i = 0; i < decrease_axis.size(); ++i) {
      if (config.is_runtime && infer_flags[i] != -1) {
        PADDLE_ENFORCE_EQ(out_dims[decrease_axis[i]],
                          1,
                          errors::InvalidArgument(
                              "the size of decrease dimension should be 1, "
                              "but received %d.",
                              out_dims[decrease_axis[i]]));
      }
      out_dims[decrease_axis[i]] = 0;
    }

    for (int i = 0; i < out_dims.size(); ++i) {
      if (out_dims[i] != 0) {
        new_out_shape.push_back(out_dims[i]);
      }
    }
    out_dims = phi::make_ddim(new_out_shape);
  }
L
Leo Chen 已提交
4118
  VLOG(4) << "out_dims: " << out_dims;
4119 4120 4121 4122 4123
  out->set_dims(out_dims);
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136
void StridedSliceInferMeta(const MetaTensor& x,
                           const std::vector<int>& axes,
                           const IntArray& starts,
                           const IntArray& ends,
                           const IntArray& strides,
                           MetaTensor* out,
                           MetaConfig config) {
  std::vector<int> infer_flags(axes.size(), 1);
  std::vector<int> decrease_axis;
  StridedSliceRawInferMeta(
      x, axes, starts, ends, strides, infer_flags, decrease_axis, out, config);
}

Z
zyfncg 已提交
4137
void SumRawInferMeta(const MetaTensor& x,
4138
                     const IntArray& axis,
Z
zyfncg 已提交
4139 4140 4141
                     bool keep_dim,
                     bool reduce_all,
                     DataType dtype,
4142 4143 4144 4145
                     MetaTensor* out,
                     MetaConfig config) {
  DDim out_dim;
  if (config.is_runtime || !axis.FromTensor()) {
4146
    out_dim = ReduceInferDim(x, axis.GetData(), keep_dim, reduce_all);
4147
  } else {
4148
    out_dim = ReduceInferDimForIntArrayAxis(x, axis, keep_dim, reduce_all);
4149
  }
Z
zyfncg 已提交
4150 4151 4152 4153 4154

  DataType out_dtype;
  if (dtype != DataType::UNDEFINED) {
    out_dtype = dtype;
  } else {
4155
    if (x.dtype() == DataType::BOOL || x.dtype() == DataType::INT32) {
Z
zyfncg 已提交
4156 4157 4158 4159
      out_dtype = DataType::INT64;
    } else {
      out_dtype = x.dtype();
    }
L
Leo Chen 已提交
4160 4161
  }

Z
zyfncg 已提交
4162 4163 4164 4165 4166
  out->set_dims(out_dim);
  out->set_dtype(out_dtype);
  out->set_layout(x.layout());
}

4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
/*  Why not use SumRawInferMeta directly?
    Because we need make InferMetaFunction's args follow the design of
   ops.yaml
*/
void SumInferMeta(const MetaTensor& x,
                  const IntArray& axis,
                  DataType dtype,
                  bool keep_dim,
                  MetaTensor* out,
                  MetaConfig config) {
4177 4178 4179 4180
  bool reduce_all = false;
  if (axis.size() == 0) {
    reduce_all = true;
  }
4181
  SumRawInferMeta(x, axis, keep_dim, reduce_all, dtype, out, config);
4182 4183
}

4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230
void SvdInferMeta(const MetaTensor& x,
                  bool full_matrices,
                  MetaTensor* u,
                  MetaTensor* s,
                  MetaTensor* vh) {
  auto UDDim = [](const DDim& x_dim, int k) {
    // get x_dim and return the ddim of U
    auto x_vec = vectorize(x_dim);
    x_vec[x_vec.size() - 1] = k;
    return phi::make_ddim(x_vec);
  };

  auto VHDDim = [](const DDim& x_dim, int k) {
    // get x_dim and return the ddim of U
    auto x_vec = vectorize(x_dim);
    x_vec[x_vec.size() - 2] = k;
    return phi::make_ddim(x_vec);
  };

  auto SDDim = [](const DDim& x_dim, int k) {
    // get x_dim and return the ddim of U
    auto x_vec = vectorize(x_dim);
    x_vec[x_vec.size() - 2] = k;
    x_vec.erase(x_vec.end() - 1);  // rank - 1
    return phi::make_ddim(x_vec);
  };

  auto in_dims = x.dims();
  int x_rank = in_dims.size();
  PADDLE_ENFORCE_GE(
      in_dims.size(),
      2,
      phi::errors::InvalidArgument("the rank of input must greater than 2"));
  int m = in_dims[x_rank - 2];
  int n = in_dims[x_rank - 1];
  int k = std::min(m, n);
  u->set_dims(!full_matrices ? UDDim(in_dims, k) : UDDim(in_dims, m));
  vh->set_dims(!full_matrices ? VHDDim(in_dims, k) : VHDDim(in_dims, n));
  s->set_dims(SDDim(in_dims, k));
  u->share_lod(x);
  vh->share_lod(x);
  s->share_lod(x);
  u->set_dtype(x.dtype());
  vh->set_dtype(x.dtype());
  s->set_dtype(x.dtype());
}

H
hong 已提交
4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276
void TemporalShiftInferMeta(const MetaTensor& x,
                            int seg_num,
                            float shift_ratio,
                            const std::string& data_format,
                            MetaTensor* out,
                            MetaConfig config) {
  auto dim_x = x.dims();
  PADDLE_ENFORCE_EQ(dim_x.size(),
                    4,
                    phi::errors::InvalidArgument(
                        "Input(X) rank should be 4 in shape of [N*T, C, H, "
                        "W], but received X rank(%d)",
                        dim_x.size()));

  PADDLE_ENFORCE_GT(
      seg_num,
      0,
      phi::errors::InvalidArgument(
          "Attr(seg_num) should be greater than 0, but received %d", seg_num));
  PADDLE_ENFORCE_GT(
      shift_ratio,
      0.,
      phi::errors::InvalidArgument(
          "Attr(shift_ratio) should be greater than 0, but received %d",
          shift_ratio));
  PADDLE_ENFORCE_LT(
      shift_ratio,
      0.5,
      phi::errors::InvalidArgument(
          "Attr(shift_ratio) should be less than 0.5, but received %d",
          shift_ratio));

  if (config.is_runtime) {
    PADDLE_ENFORCE_EQ(dim_x[0] % seg_num,
                      0,
                      phi::errors::InvalidArgument(
                          "Input(X) dimension[0] should be divided exactly "
                          "by Attr(seg_num), but received X dimension[0](%d) "
                          "mod seg_num(%d) != 0",
                          dim_x[0],
                          seg_num));
  }

  out->share_meta(x);
}

Z
zyfncg 已提交
4277
void TileInferMeta(const MetaTensor& x,
4278
                   const IntArray& repeat_times,
Z
zyfncg 已提交
4279 4280 4281 4282 4283 4284
                   MetaTensor* out,
                   MetaConfig config) {
#define MAX_RANK_SUPPORTED 6

  auto repeat_times_data = repeat_times.GetData();
  auto x_dims = x.dims();
4285
  if (repeat_times_data.empty()) {
4286
    repeat_times_data = std::vector<int64_t>(x_dims.size(), 1);
Z
zyfncg 已提交
4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
  }

  PADDLE_ENFORCE_LE(
      x_dims.size(),
      MAX_RANK_SUPPORTED,
      errors::InvalidArgument(
          "The rank of the input 'x' for tile op "
          "must not be greater than %d, but the value received is %d.",
          MAX_RANK_SUPPORTED,
          x_dims.size()));
  PADDLE_ENFORCE_LE(
      repeat_times_data.size(),
      MAX_RANK_SUPPORTED,
      errors::InvalidArgument(
          "The size of the shape of input 'repeat_times' for tile op "
          "must not be greater than %d, but the value received is %d.",
          MAX_RANK_SUPPORTED,
          repeat_times_data.size()));
  PADDLE_ENFORCE_GE(
      repeat_times_data.size(),
4307
      0,
Z
zyfncg 已提交
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318
      errors::InvalidArgument(
          "The size of the shape of input 'repeat_times' for tile op "
          "must be positive integers, but the value received is %d.",
          repeat_times_data.size()));

  auto out_rank =
      std::max(static_cast<size_t>(x_dims.size()), repeat_times_data.size());
  std::vector<int64_t> out_shape(out_rank);
  auto x_dim_vec = phi::vectorize<int>(x_dims);
  if (x_dim_vec.size() > repeat_times_data.size()) {
    auto diff = x_dim_vec.size() - repeat_times_data.size();
4319
    repeat_times_data.insert(repeat_times_data.begin(), diff, 1);
Z
zyfncg 已提交
4320 4321
  } else {
    auto diff = repeat_times_data.size() - x_dim_vec.size();
4322
    x_dim_vec.insert(x_dim_vec.begin(), diff, 1);
Z
zyfncg 已提交
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339
  }
  for (size_t i = 0; i < repeat_times_data.size(); ++i) {
    if (x_dim_vec[i] == -1 || repeat_times_data[i] == -1) {
      out_shape[i] = -1;
    } else {
      PADDLE_ENFORCE_GT(
          repeat_times_data[i],
          0,
          errors::InvalidArgument(
              "Every element of the input 'repeat_times' for tile op must be "
              "greater than 0, but the value given is %d.",
              repeat_times_data[i]));
      out_shape[i] = x_dim_vec[i] * repeat_times_data[i];
    }
  }

  out->set_dims(phi::make_ddim(out_shape));
4340
  if (out_rank > 0 && (out_shape[0] == x_dims[0])) {
Z
zyfncg 已提交
4341
    out->share_lod(x);
L
Leo Chen 已提交
4342
  }
4343
  out->set_dtype(x.dtype());
L
Leo Chen 已提交
4344 4345
}

4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
void TopKInferMeta(const MetaTensor& x,
                   const Scalar& k_scalar,
                   int axis,
                   bool largest,
                   bool sorted,
                   MetaTensor* out,
                   MetaTensor* indices,
                   MetaConfig config) {
  auto input_dims = x.dims();
  const int& dim_size = input_dims.size();
4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
  if (dim_size != 0) {
    PADDLE_ENFORCE_EQ(
        (axis < dim_size) && (axis >= (-1 * dim_size)),
        true,
        phi::errors::InvalidArgument(
            "the axis of topk must be [-%d, %d), but you set axis is %d",
            dim_size,
            dim_size,
            axis));
  } else {
    PADDLE_ENFORCE_EQ(
        (axis == dim_size) || (axis == -1),
        true,
        phi::errors::InvalidArgument("the axis of topk must be 0 or -1 when "
                                     "x.dims() = 0, but you set axis is %d",
                                     axis));
  }
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389

  if (axis < 0) axis += dim_size;

  int k = k_scalar.to<int>();
  if (k_scalar.FromTensor()) {
    k = -1;
  } else {
    PADDLE_ENFORCE_EQ(k >= 1,
                      true,
                      phi::errors::InvalidArgument(
                          "the attribute of k in the topk must >= 1 or be a "
                          "Tensor, but received %d .",
                          k));
  }

  PADDLE_ENFORCE_GE(
      input_dims.size(),
4390 4391
      0,
      phi::errors::InvalidArgument("input of topk must have >= 0d shape"));
4392 4393

  phi::DDim dims = input_dims;
4394 4395 4396
  if (input_dims.size() > 0) {
    dims[axis] = k;
  }
4397 4398 4399 4400 4401 4402 4403 4404
  out->set_dims(dims);
  out->share_lod(x);
  out->set_dtype(x.dtype());
  indices->set_dims(dims);
  indices->share_lod(x);
  indices->set_dtype(DataType::INT64);
}

C
Chen Weihang 已提交
4405 4406 4407 4408 4409 4410
void TraceInferMeta(
    const MetaTensor& x, int offset, int axis1, int axis2, MetaTensor* out) {
  int dim1 = axis1;
  int dim2 = axis2;

  auto x_dims = x.dims();
C
chentianyu03 已提交
4411

C
Chen Weihang 已提交
4412 4413 4414 4415 4416 4417
  int dim1_ = dim1 < 0 ? x_dims.size() + dim1 : dim1;
  int dim2_ = dim2 < 0 ? x_dims.size() + dim2 : dim2;

  PADDLE_ENFORCE_GE(
      x_dims.size(),
      2,
4418
      phi::errors::OutOfRange(
X
XiangGao 已提交
4419
          "Input(x)'s dim is out of range (expected at least 2, but got %ld).",
C
Chen Weihang 已提交
4420 4421 4422 4423
          x_dims.size()));
  PADDLE_ENFORCE_LT(
      dim1_,
      x_dims.size(),
4424
      phi::errors::OutOfRange(
X
XiangGao 已提交
4425 4426 4427 4428 4429 4430 4431 4432 4433 4434
          "axis1 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          dim1));
  PADDLE_ENFORCE_GE(
      dim1_,
      0,
      phi::errors::OutOfRange(
          "axis1 is out of range (expected to be in range of [%ld, "
C
Chen Weihang 已提交
4435 4436 4437 4438 4439 4440 4441
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          dim1));
  PADDLE_ENFORCE_LT(
      dim2_,
      x_dims.size(),
4442
      phi::errors::OutOfRange(
X
XiangGao 已提交
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452
          "axis2 is out of range (expected to be in range of [%ld, "
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          dim2));
  PADDLE_ENFORCE_GE(
      dim2_,
      0,
      phi::errors::OutOfRange(
          "axis2 is out of range (expected to be in range of [%ld, "
C
Chen Weihang 已提交
4453 4454 4455 4456 4457 4458 4459
          "%ld], but got %ld).",
          -(x_dims.size()),
          (x_dims.size() - 1),
          dim2));
  PADDLE_ENFORCE_NE(
      dim1_,
      dim2_,
4460 4461 4462 4463
      phi::errors::InvalidArgument("The dimensions should not be identical "
                                   "%ld vs %ld.",
                                   dim1,
                                   dim2));
C
Chen Weihang 已提交
4464 4465 4466 4467 4468 4469 4470 4471

  auto sizes = vectorize(x_dims);
  if (x_dims.size() == 2) {
    sizes.clear();
  } else {
    sizes.erase(sizes.begin() + std::max(dim1_, dim2_));
    sizes.erase(sizes.begin() + std::min(dim1_, dim2_));
  }
4472
  out->set_dims(phi::make_ddim(sizes));
C
Chen Weihang 已提交
4473
  out->set_dtype(x.dtype());
C
chentianyu03 已提交
4474 4475
}

Z
zyfncg 已提交
4476
void TransferLayoutInferMeta(const MetaTensor& x,
4477 4478
                             int src_layout,
                             int dst_layout,
Z
zyfncg 已提交
4479 4480 4481
                             MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
4482 4483
  out->set_layout(static_cast<DataLayout>(dst_layout));
  out->share_lod(x);
Z
zyfncg 已提交
4484
}
H
hong 已提交
4485

Z
zyfncg 已提交
4486 4487 4488 4489
void TransposeInferMeta(const MetaTensor& x,
                        const std::vector<int>& axis,
                        MetaTensor* out) {
  auto x_dims = x.dims();
4490 4491
  int x_rank = x_dims.size();
  int axis_size = axis.size();
H
hong 已提交
4492

4493 4494
  // Note: x_rank > axis_size when fuse squeeze2 + transpose2, else x_rank ==
  // axis_size
4495 4496 4497 4498 4499 4500 4501 4502 4503
  PADDLE_ENFORCE_GE(x_rank,
                    axis_size,
                    errors::InvalidArgument(
                        "The input tensor's dimension "
                        "should be equal to or greater than the axis's size. "
                        "But received input tensor's dimension is %d, "
                        "axis's size is %d",
                        x_rank,
                        axis_size));
H
hong 已提交
4504

4505
  std::vector<int> formated_axis = axis;
Z
zyfncg 已提交
4506
  std::vector<int> count(axis_size, 0);
4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525
  for (int i = 0; i < axis_size; i++) {
    PADDLE_ENFORCE_LT(axis[i],
                      x_rank,
                      errors::InvalidArgument(
                          "The reduce dim index %d should be in the "
                          "range [ -dimension(X), dimension(X) ) "
                          "which dimesion = %d. But received dim index = %d.",
                          i,
                          x_rank,
                          axis[i]));
    PADDLE_ENFORCE_GE(axis[i],
                      -x_rank,
                      errors::InvalidArgument(
                          "The reduce dim index %d should be in the "
                          "range [ -dimension(X), dimension(X) )  "
                          "which dimesion = %d. But received dim index = %d.",
                          i,
                          x_rank,
                          axis[i]));
Z
zyfncg 已提交
4526

4527 4528 4529
    if (axis[i] < 0) {
      formated_axis[i] = axis[i] + x_rank;
    }
Z
zyfncg 已提交
4530
    PADDLE_ENFORCE_EQ(
4531 4532 4533 4534 4535 4536
        ++count[formated_axis[i]],
        1,
        errors::InvalidArgument("Each element of axis should be unique. but "
                                "axis[%d] is %d appear not only once",
                                i,
                                axis[i]));
H
hong 已提交
4537
  }
Z
zyfncg 已提交
4538 4539

  phi::DDim out_dims(x_dims);
4540 4541
  for (int i = 0; i < axis_size; ++i) {
    out_dims[i] = x_dims[formated_axis[i]];
Z
zyfncg 已提交
4542 4543 4544 4545 4546 4547 4548 4549
  }

  out->set_dims(out_dims);
  out->set_dtype(x.dtype());
}

void UnbindInferMeta(const MetaTensor& x,
                     int axis,
4550
                     std::vector<MetaTensor*> outs) {
Z
zyfncg 已提交
4551 4552
  auto in_dims = x.dims();
  std::vector<int> out_dim;
4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564

  PADDLE_ENFORCE_GE(
      axis,
      -in_dims.size(),
      phi::errors::InvalidArgument(
          "axis must be in range(%d, %d).", -in_dims.size(), in_dims.size()));
  PADDLE_ENFORCE_LT(
      axis,
      in_dims.size(),
      phi::errors::InvalidArgument(
          "axis must be in range(%d, %d).", -in_dims.size(), in_dims.size()));

Z
zyfncg 已提交
4565
  axis = axis < 0 ? in_dims.size() + axis : axis;
4566

Z
zyfncg 已提交
4567 4568 4569 4570 4571
  for (int i = 0; i < in_dims.size(); ++i) {
    if (i != axis) out_dim.push_back(in_dims[i]);
  }
  auto out_dims = phi::make_ddim(out_dim);

4572 4573 4574 4575 4576
  for (auto& out : outs) {
    out->set_dtype(x.dtype());
    out->set_dims(out_dims);
    out->set_layout(x.layout());
    out->share_lod(x);
Z
zyfncg 已提交
4577 4578 4579
  }
}

4580 4581 4582 4583
void TrilTriuInferMeta(const MetaTensor& x,
                       int diagonal,
                       bool lower,
                       MetaTensor* out) {
4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
  const auto& x_dims = x.dims();
  PADDLE_ENFORCE_GE(x_dims.size(),
                    2,
                    phi::errors::InvalidArgument(
                        "Input(X)'s rank must be at least 2 in TrilTriuOp."));
  out->set_dims(x.dims());
  out->share_lod(x);
  out->set_dtype(x.dtype());
}

4594 4595 4596 4597 4598 4599 4600 4601
void TrilInferMeta(const MetaTensor& x, int diagonal, MetaTensor* out) {
  TrilTriuInferMeta(x, diagonal, true, out);
}

void TriuInferMeta(const MetaTensor& x, int diagonal, MetaTensor* out) {
  TrilTriuInferMeta(x, diagonal, false, out);
}

4602 4603 4604 4605 4606 4607 4608
// Some operator having oneDnn kernel will be set layout in kernel.
void UnchangedExceptLayoutInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->set_dims(x.dims());
  out->set_dtype(x.dtype());
  out->share_lod(x);
}

Z
zyfncg 已提交
4609 4610 4611 4612 4613 4614 4615 4616 4617
void UnchangedInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->share_meta(x);
}

// meta x -> out without change, check if axis in range [-Rank(x), Rank(x)-1]
void UnchangedInferMetaCheckAxis(const MetaTensor& x,
                                 int axis,
                                 MetaTensor* out) {
  auto rank = x.dims().size();
4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640
  if (rank > 0) {
    PADDLE_ENFORCE_GE(axis,
                      -rank,
                      phi::errors::InvalidArgument(
                          "Attr(axis) value should be in range [-R, R-1], "
                          "R is the rank of Input(X)."));
    PADDLE_ENFORCE_LT(axis,
                      rank,
                      phi::errors::InvalidArgument(
                          "Attr(axis) value should be in range [-R, R-1], "
                          "R is the rank of Input(X)."));
  } else if (rank == 0) {
    PADDLE_ENFORCE_GE(
        axis,
        -1,
        phi::errors::InvalidArgument("Attr(axis) value should be in range [-1, "
                                     "0] when input is 0D Tensor "));
    PADDLE_ENFORCE_LE(
        axis,
        0,
        phi::errors::InvalidArgument("Attr(axis) value should be in range [-1, "
                                     "0] when input is 0D Tensor "));
  }
Z
zyfncg 已提交
4641
  out->share_meta(x);
H
hong 已提交
4642 4643
}

4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
void UnfoldInferMeta(const MetaTensor& x,
                     const std::vector<int>& kernel_sizes,
                     const std::vector<int>& strides,
                     const std::vector<int>& paddings,
                     const std::vector<int>& dilations,
                     MetaTensor* out,
                     MetaConfig config) {
  auto in_dims = x.dims();
  // Only [N, C, H, W] input supported now
  PADDLE_ENFORCE_EQ(
      in_dims.size(),
      4,
      phi::errors::InvalidArgument(
          "Input should be 4-D tensor of format [N, C, H, W], but get %u",
          in_dims.size()));
  PADDLE_ENFORCE_EQ(
      in_dims.size() - kernel_sizes.size(),
      2U,
      phi::errors::InvalidArgument(
          "The dims of X should be larger than that of kernel_sizes "
          "by a number of 2, due to the batch size and input channel dim. "
4665
          "But received dims(X:%u) - dims(kernel_sizes:%u) != 2",
4666 4667 4668 4669 4670 4671 4672
          in_dims.size(),
          kernel_sizes.size()));
  PADDLE_ENFORCE_EQ(
      strides.size(),
      kernel_sizes.size(),
      phi::errors::InvalidArgument(
          "The dims of strides should be the same with that of kernel_sizes. "
4673
          "But received dims(strides: %u) != dims(kernel_sizes: %u).",
4674 4675 4676 4677 4678 4679 4680
          strides.size(),
          kernel_sizes.size()));
  PADDLE_ENFORCE_EQ(
      paddings.size(),
      2 * strides.size(),
      phi::errors::InvalidArgument(
          "The dims of paddings should be 2 times of that of strides. "
4681
          "But received dims(paddings: %u) != 2*dims(strides: %u).",
4682 4683 4684 4685 4686 4687 4688
          paddings.size(),
          strides.size()));
  PADDLE_ENFORCE_EQ(
      strides.size(),
      dilations.size(),
      phi::errors::InvalidArgument(
          "The dims of strides should be the same with that of dilations. "
4689
          "But received dims(strides: %u) != dims(dilations: %u).",
4690 4691 4692 4693 4694 4695 4696 4697
          strides.size(),
          dilations.size()));

  // check kernel_sizes
  PADDLE_ENFORCE_GT(kernel_sizes[0],
                    0,
                    phi::errors::InvalidArgument(
                        "The `kernel_sizes` should be greater than zero, "
4698
                        "but received kernel_height: %d kernel_width: %d.",
4699 4700 4701 4702 4703 4704
                        kernel_sizes[0],
                        kernel_sizes[1]));
  PADDLE_ENFORCE_GT(kernel_sizes[1],
                    0,
                    phi::errors::InvalidArgument(
                        "The `kernel_sizes` should be greater than zero, "
4705
                        "but received kernel_height: %d kernel_width: %d.",
4706 4707 4708 4709 4710 4711 4712
                        kernel_sizes[0],
                        kernel_sizes[1]));
  // check strides
  PADDLE_ENFORCE_GT(strides[0],
                    0,
                    phi::errors::InvalidArgument(
                        "The `strides` should be greater than zero, "
4713
                        "but received strides_height: %d strides_width: %d.",
4714 4715 4716 4717 4718 4719
                        strides[0],
                        strides[1]));
  PADDLE_ENFORCE_GT(strides[1],
                    0,
                    phi::errors::InvalidArgument(
                        "The `strides` should be greater than zero, "
4720
                        "but received strides_height: %d strides_width: %d.",
4721 4722 4723 4724 4725 4726 4727 4728
                        strides[0],
                        strides[1]));
  // check dilations
  PADDLE_ENFORCE_GT(
      dilations[0],
      0,
      phi::errors::InvalidArgument(
          "The `dilations` should be greater than zero, "
4729
          "but received dilations_height: %d dilations_width: %d.",
4730 4731 4732 4733 4734 4735 4736
          dilations[0],
          dilations[1]));
  PADDLE_ENFORCE_GT(
      dilations[1],
      0,
      phi::errors::InvalidArgument(
          "The `dilations` should be greater than zero, "
4737
          "but received dilations_height: %d dilations_width: %d.",
4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757
          dilations[0],
          dilations[1]));

  std::vector<int> out_dims;
  out_dims.push_back(in_dims[0]);
  int output_channels = in_dims[1] * kernel_sizes[0] * kernel_sizes[1];
  out_dims.push_back(output_channels);

  int output_height = phi::funcs::CalcOutputSize(in_dims[2],
                                                 kernel_sizes[0],
                                                 dilations[0],
                                                 paddings[0],
                                                 paddings[2],
                                                 strides[0]);
  int output_width = phi::funcs::CalcOutputSize(in_dims[3],
                                                kernel_sizes[1],
                                                dilations[1],
                                                paddings[1],
                                                paddings[3],
                                                strides[1]);
4758
  int output_col_length = output_height * output_width;
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796
  if (config.is_runtime) {
    // only check output height and width in runtime
    PADDLE_ENFORCE_GT(
        output_height,
        0,
        phi::errors::InvalidArgument(
            "The sliding blocks calculated from input spatial size "
            "(%d, %d), kernel_sizes (%d, %d), strides (%d, %d), "
            "dilations (%d, %d), is (%d, %d), which should be a "
            "positive integer.",
            in_dims[2],
            in_dims[3],
            kernel_sizes[0],
            kernel_sizes[1],
            strides[0],
            strides[1],
            dilations[0],
            dilations[1],
            output_height,
            output_width));
    PADDLE_ENFORCE_GT(
        output_width,
        0,
        phi::errors::InvalidArgument(
            "The sliding blocks calculated from input spatial size "
            "(%d, %d), kernel_sizes (%d, %d), strides (%d, %d), "
            "dilations (%d, %d), is (%d, %d), which should be a "
            "positive integer.",
            in_dims[2],
            in_dims[3],
            kernel_sizes[0],
            kernel_sizes[1],
            strides[0],
            strides[1],
            dilations[0],
            dilations[1],
            output_height,
            output_width));
4797 4798 4799
  } else {
    output_col_length =
        output_height == -1 || output_width == -1 ? -1 : output_col_length;
4800 4801 4802 4803 4804
  }
  out_dims.push_back(output_col_length);
  out->set_dims(phi::make_ddim(out_dims));
}

4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841
void UniformRandomInplaceInferMeta(const MetaTensor& x,
                                   float min,
                                   float max,
                                   int seed,
                                   int diag_num,
                                   int diag_step,
                                   float diag_val,
                                   MetaTensor* out) {
  PADDLE_ENFORCE_LT(
      min,
      max,
      errors::InvalidArgument(
          "The uniform_random's min must less then max. But received min = "
          "%f great than or equal max = %f.",
          min,
          max));
  PADDLE_ENFORCE_GE(diag_num,
                    0,
                    errors::InvalidArgument(
                        "The uniform_random's diag_num must greater than or "
                        "equal 0. But recevied diag_num (%d) < 0.",
                        diag_num));
  PADDLE_ENFORCE_GE(diag_step,
                    0,
                    errors::InvalidArgument(
                        "The uniform_random's diag_step must greater than or "
                        "equal 0. But recevied diag_step (%d) < 0.",
                        diag_step));
  PADDLE_ENFORCE_NE(out,
                    nullptr,
                    phi::errors::InvalidArgument(
                        "uniform_random should have output tensor out."));
  auto xdim = x.dims();
  out->set_dims(xdim);
  out->set_dtype(x.dtype());
}

4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855
void UniqueConsecutiveInferMeta(const MetaTensor& x,
                                bool return_inverse,
                                bool return_counts,
                                const std::vector<int>& axis,
                                int dtype,
                                MetaTensor* out,
                                MetaTensor* index,
                                MetaTensor* counts) {
  PADDLE_ENFORCE_NE(out,
                    nullptr,
                    phi::errors::InvalidArgument(
                        "unique_consecutive should have output tensor out."));

  auto in_dims = x.dims();
D
duanboqiang 已提交
4856 4857 4858 4859 4860 4861 4862 4863
  if (x.dims().size() == 0) {
    PADDLE_ENFORCE_EQ(axis.empty(),
                      true,
                      phi::errors::InvalidArgument(
                          "The Input(X) with 0-D Tensor, axis must be None"
                          "But now the axis is %d.",
                          axis[0]));
  }
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
  if (return_inverse) {
    PADDLE_ENFORCE_NE(
        index,
        nullptr,
        phi::errors::InvalidArgument("Tensor index should not be null if "
                                     "return_inverse is set to True."));
  }
  if (return_counts) {
    PADDLE_ENFORCE_NE(
        counts,
        nullptr,
        phi::errors::InvalidArgument("Tensor counts should not be null if "
                                     "return_counts is set to True."));
  }

  if (axis.empty()) {
    out->set_dims({-1});
    out->set_dtype(x.dtype());
    if (return_inverse) {
      index->set_dims({phi::product(in_dims)});
    }
  } else {
    int axis_value = axis[0];
    if (axis_value < 0) {
      axis_value += in_dims.size();
    }
    PADDLE_ENFORCE_LT(
        axis_value,
        in_dims.size(),
        phi::errors::InvalidArgument("The axis(%d) should be less than "
                                     "the dimension size(%d) of x.",
                                     axis_value,
                                     in_dims.size()));
    auto out_dims = in_dims;
    out_dims[axis_value] = -1;
    out->set_dims(out_dims);
    out->set_dtype(x.dtype());
    if (return_inverse) {
      index->set_dims({in_dims[axis_value]});
    }
  }
  if (return_counts) {
    counts->set_dims({-1});
  }
}

C
csy0225 已提交
4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945
void UniqueInferMeta(const MetaTensor& x,
                     bool return_index,
                     bool return_inverse,
                     bool return_counts,
                     const std::vector<int>& axis,
                     DataType dtype,
                     MetaTensor* out,
                     MetaTensor* indices,
                     MetaTensor* index,
                     MetaTensor* counts) {
  bool is_sorted = true;
  UniqueRawInferMeta(x,
                     return_index,
                     return_inverse,
                     return_counts,
                     axis,
                     dtype,
                     is_sorted,
                     out,
                     indices,
                     index,
                     counts);
}

void UniqueRawInferMeta(const MetaTensor& x,
                        bool return_index,
                        bool return_inverse,
                        bool return_counts,
                        const std::vector<int>& axis,
                        DataType dtype,
                        bool is_sorted,
                        MetaTensor* out,
                        MetaTensor* indices,
                        MetaTensor* index,
                        MetaTensor* counts) {
  if (!is_sorted) {
S
sprouteer 已提交
4946 4947 4948 4949 4950 4951
    PADDLE_ENFORCE_EQ(x.dims().size() == 1 || x.dims().size() == 0,
                      true,
                      phi::errors::InvalidArgument(
                          "The Input(X) should be 0-D or 1-D Tensor, "
                          "But now the dims of Input(X) is %d.",
                          x.dims().size()));
C
csy0225 已提交
4952 4953 4954 4955 4956
    out->set_dims(phi::make_ddim({-1}));
    index->set_dims(x.dims());
    return;
  }

S
sprouteer 已提交
4957 4958 4959 4960 4961 4962 4963 4964 4965
  if (x.dims().size() == 0) {
    PADDLE_ENFORCE_EQ(axis.empty(),
                      true,
                      phi::errors::InvalidArgument(
                          "The Input(X) with 0-D Tensor, axis must be None"
                          "But now the axis is %d.",
                          axis[0]));
  }

C
csy0225 已提交
4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
  if (axis.empty()) {
    out->set_dims(phi::make_ddim({-1}));
    if (return_inverse) {
      index->set_dims(phi::make_ddim({phi::product(x.dims())}));
    }
  } else {
    int axis_value = axis[0];
    if (axis_value < 0) {
      axis_value += x.dims().size();
    }
4976

C
csy0225 已提交
4977 4978 4979 4980 4981 4982 4983
    PADDLE_ENFORCE_LT(
        axis_value,
        x.dims().size(),
        phi::errors::InvalidArgument("The axis(%d) should be less than "
                                     "the dimension size(%d) of x.",
                                     axis_value,
                                     x.dims().size()));
4984 4985 4986 4987 4988 4989 4990 4991
    PADDLE_ENFORCE_GE(
        axis_value,
        0,
        phi::errors::InvalidArgument(
            "The axis(%d) + rank(x) (%d) should be greater than or equal to 0.",
            axis_value,
            -x.dims().size()));

C
csy0225 已提交
4992 4993 4994 4995 4996
    auto out_dims = x.dims();
    out_dims[axis_value] = -1;
    out->set_dims(out_dims);
    if (return_inverse) {
      index->set_dims(phi::make_ddim({x.dims()[axis_value]}));
4997
      index->set_dtype(dtype);
C
csy0225 已提交
4998 4999 5000 5001
    }
  }
  if (return_index) {
    indices->set_dims(phi::make_ddim({-1}));
5002
    indices->set_dtype(dtype);
C
csy0225 已提交
5003 5004 5005
  }
  if (return_counts) {
    counts->set_dims(phi::make_ddim({-1}));
5006
    counts->set_dtype(dtype);
C
csy0225 已提交
5007 5008 5009
  }
}

5010
void UnsqueezeInferMeta(const MetaTensor& x,
5011
                        const IntArray& axes,
5012 5013
                        MetaTensor* out,
                        MetaConfig config) {
5014 5015 5016 5017 5018 5019 5020 5021
  const auto& x_dims = x.dims();
  // Validity Check: input tensor dims (<6).
  PADDLE_ENFORCE_LE(x_dims.size(),
                    6,
                    phi::errors::InvalidArgument(
                        "Invalid "
                        "dimensions, the rank of Input(X) "
                        "should be in the range of [1, 6] (Eigen limit)"));
5022 5023 5024 5025 5026 5027
  if (!config.is_runtime && axes.FromTensor()) {
    // compile time infershape.  set all elements to -1.
    int output_size = x.dims().size() + axes.GetData().size();
    std::vector<int64_t> vec_out_dims(output_size, -1);
    out->set_dtype(x.dtype());
    out->set_dims(phi::make_ddim(vec_out_dims));
5028 5029
  } else {
    auto out_dims = funcs::GetUnsqueezeShape(axes.GetData(), x_dims);
5030
    out->set_dims(out_dims);
5031
    if (x_dims.size() > 0 && x_dims[0] == out_dims[0]) {
5032 5033
      out->share_lod(x);
    }
5034
    out->set_dtype(x.dtype());
5035
  }
5036
}
5037

5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051
void UnsqueezeWithXShapeInferMeta(const MetaTensor& x,
                                  const IntArray& axes,
                                  MetaTensor* out,
                                  MetaTensor* xshape,
                                  MetaConfig config) {
  const auto& x_dims = x.dims();
  UnsqueezeInferMeta(x, axes, out, config);
  // set xshape dims.
  std::vector<int64_t> xshape_dims(x_dims.size() + 1);
  xshape_dims[0] = 0;
  for (int i = 0; i < x_dims.size(); ++i) {
    xshape_dims[i + 1] = x_dims[i];
  }
  if (xshape) {
5052 5053 5054
    xshape->set_dims(phi::make_ddim(xshape_dims));
    xshape->share_lod(x);
    xshape->set_dtype(x.dtype());
5055 5056 5057
  }
}

C
csy0225 已提交
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104
void UnStackInferMeta(const MetaTensor& x,
                      int axis,
                      int num,
                      std::vector<MetaTensor*> outs) {
  auto x_dim = x.dims();
  int rank = x_dim.size();
  PADDLE_ENFORCE_GE(axis,
                    -rank,
                    phi::errors::InvalidArgument(
                        "The attribute axis is out of range, it must be "
                        "inside [-rank, rank), where rank = %d",
                        rank));
  PADDLE_ENFORCE_LT(axis,
                    rank,
                    phi::errors::InvalidArgument(
                        "The attribute axis is out of range, it must be "
                        "inside [-rank, rank), where rank = %d",
                        rank));
  if (axis < 0) axis += rank;

  size_t output_count = outs.size();
  PADDLE_ENFORCE_EQ(output_count,
                    static_cast<size_t>(num),
                    phi::errors::InvalidArgument(
                        "Number of Outputs(Y) is wrong. Got %d , but it must "
                        "equal to attribute num which is %d.",
                        output_count,
                        static_cast<size_t>(num)));
  if (x_dim[axis] > 0) {
    PADDLE_ENFORCE_EQ(
        num,
        x_dim[axis],
        phi::errors::InvalidArgument(
            "The number of attribute num is not equal to the length of the "
            "%d axis of Input(X). Expect %d but got %d.",
            axis,
            x_dim[axis],
            num));
  }
  auto vec = phi::vectorize<int>(x_dim);
  vec.erase(vec.begin() + axis);
  for (size_t i = 0; i < output_count; i++) {
    outs[i]->set_dims(phi::make_ddim(vec));
    outs[i]->set_dtype(x.dtype());
  }
}

5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146
void WeightQuantizeInferMeta(const MetaTensor& x,
                             const std::string& algo,
                             MetaTensor* out,
                             MetaTensor* scale) {
  auto x_dims = x.dims();
  PADDLE_ENFORCE_EQ(
      x_dims.size(),
      2UL,
      phi::errors::InvalidArgument(
          "The x tensor of quant op must be 2D, but got[%d]", x_dims.size()));
  PADDLE_ENFORCE_EQ(
      x_dims[0] % 64,
      0,
      phi::errors::InvalidArgument(
          "The first dimension of input must be divisible by 64, but got[%d]",
          x_dims[0]));
  PADDLE_ENFORCE_EQ(
      x_dims[1] % 16,
      0,
      phi::errors::InvalidArgument(
          "The second dimension of input must be divisible by 16, but got[%d]",
          x_dims[1]));
  std::vector<int64_t> dim_scale({x_dims[1]});
  std::vector<int64_t> dim_out;
  if (algo == "weight_only_int8" || algo == "llm.int8") {
    dim_out = std::vector<int64_t>({x_dims[1], x_dims[0]});
  } else if (algo == "weight_only_int4") {
    dim_out = std::vector<int64_t>({x_dims[1] / 2, x_dims[0]});
  } else {
    phi::errors::InvalidArgument(
        "The algo must be in ['weight_only_int8', 'weight_only_int4', "
        "'llm.int8'], but got[%s]",
        algo);
  }
  out->set_dims(phi::make_ddim(dim_out));

  out->set_dtype(DataType::INT8);

  scale->set_dims(phi::make_ddim(dim_scale));
  scale->set_dtype(DataType::FLOAT32);
}

5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
void ChannelShuffleInferMeta(const MetaTensor& x,
                             int groups,
                             const std::string& data_format,
                             MetaTensor* out) {
  auto input_dims = x.dims();
  PADDLE_ENFORCE_EQ(input_dims.size(),
                    4,
                    phi::errors::InvalidArgument(
                        "Input should be a 4-D tensor of format [N, C, H, W] "
                        "or [N, H, W, C], but got %u.",
                        input_dims.size()));
  PADDLE_ENFORCE_GE(
      groups,
      1,
      phi::errors::InvalidArgument("groups should be larger than 0."));
  PADDLE_ENFORCE_EQ(data_format == "NCHW" || data_format == "NHWC",
                    true,
                    phi::errors::InvalidArgument(
                        "data_format must be one of "
                        "NCHW and NHWC. But recevied data_format: %s",
                        data_format));

  const bool channel_last = (data_format == "NHWC");

  if (!channel_last) {
    PADDLE_ENFORCE_EQ(input_dims[1] % groups,
                      0,
                      phi::errors::InvalidArgument(
                          "The number of groups to divide channels in [%u] "
                          "should divide the number of channel [%u]",
                          groups,
                          input_dims[1]));
  } else {
    PADDLE_ENFORCE_EQ(input_dims[3] % groups,
                      0,
                      phi::errors::InvalidArgument(
                          "The number of groups to divide channels in [%u] "
                          "should divide the number of channel [%u]",
                          groups,
                          input_dims[3]));
  }
  auto output_dims = input_dims;
  out->set_dtype(x.dtype());
  out->set_dims(output_dims);
}

5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
void CheckNumericsInferMeta(const MetaTensor& tensor,
                            const std::string& op_type,
                            const std::string& var_name,
                            const int check_nan_inf_level,
                            const int stack_height_limit,
                            const std::string& output_dir,
                            MetaTensor* stats,
                            MetaTensor* values) {
  stats->set_dtype(DataType::INT64);
  stats->set_dims(phi::make_ddim({3}));
  values->set_dtype(DataType::FLOAT32);
  values->set_dims(phi::make_ddim({3}));
}

W
wanghuancoder 已提交
5207 5208 5209 5210 5211
void StridedUnChangedInferMeta(const MetaTensor& x, MetaTensor* out) {
  out->share_meta(x);
  out->set_strides(x.strides());
}

5212
}  // namespace phi
5213

5214
PD_REGISTER_INFER_META_FN(flatten, phi::FlattenInferMeta);