infershape_utils.cc 13.2 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 18
#include <string>

19
#include "paddle/fluid/framework/convert_utils.h"
C
Chen Weihang 已提交
20
#include "paddle/fluid/framework/framework.pb.h"
21
#include "paddle/fluid/framework/pten_utils.h"
C
Chen Weihang 已提交
22 23
#include "paddle/fluid/platform/enforce.h"
#include "paddle/pten/core/compat/arg_map_context.h"
24
#include "paddle/pten/core/compat/convert_utils.h"
25
#include "paddle/pten/core/compat/op_utils.h"
C
Chen Weihang 已提交
26
#include "paddle/pten/core/dense_tensor.h"
27
#include "paddle/pten/core/infermeta_utils.h"
C
Chen Weihang 已提交
28
#include "paddle/pten/core/meta_tensor.h"
29
#include "paddle/pten/core/tensor_utils.h"
C
Chen Weihang 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

namespace paddle {
namespace framework {

class InferShapeArgumentMappingContext : public pten::ArgumentMappingContext {
 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);
  }

47 48 49 50
  bool HasAttr(const std::string& name) const override {
    return ctx_.HasAttr(name);
  }

C
Chen Weihang 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  paddle::any Attr(const std::string& name) const override {
    auto& attr = ctx_.Attrs().GetAttr(name);
    return GetAttrValue(attr);
  }

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

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

  bool IsDenseTensorInput(const std::string& name) const override {
    auto var_types = ctx_.GetInputsVarType(name);
    return var_types[0] == proto::VarType::LOD_TENSOR;
  }

  bool IsSelectedRowsInput(const std::string& name) const override {
    auto var_types = ctx_.GetInputsVarType(name);
    return var_types[0] == proto::VarType::SELECTED_ROWS;
  }

74 75 76 77 78 79 80 81 82 83
  bool IsDenseTensorOutput(const std::string& name) const override {
    auto var_types = ctx_.GetOutputsVarType(name);
    return var_types[0] == proto::VarType::LOD_TENSOR;
  }

  bool IsSelectedRowsOutput(const std::string& name) const override {
    auto var_types = ctx_.GetOutputsVarType(name);
    return var_types[0] == proto::VarType::SELECTED_ROWS;
  }

C
Chen Weihang 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
 private:
  const InferShapeContext& ctx_;
};

// TODO(chenweihang): Support TensorArray later
class CompatMetaTensor : public pten::MetaTensor {
 public:
  CompatMetaTensor(InferShapeVarPtr var, bool is_runtime)
      : var_(std::move(var)), is_runtime_(is_runtime) {}

  CompatMetaTensor() = default;
  CompatMetaTensor(const CompatMetaTensor&) = default;
  CompatMetaTensor(CompatMetaTensor&&) = default;
  CompatMetaTensor& operator=(const CompatMetaTensor&) = delete;
  CompatMetaTensor& operator=(CompatMetaTensor&&) = delete;

  int64_t numel() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
      return var->Get<Tensor>().numel();
    } else {
      auto* var = BOOST_GET_CONST(VarDesc*, var_);
      return var->ElementSize();
    }
  }

  DDim dims() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
113 114 115 116 117 118 119 120
      if (var->IsType<pten::DenseTensor>()) {
        return var->Get<pten::DenseTensor>().dims();
      } else if (var->IsType<pten::SelectedRows>()) {
        return var->Get<pten::SelectedRows>().dims();
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "Currently, only can get dims from DenseTensor or SelectedRows."));
      }
C
Chen Weihang 已提交
121 122
    } else {
      auto* var = BOOST_GET_CONST(VarDesc*, var_);
123
      return pten::make_ddim(var->GetShape());
C
Chen Weihang 已提交
124 125 126 127 128 129
    }
  }

  pten::DataType dtype() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
130 131 132 133 134 135 136 137
      if (var->IsType<pten::DenseTensor>()) {
        return var->Get<pten::DenseTensor>().dtype();
      } else if (var->IsType<pten::SelectedRows>()) {
        return var->Get<pten::SelectedRows>().dtype();
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "Currently, only can get dtype from DenseTensor or SelectedRows."));
      }
