infershape_utils.cc 32.0 KB
Newer Older
C
Chen Weihang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/infershape_utils.h"

17
#include <algorithm>
18 19
#include <string>

20
#include "paddle/fluid/framework/convert_utils.h"
C
Chen Weihang 已提交
21
#include "paddle/fluid/framework/framework.pb.h"
22
#include "paddle/fluid/framework/phi_utils.h"
C
Chen Weihang 已提交
23
#include "paddle/fluid/platform/enforce.h"
24
#include "paddle/phi/common/int_array.h"
25
#include "paddle/phi/common/scalar.h"
26 27 28 29 30
#include "paddle/phi/core/compat/arg_map_context.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/compat/op_utils.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/infermeta_utils.h"
31
#include "paddle/phi/core/kernel_factory.h"
32
#include "paddle/phi/core/tensor_utils.h"
C
Chen Weihang 已提交
33 34 35 36

namespace paddle {
namespace framework {

37
class InferShapeArgumentMappingContext : public phi::ArgumentMappingContext {
C
Chen Weihang 已提交
38 39 40 41 42 43 44 45 46 47 48 49
 public:
  explicit InferShapeArgumentMappingContext(const InferShapeContext& ctx)
      : ctx_(ctx) {}

  bool HasInput(const std::string& name) const override {
    return ctx_.HasInput(name);
  }

  bool HasOutput(const std::string& name) const override {
    return ctx_.HasOutput(name);
  }

50 51 52 53
  bool HasAttr(const std::string& name) const override {
    return ctx_.HasAttr(name);
  }

C
Chen Weihang 已提交
54
  paddle::any Attr(const std::string& name) const override {
55 56
    auto* attr = ctx_.Attrs().GetAttr(name);
    PADDLE_ENFORCE_NOT_NULL(
57 58 59
        attr,
        platform::errors::NotFound("Attribute (%s) should be in AttributeMap.",
                                   name));
60
    return GetAttrValue(*attr);
C
Chen Weihang 已提交
61 62 63
  }

  size_t InputSize(const std::string& name) const override {
64 65 66 67 68 69
    if (ctx_.HasInputs(name)) {
      return ctx_.Inputs(name).size();
    } else if (ctx_.HasInput(name)) {
      return 1;
    }
    return 0;
C
Chen Weihang 已提交
70 71 72 73 74 75 76
  }

  size_t OutputSize(const std::string& name) const override {
    return ctx_.Outputs(name).size();
  }

  bool IsDenseTensorInput(const std::string& name) const override {
77 78 79 80 81
    auto var_type = ctx_.GetInputVarType(name);
    return var_type == proto::VarType::LOD_TENSOR;
  }

  bool IsDenseTensorInputs(const std::string& name) const override {
C
Chen Weihang 已提交
82
    auto var_types = ctx_.GetInputsVarType(name);
83 84
    return std::all_of(var_types.begin(),
                       var_types.end(),
85 86 87
                       [](const proto::VarType::Type& type) {
                         return type == proto::VarType::LOD_TENSOR;
                       });
C
Chen Weihang 已提交
88 89
  }

Y
YuanRisheng 已提交
90 91 92 93 94 95 96 97 98
  bool IsSelectedRowsInputs(const std::string& name) const override {
    auto var_types = ctx_.GetInputsVarType(name);
    return std::all_of(var_types.begin(),
                       var_types.end(),
                       [](const proto::VarType::Type& type) {
                         return type == proto::VarType::SELECTED_ROWS;
                       });
  }

C
Chen Weihang 已提交
99
  bool IsSelectedRowsInput(const std::string& name) const override {
100 101
    auto var_type = ctx_.GetInputVarType(name);
    return var_type == proto::VarType::SELECTED_ROWS;
C
Chen Weihang 已提交
102 103
  }

104 105
  bool IsDenseTensorVectorInput(const std::string& name) const override {
    auto var_types = ctx_.GetInputsVarType(name);
106 107
    return std::all_of(var_types.begin(),
                       var_types.end(),
108 109 110
                       [](const proto::VarType::Type& type) {
                         return type == proto::VarType::LOD_TENSOR_ARRAY;
                       });
111 112
  }

113 114 115 116 117
  bool IsSparseCooTensorInput(const std::string& name) const override {
    auto var_type = ctx_.GetInputVarType(name);
    return var_type == proto::VarType::SPARSE_COO;
  }

118 119
  bool IsDenseTensorOutput(const std::string& name) const override {
    auto var_types = ctx_.GetOutputsVarType(name);
120 121
    return std::all_of(var_types.begin(),
                       var_types.end(),
122 123 124
                       [](const proto::VarType::Type& type) {
                         return type == proto::VarType::LOD_TENSOR;
                       });
125 126 127 128
  }

