infershape_utils.cc 7.8 KB
Newer Older
C
Chen Weihang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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"

#include "paddle/fluid/framework/framework.pb.h"
18
#include "paddle/fluid/framework/pten_utils.h"
C
Chen Weihang 已提交
19 20
#include "paddle/fluid/platform/enforce.h"
#include "paddle/pten/core/compat/arg_map_context.h"
21
#include "paddle/pten/core/compat/op_utils.h"
C
Chen Weihang 已提交
22 23 24
#include "paddle/pten/core/compat_utils.h"
#include "paddle/pten/core/convert_utils.h"
#include "paddle/pten/core/dense_tensor.h"
25
#include "paddle/pten/core/infermeta_utils.h"
C
Chen Weihang 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#include "paddle/pten/core/meta_tensor.h"

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);
  }

  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;
  }

67 68 69 70 71 72 73 74 75 76
  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 已提交
77 78 79 80 81 82 83 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
 private:
  const InferShapeContext& ctx_;
};

// TODO(chenweihang): Support SelectedRows later
// 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_);
      return var->Get<LoDTensor>().dims();
    } else {
      auto* var = BOOST_GET_CONST(VarDesc*, var_);
      return make_ddim(var->GetShape());
    }
  }

  pten::DataType dtype() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
      return var->Get<LoDTensor>().dtype();
    } else {
      auto* var = BOOST_GET_CONST(VarDesc*, var_);
      return pten::TransToPtenDataType(var->GetDataType());
    }
  }

  DataLayout layout() const override {
    if (is_runtime_) {
      auto* var = BOOST_GET_CONST(Variable*, var_);
      return var->Get<LoDTensor>().layout();
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported get layout for VarDesc now."));
    }
  }

  void set_dims(const DDim& dims) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      pten::CompatibleDenseTensorUtils::GetMutableMeta(
          static_cast<pten::DenseTensor*>(tensor))
          ->dims = dims;
    } 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_);
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      pten::CompatibleDenseTensorUtils::GetMutableMeta(
          static_cast<pten::DenseTensor*>(tensor))
          ->dtype = dtype;
    } else {
      auto* var = BOOST_GET(VarDesc*, var_);
      var->SetDataType(pten::TransToProtoVarType(dtype));
    }
  }

  void set_layout(DataLayout layout) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      pten::CompatibleDenseTensorUtils::GetMutableMeta(
          static_cast<pten::DenseTensor*>(tensor))
          ->layout = layout;
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported set layout for VarDesc now."));
    }
  }

  void share_lod(const MetaTensor& meta_tensor) override {
    if (is_runtime_) {
      auto* var = BOOST_GET(Variable*, var_);
      LoDTensor* tensor = var->GetMutable<LoDTensor>();
      pten::CompatibleDenseTensorUtils::GetMutableMeta(
          static_cast<pten::DenseTensor*>(tensor))
          ->lod =
          static_cast<const CompatMetaTensor&>(meta_tensor).GetRuntimeLoD();
    } else {
      auto* var = BOOST_GET(VarDesc*, var_);
      var->SetLoDLevel(static_cast<const CompatMetaTensor&>(meta_tensor)
                           .GetCompileTimeLoD());
    }
  }

 private:
  const LoD& GetRuntimeLoD() const {
    auto* var = BOOST_GET_CONST(Variable*, var_);
    return var->Get<LoDTensor>().lod();
  }
  int32_t GetCompileTimeLoD() const {
    auto* var = BOOST_GET_CONST(VarDesc*, var_);
    return var->GetLoDLevel();
  }

  InferShapeVarPtr var_;
  bool is_runtime_;
};

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
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);
  auto& output_names = std::get<2>(signature.args);
  // TODO(chenweihang): support attrs in next pr
  // auto& attr_names = std::get<1>(signature.args);

  // TODO(chenweihang): support multiple inputs and outputs
  pten::InferMetaContext infer_mete_context;
  for (auto& in_name : input_names) {
    infer_meta_context.EmplaceBackInput(std::make_shared<CompatMetaTensor>(
        ctx->GetInputVarPtrs(in_name)[0], ctx->IsRuntime()));
  }
  for (auto& out_name : output_names) {
    infer_meta_context.EmplaceBackOutput(std::make_shared<CompatMetaTensor>(
        ctx->GetOutputVarPtrs(out_name)[0], ctx->IsRuntime()));
  }
  // TODO(chenweihang): support attrs later

  return infer_meta_context;
}

C
Chen Weihang 已提交
237 238
}  // namespace framework
}  // namespace paddle