C
Chen Weihang 已提交
138 139
    } else {
      auto* var = BOOST_GET_CONST(VarDesc*, var_);
140
      return paddle::framework::TransToPtenDataType(var->GetDataType());
C
Chen Weihang 已提交
141 142 143 144 145 146 147 148
    }
  }

  DataLayout layout() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
      return var->Get<LoDTensor>().layout();
    } else {
149 150 151
      // NOTE(chenweihang): do nothing
      // Unsupported get layout for VarDesc now
      return DataLayout::UNDEFINED;
C
Chen Weihang 已提交
152 153 154 155 156 157
    }
  }

  void set_dims(const DDim& dims) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
158 159 160 161 162 163 164 165 166 167
      if (var->IsType<pten::DenseTensor>()) {
        auto* tensor = var->GetMutable<pten::DenseTensor>();
        pten::DenseTensorUtils::GetMutableMeta(tensor)->dims = dims;
      } else if (var->IsType<pten::SelectedRows>()) {
        auto* tensor = var->GetMutable<pten::SelectedRows>()->mutable_value();
        pten::DenseTensorUtils::GetMutableMeta(tensor)->dims = dims;
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "Currently, only can set dims from DenseTensor or SelectedRows."));
      }
C
Chen Weihang 已提交
168 169 170 171 172 173 174 175 176
    } else {
      auto* var = BOOST_GET(VarDesc*, var_);
      var->SetShape(vectorize(dims));
    }
  }

  void set_dtype(pten::DataType dtype) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
177 178 179 180 181 182 183 184 185 186
      if (var->IsType<pten::DenseTensor>()) {
        auto* tensor = var->GetMutable<pten::DenseTensor>();
        pten::DenseTensorUtils::GetMutableMeta(tensor)->dtype = dtype;
      } else if (var->IsType<pten::SelectedRows>()) {
        auto* tensor = var->GetMutable<pten::SelectedRows>()->mutable_value();
        pten::DenseTensorUtils::GetMutableMeta(tensor)->dtype = dtype;
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "Currently, only can set dtype from DenseTensor or SelectedRows."));
      }
C
Chen Weihang 已提交
187 188
    } else {
      auto* var = BOOST_GET(VarDesc*, var_);
189
      var->SetDataType(paddle::framework::TransToProtoVarType(dtype));
C
Chen Weihang 已提交
190 191 192 193 194 195 196
    }
  }

  void set_layout(DataLayout layout) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
197
      pten::DenseTensorUtils::GetMutableMeta(
C
Chen Weihang 已提交
198 199 200
          static_cast<pten::DenseTensor*>(tensor))
          ->layout = layout;
    } else {
201 202
      // NOTE(chenweihang): do nothing
      // Unsupported set layout for VarDesc now
C
Chen Weihang 已提交
203 204 205 206 207 208
    }
  }

  void share_lod(const MetaTensor& meta_tensor) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
209 210 211 212 213 214 215 216
      if (var->IsType<pten::DenseTensor>()) {
        auto* tensor = var->GetMutable<pten::DenseTensor>();
        pten::DenseTensorUtils::GetMutableMeta(tensor)->lod =
            static_cast<const CompatMetaTensor&>(meta_tensor).GetRuntimeLoD();
      } else {
        // NOTE(chenweihang): do nothing
        // only LoDTensor need to share lod
      }
C
Chen Weihang 已提交
217 218 219 220 221 222 223
    } else {
      auto* var = BOOST_GET(VarDesc*, var_);
      var->SetLoDLevel(static_cast<const CompatMetaTensor&>(meta_tensor)
                           .GetCompileTimeLoD());
    }
  }

224 225 226 227 228
  void share_meta(const MetaTensor& meta_tensor) override {
    set_dims(meta_tensor.dims());
    set_dtype(meta_tensor.dtype());
    // VarDesc doesn't contains layout, so we cannot share layout
    // set_layout(meta_tensor.layout());
229 230

    // special case 1: share lod of LoDTensor
231
    share_lod(meta_tensor);
232 233 234 235 236 237 238 239 240 241 242 243

    // special case 2: share height and rows of SelectedRows in runtime
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
      if (var->IsType<pten::SelectedRows>()) {
        auto* selected_rows = var->GetMutable<pten::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());
      }
    }
244 245
  }

C
Chen Weihang 已提交
246 247 248 249 250
 private:
  const LoD& GetRuntimeLoD() const {
    auto* var = BOOST_GET_CONST(Variable*, var_);
    return var->Get<LoDTensor>().lod();
  }
251

C
Chen Weihang 已提交
252 253 254 255 256
  int32_t GetCompileTimeLoD() const {
    auto* var = BOOST_GET_CONST(VarDesc*, var_);
    return var->GetLoDLevel();
  }