  bool IsSelectedRowsOutput(const std::string& name) const override {
    auto var_types = ctx_.GetOutputsVarType(name);
129 130
    return std::all_of(var_types.begin(),
                       var_types.end(),
131 132 133
                       [](const proto::VarType::Type& type) {
                         return type == proto::VarType::SELECTED_ROWS;
                       });
134 135
  }

136 137
  bool IsForInferShape() const override { return true; }

138 139
  bool IsRuntime() const override { return ctx_.IsRuntime(); }

C
Chen Weihang 已提交
140 141 142 143
 private:
  const InferShapeContext& ctx_;
};

144 145 146 147 148 149 150
static inline void ValidCheck(const phi::MetaTensor& meta_tensor) {
  PADDLE_ENFORCE_EQ(meta_tensor.initialized(),
                    true,
                    phi::errors::InvalidArgument(
                        "The current CompatMetaTensor is not initialized."));
}

151
int64_t CompatMetaTensor::numel() const {
152
  ValidCheck(*this);
153
  if (is_runtime_) {
R
Ruibiao Chen 已提交
154
    auto* var = PADDLE_GET_CONST(Variable*, var_);
155 156
    return var->Get<Tensor>().numel();
  } else {
R
Ruibiao Chen 已提交
157
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
158
    return var->ElementSize();
C
Chen Weihang 已提交
159
  }
160
}
C
Chen Weihang 已提交
161

Y
YuanRisheng 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
bool CompatMetaTensor::is_selected_rows() const {
  if (is_runtime_) {
    auto* var = PADDLE_GET_CONST(Variable*, var_);
    return var->IsType<phi::SelectedRows>();
  } else {
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
    return var->GetType() == proto::VarType::SELECTED_ROWS;
  }
}

bool CompatMetaTensor::is_dense() const {
  if (is_runtime_) {
    auto* var = PADDLE_GET_CONST(Variable*, var_);
    return var->IsType<phi::DenseTensor>();
  } else {
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
    return var->GetType() == proto::VarType::LOD_TENSOR;
  }
}

bool CompatMetaTensor::is_tensor_array() const {
  if (is_runtime_) {
    auto* var = PADDLE_GET_CONST(Variable*, var_);
    return var->IsType<framework::LoDTensorArray>();
  } else {
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
    return var->GetType() == proto::VarType::LOD_TENSOR_ARRAY;
  }
}

192
DDim CompatMetaTensor::dims() const {
193
  ValidCheck(*this);
194
  if (is_runtime_) {
R
Ruibiao Chen 已提交
195
    auto* var = PADDLE_GET_CONST(Variable*, var_);
196 197 198
    if (var->IsType<phi::DenseTensor>()) {
      return var->Get<phi::DenseTensor>().dims();
    } else if (var->IsType<phi::SelectedRows>()) {
Y
YuanRisheng 已提交
199
      return var->Get<phi::SelectedRows>().GetCompleteDims();
200 201
    } else if (var->IsType<phi::SparseCooTensor>()) {
      return var->Get<phi::SparseCooTensor>().dims();
202 203 204 205
    } else if (var->IsType<framework::LoDTensorArray>()) {
      // use tensor array size as dims
      auto& tensor_array = var->Get<framework::LoDTensorArray>();
      return phi::make_ddim({static_cast<int64_t>(tensor_array.size())});
C
Chen Weihang 已提交
206
    } else {
207 208 209
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can get dims from DenseTensor or SelectedRows or "
          "DenseTensorArray."));
C
Chen Weihang 已提交
210
    }
211
  } else {
R
Ruibiao Chen 已提交
212
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
213 214 215

    return var->GetShape().empty() ? phi::make_ddim({0UL})
                                   : phi::make_ddim(var->GetShape());
C
Chen Weihang 已提交
216
  }
217
}
C
Chen Weihang 已提交
218

219
phi::DataType CompatMetaTensor::dtype() const {
220
  ValidCheck(*this);
221
  if (is_runtime_) {
R
Ruibiao Chen 已提交
222
    auto* var = PADDLE_GET_CONST(Variable*, var_);
223 224 225 226
    if (var->IsType<phi::DenseTensor>()) {
      return var->Get<phi::DenseTensor>().dtype();
    } else if (var->IsType<phi::SelectedRows>()) {
      return var->Get<phi::SelectedRows>().dtype();
227 228
    } else if (var->IsType<phi::SparseCooTensor>()) {
      return var->Get<phi::SparseCooTensor>().dtype();
229 230 231 232
    } else if (var->IsType<framework::LoDTensorArray>()) {
      // NOTE(chenweihang): do nothing
      // Unsupported get dtype from LoDTensorArray now
      return phi::DataType::UNDEFINED;
C
Chen Weihang 已提交
233
    } else {
234 235
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can get dtype from DenseTensor or SelectedRows."));
C
Chen Weihang 已提交
236
    }
237
  } else {
R
Ruibiao Chen 已提交
238
    auto* var = PADDLE_GET_CONST(VarDesc*, var_);
239
    return paddle::framework::TransToPhiDataType(var->GetDataType());
C
Chen Weihang 已提交
240
  }
241
}
C
Chen Weihang 已提交
242

243
DataLayout CompatMetaTensor::layout() const {
244
  ValidCheck(*this);
245
  if (is_runtime_) {
R
Ruibiao Chen 已提交
246
    auto* var = PADDLE_GET_CONST(Variable*, var_);
247 248 249 250
    if (var->IsType<phi::DenseTensor>()) {
      return var->Get<phi::DenseTensor>().layout();
    } else if (var->IsType<phi::SelectedRows>()) {
      return var->Get<phi::SelectedRows>().layout();
251 252
    } else if (var->IsType<phi::SparseCooTensor>()) {
      return var->Get<phi::SparseCooTensor>().layout();
253
    } else if (var->IsType<framework::LoDTensorArray>()) {
254
      // NOTE(chenweihang): do nothing
255 256 257 258 259 260
      // Unsupported get layout from LoDTensorArray now
      return phi::DataLayout::UNDEFINED;
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can get layout from DenseTensor or "
          "SelectedRows."));
C
Chen Weihang 已提交
261
    }
262 263 264 265
  } else {
    // NOTE(chenweihang): do nothing
    // Unsupported get layout for VarDesc now
    return DataLayout::UNDEFINED;
C
Chen Weihang 已提交
266
  }
267 268 269
}

void CompatMetaTensor::set_dims(const DDim& dims) {
270
  ValidCheck(*this);
271
  if (is_runtime_) {
R
Ruibiao Chen 已提交
272
    auto* var = PADDLE_GET(Variable*, var_);
273 274 275 276
    if (var->IsType<phi::DenseTensor>()) {
      auto* tensor = var->GetMutable<phi::DenseTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->dims = dims;
    } else if (var->IsType<phi::SelectedRows>()) {
Y
YuanRisheng 已提交
277
      var->GetMutable<phi::SelectedRows>()->set_height(dims[0]);
278 279 280
    } else if (var->IsType<phi::SparseCooTensor>()) {
      auto* tensor = var->GetMutable<phi::SparseCooTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->dims = dims;
281 282 283 284 285
    } else if (var->IsType<framework::LoDTensorArray>()) {
      auto* tensor_array = var->GetMutable<framework::LoDTensorArray>();
      // Note: Here I want enforce `tensor_array->size() == 0UL`, because
      // inplace using on LoDTensorArray is dangerous, but the unittest
      // `test_list` contains this behavior
286 287
      PADDLE_ENFORCE_EQ(dims.size(),
                        1UL,
288 289 290 291
                        platform::errors::InvalidArgument(
                            "LoDTensorArray can only have one dimension."));
      // only set the array size for LoDTensorArray input
      tensor_array->resize(dims[0]);
C
Chen Weihang 已提交
292
    } else {
293 294
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can set dims from DenseTensor or SelectedRows."));
C
Chen Weihang 已提交
295
    }
296
  } else {
R
Ruibiao Chen 已提交
297
    auto* var = PADDLE_GET(VarDesc*, var_);
298
    var->SetShape(vectorize(dims));
C
Chen Weihang 已提交
299
  }
300 301 302
}

void CompatMetaTensor::set_dtype(phi::DataType dtype) {
303
  ValidCheck(*this);
304
  if (is_runtime_) {
R
Ruibiao Chen 已提交
305
    auto* var = PADDLE_GET(Variable*, var_);
306 307 308 309 310 311
    if (var->IsType<phi::DenseTensor>()) {
      auto* tensor = var->GetMutable<phi::DenseTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->dtype = dtype;
    } else if (var->IsType<phi::SelectedRows>()) {
      auto* tensor = var->GetMutable<phi::SelectedRows>()->mutable_value();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->dtype = dtype;
312 313 314
    } else if (var->IsType<phi::SparseCooTensor>()) {
      auto* tensor = var->GetMutable<phi::SparseCooTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->dtype = dtype;
315 316 317
    } else if (var->IsType<framework::LoDTensorArray>()) {
      // NOTE(chenweihang): do nothing
      // Unsupported set dtype for LoDTensorArray now
C
Chen Weihang 已提交
318
    } else {
319 320
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can set dtype from DenseTensor or SelectedRows."));
C
Chen Weihang 已提交
321
    }
322
  } else {
R
Ruibiao Chen 已提交
323
    auto* var = PADDLE_GET(VarDesc*, var_);
324
    var->SetDataType(paddle::framework::TransToProtoVarType(dtype));
C
Chen Weihang 已提交
325
  }
326 327 328
}