257 258 259 260 261 262 263 264 265 266 267
  const pten::SelectedRows& GetSelectedRows() const {
    PADDLE_ENFORCE_EQ(is_runtime_, true,
                      platform::errors::Unavailable(
                          "Only can get Tensor from MetaTensor in rumtime."));
    auto* var = BOOST_GET_CONST(Variable*, var_);
    PADDLE_ENFORCE_EQ(var->IsType<pten::SelectedRows>(), true,
                      platform::errors::Unavailable(
                          "The Tensor in MetaTensor is not SelectedRows."));
    return var->Get<pten::SelectedRows>();
  }

C
Chen Weihang 已提交
268 269 270 271
  InferShapeVarPtr var_;
  bool is_runtime_;
};

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
pten::InferMetaContext BuildInferMetaContext(InferShapeContext* ctx,
                                             const std::string& op_type) {
  // 1. get kernel args
  InitDefaultKernelSignatureMap();
  auto arg_map_fn = pten::OpUtilsMap::Instance().GetArgumentMappingFn(op_type);
  PADDLE_ENFORCE_NOT_NULL(
      arg_map_fn, platform::errors::NotFound(
                      "The ArgumentMappingFn of %s op is not found.", op_type));
  InferShapeArgumentMappingContext arg_map_context(*ctx);
  auto signature = arg_map_fn(arg_map_context);
  VLOG(3) << "BuildInferMetaContext: op kernel signature - " << signature;

  // 2. build infermeta context
  pten::InferMetaContext infer_meta_context(ctx->IsRuntime());

  auto& input_names = std::get<0>(signature.args);
288
  auto& attr_names = std::get<1>(signature.args);
289 290
  auto& output_names = std::get<2>(signature.args);

291
  // TODO(chenweihang): support multiple inputs and outputs later
292 293
  pten::InferMetaContext infer_mete_context;
  for (auto& in_name : input_names) {
294 295 296 297 298 299
    if (ctx->HasInput(in_name)) {
      infer_meta_context.EmplaceBackInput(std::make_shared<CompatMetaTensor>(
          ctx->GetInputVarPtrs(in_name)[0], ctx->IsRuntime()));
    } else {
      infer_meta_context.EmplaceBackInput({nullptr});
    }
300
  }
301 302 303 304 305 306 307

  auto attr_reader = ctx->Attrs();
  for (auto& attr_name : attr_names) {
    if (ctx->HasAttr(attr_name)) {
      auto& attr = attr_reader.GetAttr(attr_name);
      if (std::type_index(attr.type()) == std::type_index(typeid(bool))) {
        infer_meta_context.EmplaceBackAttr(BOOST_GET_CONST(bool, attr));
308 309 310 311 312
      } else if (std::type_index(attr.type()) == std::type_index(typeid(int))) {
        infer_meta_context.EmplaceBackAttr(BOOST_GET_CONST(int, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(int64_t))) {
        infer_meta_context.EmplaceBackAttr(BOOST_GET_CONST(int64_t, attr));
313 314 315
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(float))) {
        infer_meta_context.EmplaceBackAttr(BOOST_GET_CONST(float, attr));
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::string))) {
        infer_meta_context.EmplaceBackAttr(BOOST_GET_CONST(std::string, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<bool>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<bool>, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<int>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<int>, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<int64_t>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<int64_t>, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<float>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<float>, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<double>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<double>, attr));
      } else if (std::type_index(attr.type()) ==
                 std::type_index(typeid(std::vector<std::string>))) {
        infer_meta_context.EmplaceBackAttr(
            BOOST_GET_CONST(std::vector<std::string>, attr));
343
      } else {
344 345 346
        PADDLE_THROW(platform::errors::Unimplemented(
            "Unsupported attribute type is received when call "
            "InferShapeFunctor."));
347 348 349 350 351 352
      }
    } else {
      // do nothing
    }
  }

353
  for (auto& out_name : output_names) {
354 355 356 357 358 359
    if (ctx->HasOutput(out_name)) {
      infer_meta_context.EmplaceBackOutput(std::make_shared<CompatMetaTensor>(
          ctx->GetOutputVarPtrs(out_name)[0], ctx->IsRuntime()));
    } else {
      infer_meta_context.EmplaceBackOutput({nullptr});
    }
360 361 362 363 364
  }

  return infer_meta_context;
}

C
Chen Weihang 已提交
365 366
}  // namespace framework
}  // namespace paddle