void CompatMetaTensor::set_layout(DataLayout layout) {
329
  ValidCheck(*this);
330
  if (is_runtime_) {
R
Ruibiao Chen 已提交
331
    auto* var = PADDLE_GET(Variable*, var_);
332 333 334 335 336 337
    if (var->IsType<phi::DenseTensor>()) {
      auto* tensor = var->GetMutable<phi::DenseTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->layout = layout;
    } else if (var->IsType<phi::SelectedRows>()) {
      auto* tensor = var->GetMutable<phi::SelectedRows>()->mutable_value();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->layout = layout;
338 339 340
    } else if (var->IsType<phi::SparseCooTensor>()) {
      auto* tensor = var->GetMutable<phi::SparseCooTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->layout = layout;
341
    } else if (var->IsType<framework::LoDTensorArray>()) {
342
      // NOTE(chenweihang): do nothing
343 344 345 346 347
      // Unsupported set dtype for LoDTensorArray now
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Currently, only can set layout from DenseTensor or "
          "SelectedRows."));
C
Chen Weihang 已提交
348
    }
349 350 351
  } else {
    // NOTE(chenweihang): do nothing
    // Unsupported set layout for VarDesc now
C
Chen Weihang 已提交
352
  }
353 354 355
}

void CompatMetaTensor::share_lod(const MetaTensor& meta_tensor) {
356 357
  ValidCheck(*this);
  ValidCheck(meta_tensor);
358
  if (is_runtime_) {
R
Ruibiao Chen 已提交
359
    auto* var = PADDLE_GET(Variable*, var_);
Y
YuanRisheng 已提交
360
    if (var->IsType<phi::DenseTensor>() && meta_tensor.is_dense()) {
361 362 363
      auto* tensor = var->GetMutable<phi::DenseTensor>();
      phi::DenseTensorUtils::GetMutableMeta(tensor)->lod =
          static_cast<const CompatMetaTensor&>(meta_tensor).GetRuntimeLoD();
C
Chen Weihang 已提交
364
    } else {
365 366
      // NOTE(chenweihang): do nothing
      // only LoDTensor need to share lod
C
Chen Weihang 已提交
367
    }
368
  } else {
R
Ruibiao Chen 已提交
369
    auto* var = PADDLE_GET(VarDesc*, var_);
Y
YuanRisheng 已提交
370 371 372 373
    if (!meta_tensor.is_dense() && !meta_tensor.is_tensor_array()) {
      VLOG(3) << "input metatensor is not LoDTensor or LoDTensorArray.";
      return;
    }
374 375
    var->SetLoDLevel(
        static_cast<const CompatMetaTensor&>(meta_tensor).GetCompileTimeLoD());
C
Chen Weihang 已提交
376
  }
377 378 379
}

void CompatMetaTensor::share_dims(const MetaTensor& meta_tensor) {
380 381
  ValidCheck(*this);
  ValidCheck(meta_tensor);
382 383
  set_dims(meta_tensor.dims());
  if (is_runtime_) {
R
Ruibiao Chen 已提交
384
    auto* var = PADDLE_GET(Variable*, var_);
385 386 387 388 389 390
    if (var->IsType<phi::SelectedRows>()) {
      auto* selected_rows = var->GetMutable<phi::SelectedRows>();
      auto& input_selected_rows =
          static_cast<const CompatMetaTensor&>(meta_tensor).GetSelectedRows();
      selected_rows->set_rows(input_selected_rows.rows());
      selected_rows->set_height(input_selected_rows.height());
391
    }
392
  }
393 394 395 396 397 398 399 400 401
}

void CompatMetaTensor::share_meta(const MetaTensor& meta_tensor) {
  share_dims(meta_tensor);
  set_dtype(meta_tensor.dtype());
  set_layout(meta_tensor.layout());
  // special case: share lod of LoDTensor
  share_lod(meta_tensor);
}
C
Chen Weihang 已提交
402

403 404 405 406 407 408 409 410 411 412 413 414
void CompatInferMetaContext::EmplaceBackInput(CompatMetaTensor input) {
  int index = compat_inputs_.size();
  compat_inputs_.emplace_back(std::move(input));
  input_range_.emplace_back(std::pair<int, int>(index, index + 1));
}
void CompatInferMetaContext::EmplaceBackOutput(CompatMetaTensor output) {
  int index = compat_outputs_.size();
  compat_outputs_.emplace_back(std::move(output));
  output_range_.emplace_back(std::pair<int, int>(index, index + 1));
}

void CompatInferMetaContext::EmplaceBackInputs(
C
Chen Weihang 已提交
415
    paddle::small_vector<CompatMetaTensor, phi::kInputSmallVectorSize> inputs) {
416 417 418 419 420 421 422 423
  int index = compat_inputs_.size();
  input_range_.emplace_back(std::pair<int, int>(index, index + inputs.size()));
  compat_inputs_.insert(compat_inputs_.end(),
                        std::make_move_iterator(inputs.begin()),
                        std::make_move_iterator(inputs.end()));
}

void CompatInferMetaContext::EmplaceBackOutputs(
C
Chen Weihang 已提交
424
    paddle::small_vector<CompatMetaTensor, phi::kOutputSmallVectorSize>
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
        outputs) {
  int index = compat_outputs_.size();
  output_range_.emplace_back(
      std::pair<int, int>(index, index + outputs.size()));
  compat_outputs_.insert(compat_outputs_.end(),
                         std::make_move_iterator(outputs.begin()),
                         std::make_move_iterator(outputs.end()));
}

const phi::MetaTensor& CompatInferMetaContext::InputAt(size_t idx) const {
  return compat_inputs_.at(idx);
}

std::vector<const phi::MetaTensor*> CompatInferMetaContext::InputsBetween(
    size_t start, size_t end) const {
  std::vector<const phi::MetaTensor*> result;
  result.reserve(end - start);

  for (size_t i = start; i < end; ++i) {
    auto& in = compat_inputs_.at(i);
    result.emplace_back(in.initialized() ? &in : nullptr);
  }

  return result;
}

451
paddle::optional<std::vector<const phi::MetaTensor*>>
452 453 454 455 456 457 458 459 460 461 462 463
CompatInferMetaContext::OptionalInputsBetween(size_t start, size_t end) const {
  const auto& first = compat_inputs_.at(start);

  if (first.initialized()) {
    std::vector<const phi::MetaTensor*> result;
    result.reserve(end - start);

    for (size_t i = start; i < end; ++i) {
      auto& in = compat_inputs_.at(i);
      result.emplace_back(in.initialized() ? &in : nullptr);
    }

464 465
    return paddle::optional<std::vector<const phi::MetaTensor*>>(
        std::move(result));
466
  }
467
  return paddle::none;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
}

phi::MetaTensor* CompatInferMetaContext::MutableOutputAt(size_t idx) {
  auto& out = compat_outputs_.at(idx);
  return out.initialized() ? &out : nullptr;
}

std::vector<phi::MetaTensor*> CompatInferMetaContext::MutableOutputBetween(
    size_t start, size_t end) {
  std::vector<phi::MetaTensor*> result;
  result.reserve(end - start);
  for (size_t i = start; i < end; ++i) {
    auto& out = compat_outputs_.at(i);
    result.emplace_back(out.initialized() ? &out : nullptr);
  }
  return result;
}

CompatInferMetaContext BuildInferMetaContext(InferShapeContext* ctx,
                                             const std::string& op_type) {
488
  // 1. get kernel args
489
  auto* arg_map_fn = ctx->GetPhiArgumentMappingFn();
490
  InferShapeArgumentMappingContext arg_map_context(*ctx);
491 492 493
  phi::KernelSignature signature = arg_map_fn
                                       ? (*arg_map_fn)(arg_map_context)
                                       : *ctx->GetPhiDefaultKernelSignature();
494 495 496
  VLOG(3) << "BuildInferMetaContext: op kernel signature - " << signature;

  // 2. build infermeta context
497
  CompatInferMetaContext infer_meta_context(
F
From00 已提交
498
      {ctx->IsRuntime(), ctx->IsRunMKLDNNKernel()});
499

500 501 502
  const auto& input_names = signature.input_names;
  const auto& attr_names = signature.attr_names;
  const auto& output_names = signature.output_names;
503

504 505 506
  const auto& args_def =
      phi::KernelFactory::Instance().GetFirstKernelArgsDef(signature.name);
  const auto& attr_defs = args_def.attribute_defs();
507

508
  for (auto& in_name : input_names) {
509
    if (ctx->HasInputs(in_name)) {
510
      auto input_var = std::move(ctx->GetInputVarPtrs(in_name));
511 512
      if (input_var.size() == 1) {
        infer_meta_context.EmplaceBackInput(
513
            std::move(CompatMetaTensor(input_var[0], ctx->IsRuntime())));
514
      } else {
C
Chen Weihang 已提交
515
        paddle::small_vector<CompatMetaTensor, phi::kInputSmallVectorSize>
516
            inputs;
517
        for (const auto& in : input_var) {
518 519
          inputs.emplace_back(
              std::move(CompatMetaTensor(in, ctx->IsRuntime())));
520 521 522
        }
        infer_meta_context.EmplaceBackInputs(std::move(inputs));
      }
523
    } else {
524 525 526
      // Note: Because the input of InferMetaFn is const MetaTensor&,
      // so when we prepare input MetaTensor by InferMetaContext->InputAt(),
      // we need to return a const reference of empty MetaTensor
527 528
      infer_meta_context.EmplaceBackInput(
          std::move(CompatMetaTensor(ctx->IsRuntime())));
529
    }
530
  }
531

532 533
  VLOG(6) << "BuildInferMetaContext: Done inputs";

534
  auto attr_reader = ctx->Attrs();
535
  for (size_t i = 0; i < attr_names.size(); ++i) {
536
    auto& attr_name = attr_names[i];
537
    auto* attr_ptr = attr_reader.GetAttr(attr_name);
538 539 540
    bool is_attr_var = attr_ptr != nullptr && HasAttrVar(*attr_ptr);
    VLOG(6) << "BuildInferMetaContext: " << attr_name << ": "
            << attr_defs[i].type_index << ", is_attr_var: " << is_attr_var;
541 542
    switch (attr_defs[i].type_index) {
      case phi::AttributeType::SCALAR:
543
        if (attr_ptr && !is_attr_var) {
544 545 546 547
          auto& attr = *attr_ptr;
          switch (AttrTypeID(attr)) {
            case framework::proto::AttrType::FLOAT:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
548
                  phi::Scalar(PADDLE_GET_CONST(float, attr)));
549
              break;
550 551 552 553
            case framework::proto::AttrType::FLOAT64:
              infer_meta_context.EmplaceBackAttr(
                  phi::Scalar(PADDLE_GET_CONST(double, attr)));
              break;
554 555
            case framework::proto::AttrType::INT:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
556
                  phi::Scalar(PADDLE_GET_CONST(int, attr)));
557
              break;
558 559 560 561
            case framework::proto::AttrType::LONG:
              infer_meta_context.EmplaceBackAttr(
                  phi::Scalar(PADDLE_GET_CONST(int64_t, attr)));
              break;
562 563
            case framework::proto::AttrType::STRING:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
564
                  phi::Scalar(PADDLE_GET_CONST(std::string, attr)));
565
              break;
566 567 568 569
            case framework::proto::AttrType::BOOLEAN:
              infer_meta_context.EmplaceBackAttr(
                  phi::Scalar(PADDLE_GET_CONST(bool, attr)));
              break;
570 571 572 573 574
            default:
              PADDLE_THROW(platform::errors::Unimplemented(
                  "Unsupported cast op attribute `%s` to Scalar when construct "
                  "InferMetaContext.",
                  attr_name));
575
          }
576 577 578 579
        } else if (ctx->HasInput(attr_name)) {
          auto infershape_input = std::move(ctx->GetInputVarPtrs(attr_name));
          if (infershape_input.size() == 1) {
            if (ctx->IsRuntime()) {
R
Ruibiao Chen 已提交
580
              Variable* var = PADDLE_GET_CONST(Variable*, infershape_input[0]);
581 582 583 584 585 586 587
              infer_meta_context.EmplaceBackAttr(
                  std::move(experimental::MakePhiScalarFromVar(*var)));
            } else {
              phi::Scalar tensor_scalar(-1);
              tensor_scalar.SetFromTensor(true);
              infer_meta_context.EmplaceBackAttr(std::move(tensor_scalar));
            }
588
          } else {
589 590 591
            PADDLE_THROW(platform::errors::InvalidArgument(
                "Invalid input.size() when cast op attribute `%s` to Scalar, "
                "expected 1, but actually is %d .",
592 593
                attr_name,
                infershape_input.size()));
594 595
          }
        } else {
596 597 598 599 600
          // do nothing, skip current attr
        }
        break;
      case phi::AttributeType::INT_ARRAY:
        // When attr is a vector_tensor or tensor, transform it to IntArray
601
        if (attr_ptr && !is_attr_var) {
602 603 604 605
          auto& attr = *attr_ptr;
          switch (AttrTypeID(attr)) {
            case framework::proto::AttrType::INTS:
              infer_meta_context.EmplaceBackAttr(std::move(
R
Ruibiao Chen 已提交
606
                  phi::IntArray(PADDLE_GET_CONST(std::vector<int32_t>, attr))));
607 608 609
              break;
            case framework::proto::AttrType::LONGS:
              infer_meta_context.EmplaceBackAttr(std::move(
R
Ruibiao Chen 已提交
610
                  phi::IntArray(PADDLE_GET_CONST(std::vector<int64_t>, attr))));
611 612 613
              break;
            case framework::proto::AttrType::INT:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
614
                  phi::IntArray({PADDLE_GET_CONST(int, attr)}));
615 616 617 618 619 620
              break;
            default:
              PADDLE_THROW(platform::errors::Unimplemented(
                  "Unsupported cast op attribute `%s` to IntArray when "
                  "construct InferMetaContext.",
                  attr_name));
621
          }
622 623 624 625 626 627 628 629
        } else if (ctx->HasInputs(attr_name) || ctx->HasInput(attr_name)) {
          auto infershape_inputs = std::move(ctx->GetInputVarPtrs(attr_name));
          if (ctx->IsRuntime()) {
            // If is in runtime, we will get tensor's value for IntArray
            // and push it into attrs
            std::vector<Variable*> vars;
            vars.reserve(infershape_inputs.size());
            for (size_t i = 0; i < infershape_inputs.size(); i++) {
R
Ruibiao Chen 已提交
630
              vars.push_back(PADDLE_GET_CONST(Variable*, infershape_inputs[i]));
631
            }
632 633 634 635 636 637
            if (infershape_inputs.size() != 1) {
              infer_meta_context.EmplaceBackAttr(
                  std::move(experimental::MakePhiIntArrayFromVarList(vars)));
            } else {
              infer_meta_context.EmplaceBackAttr(
                  std::move(experimental::MakePhiIntArrayFromVar(*vars[0])));
638
            }
639
          } else {
640 641 642 643
            // If is not in runtime, we will set default value(-1) for IntArray
            std::vector<VarDesc*> vars;
            vars.reserve(infershape_inputs.size());
            for (size_t i = 0; i < infershape_inputs.size(); ++i) {
R
Ruibiao Chen 已提交
644
              vars.push_back(PADDLE_GET_CONST(VarDesc*, infershape_inputs[i]));
645 646 647 648 649 650 651 652 653 654 655
            }

            int64_t num_ele = 0;
            if (vars.size() == 1) {
              num_ele = 1;
              const auto& tensor_dims = vars[0]->GetShape();
              for (size_t i = 0; i < tensor_dims.size(); ++i) {
                num_ele *= tensor_dims[i];
              }

              if (num_ele <= 0) {
656
                num_ele = tensor_dims.size();
657 658 659 660 661 662 663 664
              }

            } else {
              num_ele = vars.size();
            }
            phi::IntArray tensor_attr(std::vector<int32_t>(num_ele, -1));
            tensor_attr.SetFromTensor(true);
            infer_meta_context.EmplaceBackAttr(std::move(tensor_attr));
665 666
          }
        } else {
667
          // do nothing, skip current attr
668
        }
669 670 671 672 673 674
        break;
      case phi::AttributeType::SCALARS:
        if (attr_ptr) {
          auto& attr = *attr_ptr;
          switch (AttrTypeID(attr)) {
            case framework::proto::AttrType::INTS: {
R
Ruibiao Chen 已提交
675
              const auto& vec = PADDLE_GET_CONST(std::vector<int32_t>, attr);
676 677 678 679 680 681 682 683
              std::vector<phi::Scalar> scalar_list;
              scalar_list.reserve(vec.size());
              for (const auto& val : vec) {
                scalar_list.emplace_back(val);
              }
              infer_meta_context.EmplaceBackAttr(std::move(scalar_list));
            } break;
            case framework::proto::AttrType::LONGS: {
R
Ruibiao Chen 已提交
684
              const auto& vec = PADDLE_GET_CONST(std::vector<int64_t>, attr);
685 686 687 688 689 690 691 692
              std::vector<phi::Scalar> scalar_list;
              scalar_list.reserve(vec.size());
              for (const auto& val : vec) {
                scalar_list.emplace_back(val);
              }
              infer_meta_context.EmplaceBackAttr(std::move(scalar_list));
            } break;
            case framework::proto::AttrType::FLOATS: {
R
Ruibiao Chen 已提交
693
              const auto& vec = PADDLE_GET_CONST(std::vector<float>, attr);
694 695 696 697 698 699 700 701
              std::vector<phi::Scalar> scalar_list;
              scalar_list.reserve(vec.size());
              for (const auto& val : vec) {
                scalar_list.emplace_back(val);
              }
              infer_meta_context.EmplaceBackAttr(std::move(scalar_list));
            } break;
            case framework::proto::AttrType::FLOAT64S: {
R
Ruibiao Chen 已提交
702
              const auto& vec = PADDLE_GET_CONST(std::vector<double>, attr);
703 704 705 706 707 708 709 710 711 712 713 714
              std::vector<phi::Scalar> scalar_list;
              scalar_list.reserve(vec.size());
              for (const auto& val : vec) {
                scalar_list.emplace_back(val);
              }
              infer_meta_context.EmplaceBackAttr(std::move(scalar_list));
            } break;
            default:
              PADDLE_THROW(platform::errors::Unimplemented(
                  "Unsupported cast op attribute `%s` to vector<Scalar> when "
                  "construct KernelContext.",
                  attr_names[i]));
715 716
          }
        } else {
717
          // do nothing, skip current attr
718
        }
719 720 721 722 723 724
        break;
      default:
        if (attr_ptr) {
          auto& attr = *attr_ptr;
          switch (attr_defs[i].type_index) {
            case phi::AttributeType::FLOAT32:
R
Ruibiao Chen 已提交
725
              infer_meta_context.EmplaceBackAttr(PADDLE_GET_CONST(float, attr));
726
              break;
727 728 729 730
            case phi::AttributeType::FLOAT64:
              infer_meta_context.EmplaceBackAttr(
                  PADDLE_GET_CONST(double, attr));
              break;
731
            case phi::AttributeType::INT32:
R
Ruibiao Chen 已提交
732
              infer_meta_context.EmplaceBackAttr(PADDLE_GET_CONST(int, attr));
733 734
              break;
            case phi::AttributeType::BOOL:
R
Ruibiao Chen 已提交
735
              infer_meta_context.EmplaceBackAttr(PADDLE_GET_CONST(bool, attr));
736 737 738
              break;
            case phi::AttributeType::INT64:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
739
                  PADDLE_GET_CONST(int64_t, attr));
740 741 742
              break;
            case phi::AttributeType::INT32S:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
743
                  PADDLE_GET_CONST(std::vector<int>, attr));
744 745 746 747
              break;
            case phi::AttributeType::DATA_TYPE: {
              auto data_type = paddle::framework::TransToPhiDataType(
                  static_cast<framework::proto::VarType::Type>(
R
Ruibiao Chen 已提交
748
                      PADDLE_GET_CONST(int, attr)));
749 750 751 752
              infer_meta_context.EmplaceBackAttr(data_type);
            } break;
            case phi::AttributeType::STRING:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
753
                  PADDLE_GET_CONST(std::string, attr));
754 755 756 757 758
              break;
            case phi::AttributeType::INT64S:
              switch (AttrTypeID(attr)) {
                case framework::proto::AttrType::LONGS:
                  infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
759
                      PADDLE_GET_CONST(std::vector<int64_t>, attr));
760 761 762
                  break;
                case framework::proto::AttrType::INTS: {
                  const auto& vector_int_attr =
R
Ruibiao Chen 已提交
763
                      PADDLE_GET_CONST(std::vector<int>, attr);
764 765 766 767 768 769 770 771 772 773 774 775 776 777
                  const std::vector<int64_t> vector_int64_attr(
                      vector_int_attr.begin(), vector_int_attr.end());
                  infer_meta_context.EmplaceBackAttr(vector_int64_attr);
                } break;
                default:
                  PADDLE_THROW(platform::errors::Unimplemented(
                      "Unsupported cast op attribute `%s` to vector<int64_t> "
                      "when "
                      "construct KernelContext.",
                      attr_names[i]));
              }
              break;
            case phi::AttributeType::FLOAT32S:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
778
                  PADDLE_GET_CONST(std::vector<float>, attr));
779 780 781
              break;
            case phi::AttributeType::STRINGS:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
782
                  PADDLE_GET_CONST(std::vector<std::string>, attr));
783 784 785
              break;
            case phi::AttributeType::BOOLS:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
786
                  PADDLE_GET_CONST(std::vector<bool>, attr));
787 788 789
              break;
            case phi::AttributeType::FLOAT64S:
              infer_meta_context.EmplaceBackAttr(
R
Ruibiao Chen 已提交
790
                  PADDLE_GET_CONST(std::vector<double>, attr));
791 792 793 794 795 796 797
              break;
            default:
              PADDLE_THROW(platform::errors::Unimplemented(
                  "Unsupported cast op attribute `%s` when construct "
                  "KernelContext in dygraph.",
                  attr_names[i]));
          }
H
hong 已提交
798
        } else {
799
          // do nothing, skip currnet attr
H
hong 已提交
800
        }
801 802 803
    }
  }

804 805
  VLOG(6) << "BuildInferMetaContext: Done attrs";

806
  for (auto& out_name : output_names) {
807
    if (ctx->HasOutputs(out_name, true)) {
808
      auto output_var = std::move(ctx->GetOutputVarPtrs(out_name));
809
      if (output_var.size() == 1) {
810 811
        infer_meta_context.EmplaceBackOutput(
            std::move(CompatMetaTensor(output_var[0], ctx->IsRuntime())));
812
      } else {
C
Chen Weihang 已提交
813
        paddle::small_vector<CompatMetaTensor, phi::kOutputSmallVectorSize>
814
            outputs;
815
        for (const auto& out : output_var) {
816
          if (ctx->IsRuntime()) {
R
Ruibiao Chen 已提交
817
            if (PADDLE_GET_CONST(Variable*, out)) {
818
              outputs.emplace_back(
819
                  std::move(CompatMetaTensor(out, ctx->IsRuntime())));
820 821
              continue;
            }
R
Ruibiao Chen 已提交
822
          } else if (PADDLE_GET_CONST(VarDesc*, out)) {
823
            outputs.emplace_back(
824
                std::move(CompatMetaTensor(out, ctx->IsRuntime())));
825 826
            continue;
          }
827
          outputs.emplace_back(std::move(CompatMetaTensor(ctx->IsRuntime())));
828 829 830 831
        }
        infer_meta_context.EmplaceBackOutputs(std::move(outputs));
      }
    } else {
832 833
      infer_meta_context.EmplaceBackOutput(
          std::move(CompatMetaTensor(ctx->IsRuntime())));
834
    }
835 836
  }

837 838
  VLOG(6) << "BuildInferMetaContext: Done outputs";

839 840 841
  return infer_meta_context;
}

C
Chen Weihang 已提交
842 843
}  // namespace framework
}  // namespace paddle