layer.h 31.9 KB
Newer Older
J
Jiabin Yang 已提交
1
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
// 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.

#pragma once
J
Jiabin Yang 已提交
16 17
#include <algorithm>
#include <atomic>
Z
Zeng Jinle 已提交
18
#include <cstdint>
J
Jiabin Yang 已提交
19
#include <list>
Z
Zeng Jinle 已提交
20 21 22 23
#include <map>     // NOLINT
#include <memory>  // NOLINT
#include <mutex>   // NOLINT
#include <set>
24
#include <string>         // NOLINT
M
minqiyang 已提交
25
#include <unordered_map>  // NOLINT
26
#include <utility>
J
Jiabin Yang 已提交
27
#include <vector>
28 29
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/operator.h"
H
hong 已提交
30 31 32 33
#include "paddle/fluid/framework/shape_inference.h"
#include "paddle/fluid/framework/type_defs.h"
#include "paddle/fluid/framework/var_desc.h"
#include "paddle/fluid/framework/var_type.h"
M
minqiyang 已提交
34
#include "paddle/fluid/framework/var_type_inference.h"
J
Jiabin Yang 已提交
35
#include "paddle/fluid/framework/variable.h"
Z
Zeng Jinle 已提交
36
#include "paddle/fluid/imperative/flags.h"
J
Jiabin Yang 已提交
37 38 39
#include "paddle/fluid/imperative/type_defs.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/macros.h"
M
minqiyang 已提交
40

41 42 43 44 45
namespace paddle {
namespace imperative {

class OpBase;

Z
Zeng Jinle 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58
class ThreadSafeNameSet {
 public:
  void Insert(const std::string& name);

  void Remove(const std::string& name);

  std::vector<std::string> Names() const;

 private:
  std::multiset<std::string> set_;
  mutable std::mutex mtx_;
};

59
class VarBase {
J
Jiabin Yang 已提交
60 61
  DISABLE_COPY_AND_ASSIGN(VarBase);

62
 public:
Z
Zeng Jinle 已提交
63
  static std::vector<std::string> AliveVarNames();
J
Jiabin Yang 已提交
64
  explicit VarBase(bool has_grad, const std::string& name)
65
      : name_(name),
J
Jiabin Yang 已提交
66
        grad_var_(has_grad ? new VarBase(false, GradVarName()) : nullptr) {
Z
Zeng Jinle 已提交
67
    if (IsDebugEnabled()) {
J
Jiabin Yang 已提交
68
      VLOG(10) << "Construct VarBase: " << name;
Z
Zeng Jinle 已提交
69 70
      name_set_.Insert(name_);
    }
71
  }
72

J
Jiabin Yang 已提交
73 74 75 76
  explicit VarBase(const std::string& name) : VarBase(true, name) {}

  ~VarBase() {
    VLOG(10) << "Destruct VarBase: " << name_;
Z
Zeng Jinle 已提交
77 78 79
    if (IsDebugEnabled()) {
      name_set_.Remove(name_);
    }
M
minqiyang 已提交
80
  }
81

J
Jiabin Yang 已提交
82
  const framework::Variable& Var() const { return var_; }
83

J
Jiabin Yang 已提交
84
  framework::Variable* MutableVar() { return &var_; }
M
minqiyang 已提交
85

J
Jiabin Yang 已提交
86 87 88 89
  bool HasGradVar() const { return grad_var_ != nullptr; }

  const std::shared_ptr<VarBase>& GradVarBase() const { return grad_var_; }

90 91 92 93 94 95 96 97 98 99 100 101
  void ClearGradVarBase() { grad_var_ = nullptr; }

  const std::shared_ptr<VarBase>& MutableGradVarBase() {
    if (grad_var_ == nullptr) {
      grad_var_ = std::make_shared<VarBase>(false, GradVarName());
      // NOTE(zhiqiu): we should keep grad_var_'s stop_gradient property same as
      // fwd varbase
      grad_var_->SetOverridedStopGradient(overrided_stop_gradient_);
    }
    return grad_var_;
  }

J
Jiabin Yang 已提交
102 103 104
  const framework::Variable& GradVar() const {
    PADDLE_ENFORCE_NOT_NULL(grad_var_, "Gradient of %s does not exist", name_);
    return grad_var_->var_;
M
minqiyang 已提交
105
  }
M
minqiyang 已提交
106

J
Jiabin Yang 已提交
107 108 109 110
  framework::Variable* MutableGradVar() {
    PADDLE_ENFORCE_NOT_NULL(grad_var_, "Gradient of %s does not exist", name_);
    return &(grad_var_->var_);
  }
X
Xin Pan 已提交
111

112 113 114 115 116 117 118
  // This is used for python api
  void SetOverridedStopGradient(bool stop_gradient) {
    if (stop_gradient) {
      overrided_stop_gradient_ = 1;
    } else {
      overrided_stop_gradient_ = 0;
    }
J
Jiabin Yang 已提交
119
    if (grad_var_) {
120 121 122 123 124 125 126 127 128
      grad_var_->SetOverridedStopGradient(stop_gradient);
    }
  }
  // This is used for python api
  bool OverridedStopGradient() const {
    if (overrided_stop_gradient_ == 0) {
      return false;
    } else {
      return true;
129
    }
M
minqiyang 已提交
130
  }
X
Xin Pan 已提交
131

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  // This is used inside C++
  int InnerOverridedStopGradient() const { return overrided_stop_gradient_; }

  bool GradGenerated() const { return grad_generated_; }

  void SetGradGenerated(bool generated) { grad_generated_ = generated; }
  // This is used inside C++
  void InnerSetOverridedStopGradient(bool stop_gradient) {
    if (overrided_stop_gradient_ == -1) {
      overrided_stop_gradient_ = static_cast<int>(stop_gradient);
      if (grad_var_) {
        grad_var_->InnerSetOverridedStopGradient(stop_gradient);
      }
    } else {
      VLOG(6) << "Ignore Stop gradient conversion for Var: " << Name()
              << "Set value is: " << overrided_stop_gradient_;
    }
  }
150

J
Jiabin Yang 已提交
151
  void SetPersistable(bool persistable) { persistable_ = persistable; }
152

J
Jiabin Yang 已提交
153
  bool Persistable() const { return persistable_; }
154

J
Jiabin Yang 已提交
155
  void AddGradOps(const std::weak_ptr<OpBase>& op);
X
Xin Pan 已提交
156

J
Jiabin Yang 已提交
157 158 159 160 161 162
  std::vector<OpBase*> GradOps() {
    std::vector<OpBase*> rlt;
    // TODO(jiabin): use better data structure to remove nullptr when we find it
    for (const auto& wk_ptr : grad_ops_) {
      OpBase* tmp_op = wk_ptr.lock().get();
      if (tmp_op) rlt.emplace_back(tmp_op);
M
minqiyang 已提交
163
    }
J
Jiabin Yang 已提交
164
    return rlt;
X
Xin Pan 已提交
165
  }
166

J
Jiabin Yang 已提交
167
  void ClearGradOps() { grad_ops_.clear(); }
X
Xin Pan 已提交
168

J
Jiabin Yang 已提交
169
  const std::string& Name() const { return name_; }
M
minqiyang 已提交
170

J
Jiabin Yang 已提交
171 172 173 174 175
  void SetName(const std::string& name) {
    name_ = name;
    if (grad_var_) {
      grad_var_->SetName(GradVarName());
    }
M
minqiyang 已提交
176 177
  }

J
Jiabin Yang 已提交
178
  std::string GradVarName() { return framework::GradVarName(name_); }
179

J
Jiabin Yang 已提交
180
  void SetType(framework::proto::VarType::Type type) { type_ = type; }
181

J
Jiabin Yang 已提交
182
  framework::proto::VarType::Type Type() const { return type_; }
183

J
Jiabin Yang 已提交
184 185 186 187
  void SetDataType(framework::proto::VarType::Type data_type) {
    data_type_ = data_type;
    if (grad_var_) {
      grad_var_->SetDataType(data_type_);
188 189 190
    }
  }

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  framework::proto::VarType::Type DataType() const {
    const framework::Tensor* tensor = nullptr;
    if (var_.IsInitialized()) {
      if (type_ == framework::proto::VarType::LOD_TENSOR) {
        tensor = &(var_.Get<framework::LoDTensor>());
      } else if (type_ == framework::proto::VarType::SELECTED_ROWS) {
        tensor = &(var_.Get<framework::SelectedRows>().value());
      } else {
        VLOG(6) << "Variable " << name_ << " is not initialized";
        return data_type_;
      }
    }
    if (tensor && tensor->IsInitialized()) {
      return tensor->type();
    } else {
      VLOG(6) << "The tensor of variable " << name_ << " is not initialized";
      return data_type_;
    }
  }
X
polish  
Xin Pan 已提交
210

J
Jiabin Yang 已提交
211
  void ClearGradient();
X
Xin Pan 已提交
212

J
Jiabin Yang 已提交
213 214
  std::shared_ptr<VarBase> NewVarBase(const platform::Place& dst_place,
                                      const bool blocking) const;
M
minqiyang 已提交
215

J
Jiabin Yang 已提交
216 217 218 219
 private:
  framework::Variable var_;
  std::string name_;
  std::shared_ptr<VarBase> grad_var_;
H
hong 已提交
220

J
Jiabin Yang 已提交
221
  mutable size_t copied_counter_ = 0;
222

J
Jiabin Yang 已提交
223 224
  // grad_op indicates which grad_op will this var be used as input
  std::vector<std::weak_ptr<OpBase>> grad_ops_;
225 226 227 228 229
  // add this property for users may set stop_gradient themselves and this
  // should override the
  // frameworks setting (-1) unset, (1) true, (0) false
  int overrided_stop_gradient_{-1};
  bool grad_generated_{false};
J
Jiabin Yang 已提交
230
  bool persistable_{false};
M
minqiyang 已提交
231

J
Jiabin Yang 已提交
232 233 234
  framework::proto::VarType::Type type_{framework::proto::VarType::LOD_TENSOR};
  framework::proto::VarType::Type data_type_{framework::proto::VarType::FP32};
  static ThreadSafeNameSet name_set_;
235 236 237 238 239 240
};

class Layer {
 public:
  virtual ~Layer() {}

241 242
  virtual std::vector<std::shared_ptr<VarBase>> Forward(
      const std::vector<std::shared_ptr<VarBase>>& inputs) {
J
Jiabin Yang 已提交
243
    return {};
244
  }
X
Xin Pan 已提交
245
};
246

H
hong 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class DygraphExecutionContext : public framework::ExecutionContext {
  using Variable = framework::Variable;

 public:
  DygraphExecutionContext(const framework::OperatorBase& op,
                          const framework::Scope& scope,
                          const platform::DeviceContext& device_context,
                          const framework::RuntimeContext& ctx,
                          std::vector<framework::KernelConfig>* configs,
                          const NameVarBaseMap& var_base_map_in,
                          const NameVarBaseMap& var_base_map_out,
                          const framework::AttributeMap* attrs)
      : ExecutionContext(op, scope, device_context, ctx, configs),
        var_base_map_in_(var_base_map_in),
        var_base_map_out_(var_base_map_out),
        attrs_(attrs) {}

264
  std::string InputName(const std::string& name) const override {
H
hong 已提交
265 266 267 268 269 270
    auto it = var_base_map_in_.find(name);
    PADDLE_ENFORCE_NE(it, var_base_map_in_.end(),
                      platform::errors::PreconditionNotMet(
                          "Can not find [%s] in Input", name));
    return it->second[0]->Name();
  }
271
  std::vector<std::string> InputNames(const std::string& name) const override {
H
hong 已提交
272 273 274 275 276 277 278 279 280 281 282 283
    auto it = var_base_map_in_.find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_in_.end(),
        platform::errors::NotFound("Can not find [%s] in Input", name));
    std::vector<std::string> vec_res;
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.push_back(it->second[i]->Name());
    }
    return vec_res;
  }

284
  std::string OutputName(const std::string& name) const override {
H
hong 已提交
285 286 287 288 289 290 291
    auto it = var_base_map_out_.find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_.end(),
        platform::errors::NotFound("Can not find [%s] in Output", name));
    return it->second[0]->Name();
  }

292
  std::vector<std::string> OutputNames(const std::string& name) const override {
H
hong 已提交
293 294 295 296 297 298 299 300 301 302 303 304
    auto it = var_base_map_out_.find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_.end(),
        platform::errors::NotFound("Can not find [%s] in Output", name));
    std::vector<std::string> vec_res;
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.push_back(it->second[i]->Name());
    }
    return vec_res;
  }

305 306 307
  bool HasAttr(const std::string& name) const override {
    return attrs_->count(name);
  }
H
hong 已提交
308

309
  const framework::AttributeMap& Attrs() const override { return *attrs_; }
H
hong 已提交
310

311
  const framework::Attribute& GetAttr(const std::string& name) const override {
H
hong 已提交
312 313 314 315 316 317 318 319 320
    auto it = attrs_->find(name);

    PADDLE_ENFORCE_NE(
        it, attrs_->end(),
        platform::errors::NotFound("can not find [%s] in attrs", name));

    return it->second;
  }

321
  std::vector<std::string> InNameList() const override {
H
hong 已提交
322 323 324 325 326 327 328 329 330
    std::vector<std::string> vec_temp;
    vec_temp.reserve(var_base_map_in_.size());

    for (auto& v : var_base_map_in_) {
      vec_temp.push_back(v.first);
    }

    return vec_temp;
  }
331
  bool HasInput(const std::string& name) const override {
H
hong 已提交
332 333 334 335
    auto it = var_base_map_in_.find(name);
    return (it != var_base_map_in_.end() && it->second.size() > 0);
  }

336
  bool HasOutput(const std::string& name) const override {
H
hong 已提交
337 338 339 340
    auto it = var_base_map_out_.find(name);
    return (it != var_base_map_out_.end() && it->second.size() > 0);
  }

341
  size_t InputSize(const std::string& name) const override {
H
hong 已提交
342 343 344
    return InputNames(name).size();
  }

345
  size_t OutputSize(const std::string& name) const override {
H
hong 已提交
346 347 348 349 350 351 352 353 354 355 356 357
    return OutputNames(name).size();
  }

  const Variable* InputVar(const std::string& name) const override {
    auto it = var_base_map_in_.find(name);
    if (it == var_base_map_in_.end()) {
      return nullptr;
    }

    return it->second.empty() ? nullptr : it->second[0]->MutableVar();
  }

358
  Variable* OutputVar(const std::string& name) const override {
H
hong 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    auto it = var_base_map_out_.find(name);
    if (it == var_base_map_out_.end()) {
      return nullptr;
    }

    return it->second.empty() ? nullptr : it->second[0]->MutableVar();
  }

  const std::vector<Variable*> MultiInputVar(
      const std::string& name) const override {
    auto it = var_base_map_in_.find(name);
    if (it == var_base_map_in_.end()) {
      return {};
    }
    std::vector<Variable*> vec_res;
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.push_back(it->second[i]->MutableVar());
    }

    return vec_res;
  }

  std::vector<Variable*> MultiOutputVar(
      const std::string& name) const override {
    auto it = var_base_map_out_.find(name);
    if (it == var_base_map_out_.end()) {
      return {};
    }
    std::vector<Variable*> vec_res;
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.push_back(it->second[i]->MutableVar());
    }

    return vec_res;
  }

 private:
  const NameVarBaseMap& var_base_map_in_;
  const NameVarBaseMap& var_base_map_out_;
  const framework::AttributeMap* attrs_;
};

M
minqiyang 已提交
403
// infer var type context for imperative mode
J
Jiabin Yang 已提交
404
class RuntimeInferVarTypeContext : public framework::InferVarTypeContext {
M
minqiyang 已提交
405
 public:
J
Jiabin Yang 已提交
406 407 408
  RuntimeInferVarTypeContext(const NameVarBaseMap& inputs,
                             const NameVarBaseMap* outputs,
                             const framework::AttributeMap& attrs_map)
M
minqiyang 已提交
409 410 411 412 413 414 415
      : InferVarTypeContext(nullptr, nullptr),
        inputs_(inputs),
        outputs_(outputs),
        attrs_(attrs_map),
        input_names_(),
        output_names_(),
        var_set_() {
J
Jiabin Yang 已提交
416 417 418
    input_names_.reserve(inputs_.size());
    for (auto& it : inputs_) {
      for (auto& var : it.second) {
M
minqiyang 已提交
419
        input_names_[it.first].emplace_back(var->Name());
J
Jiabin Yang 已提交
420
        var_set_[var->Name()] = var.get();
M
minqiyang 已提交
421 422 423 424 425
      }
    }

    output_names_.reserve(outputs_->size());
    for (auto& it : *outputs_) {
J
Jiabin Yang 已提交
426
      for (auto& var : it.second) {
M
minqiyang 已提交
427
        output_names_[it.first].emplace_back(var->Name());
J
Jiabin Yang 已提交
428
        var_set_[var->Name()] = var.get();
M
minqiyang 已提交
429 430 431 432
      }
    }
  }

M
minqiyang 已提交
433 434 435
  virtual ~RuntimeInferVarTypeContext() {}

  framework::Attribute GetAttr(const std::string& name) const override {
J
Jiabin Yang 已提交
436 437 438 439
    auto iter = attrs_.find(name);
    PADDLE_ENFORCE_EQ(iter != attrs_.end(), true, "Cannot find attribute %s",
                      name);
    return iter->second;
M
minqiyang 已提交
440 441
  }

M
minqiyang 已提交
442
  bool HasVar(const std::string& name) const override {
M
minqiyang 已提交
443 444 445
    return var_set_.count(name) > 0;
  }

M
minqiyang 已提交
446
  bool HasInput(const std::string& name) const override {
447 448
    auto it = inputs_.find(name);
    return (it != inputs_.end() && it->second.size() > 0);
M
minqiyang 已提交
449 450
  }

M
minqiyang 已提交
451
  bool HasOutput(const std::string& name) const override {
M
minqiyang 已提交
452
    PADDLE_ENFORCE_NOT_NULL(outputs_);
453 454
    auto it = outputs_->find(name);
    return (it != outputs_->end() && it->second.size() > 0);
M
minqiyang 已提交
455 456
  }

M
minqiyang 已提交
457 458
  const std::vector<std::string>& Input(
      const std::string& name) const override {
J
Jiabin Yang 已提交
459 460 461 462
    auto iter = input_names_.find(name);
    PADDLE_ENFORCE_EQ(iter != input_names_.end(), true, "Cannot find input %s",
                      name);
    return iter->second;
M
minqiyang 已提交
463 464
  }

M
minqiyang 已提交
465 466
  const std::vector<std::string>& Output(
      const std::string& name) const override {
J
Jiabin Yang 已提交
467
    auto iter = output_names_.find(name);
H
hong 已提交
468

J
Jiabin Yang 已提交
469 470 471
    PADDLE_ENFORCE_EQ(iter != output_names_.end(), true,
                      "Cannot find output %s", name);
    return iter->second;
M
minqiyang 已提交
472 473
  }

M
minqiyang 已提交
474 475
  framework::proto::VarType::Type GetType(
      const std::string& name) const override {
J
Jiabin Yang 已提交
476
    auto iter = var_set_.find(name);
H
hong 已提交
477

J
Jiabin Yang 已提交
478 479 480
    PADDLE_ENFORCE_EQ(iter != var_set_.end(), true,
                      "Cannot find var %s in GetType", name);
    return iter->second->Type();
M
minqiyang 已提交
481 482
  }

M
minqiyang 已提交
483 484
  void SetType(const std::string& name,
               framework::proto::VarType::Type type) override {
485 486 487 488
    if (name == "kLookupTablePath") {
      VLOG(2) << "SUPER UGLY FIX, remove this when move imperative mode in C++";
    } else {
      var_set_[name]->SetType(type);
489 490 491 492
      if ((var_set_[name]->MutableVar()->IsInitialized() == true) &&
          (var_set_[name]->MutableVar()->Type() != type)) {
        var_set_[name]->MutableVar()->Clear();
      }
493
    }
M
minqiyang 已提交
494 495
  }

M
minqiyang 已提交
496 497
  framework::proto::VarType::Type GetDataType(
      const std::string& name) const override {
J
Jiabin Yang 已提交
498
    auto iter = var_set_.find(name);
H
hong 已提交
499

J
Jiabin Yang 已提交
500 501 502
    PADDLE_ENFORCE_EQ(iter != var_set_.end(), true,
                      "Cannot find var %s in GetDataType", name);
    return iter->second->DataType();
M
minqiyang 已提交
503 504
  }

M
minqiyang 已提交
505 506
  void SetDataType(const std::string& name,
                   framework::proto::VarType::Type type) override {
M
minqiyang 已提交
507
    var_set_[name]->SetDataType(type);
M
minqiyang 已提交
508 509
  }

M
minqiyang 已提交
510 511
  std::vector<framework::proto::VarType::Type> GetDataTypes(
      const std::string& name) const override {
M
minqiyang 已提交
512 513 514
    PADDLE_THROW("GetDataTypes is not supported in runtime InferVarType");
  }

M
minqiyang 已提交
515 516 517
  void SetDataTypes(const std::string& name,
                    const std::vector<framework::proto::VarType::Type>&
                        multiple_data_type) override {
M
minqiyang 已提交
518 519 520
    PADDLE_THROW("SetDataTypes is not supported in runtime InferVarType");
  }

M
minqiyang 已提交
521
  std::vector<int64_t> GetShape(const std::string& name) const override {
M
minqiyang 已提交
522 523 524
    PADDLE_THROW("Do not handle Shape in runtime InferVarType");
  }

M
minqiyang 已提交
525 526
  void SetShape(const std::string& name,
                const std::vector<int64_t>& dims) override {
M
minqiyang 已提交
527 528 529
    PADDLE_THROW("Do not handle Shape in runtime InferVarType");
  }

M
minqiyang 已提交
530
  int32_t GetLoDLevel(const std::string& name) const override {
M
minqiyang 已提交
531 532 533
    PADDLE_THROW("Do not handle LoDLevel in runtime InferVarType");
  }

M
minqiyang 已提交
534
  void SetLoDLevel(const std::string& name, int32_t lod_level) override {
M
minqiyang 已提交
535 536 537 538
    PADDLE_THROW("Do not handle LoDLevel in runtime InferVarType");
  }

 private:
J
Jiabin Yang 已提交
539 540 541
  const NameVarBaseMap& inputs_;
  const NameVarBaseMap* outputs_;
  const framework::AttributeMap& attrs_;
M
minqiyang 已提交
542 543
  std::unordered_map<std::string, std::vector<std::string>> input_names_;
  std::unordered_map<std::string, std::vector<std::string>> output_names_;
J
Jiabin Yang 已提交
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 571 572 573 574
  std::unordered_map<std::string, VarBase*> var_set_;
};

// TODO(zjl): to support py_func layer
class OpBase : public std::enable_shared_from_this<OpBase> {
  DISABLE_COPY_AND_ASSIGN(OpBase);

 public:
  ~OpBase() { VLOG(3) << "Destruct Op: " << Type() << std::endl; }

  // Developer should not rely on this method to create OpBase.
  // OpBase should be created in Tracer and managed by Tracer totally.
  template <typename... Args>
  static std::shared_ptr<OpBase> Create(Args&&... args) {
    return std::shared_ptr<OpBase>(new OpBase(std::forward<Args>(args)...));
  }

  size_t id() const { return id_; }

  const std::string& Type() const { return op_->Type(); }

  void Run(const NameVarBaseMap& ins, const NameVarBaseMap& outs);

  const framework::VariableNameMap& InputNameMap() const {
    return op_->Inputs();
  }

  const framework::VariableNameMap& OutputNameMap() const {
    return op_->Outputs();
  }

H
hong 已提交
575
  const framework::AttributeMap& Attrs() const { return attrs_; }
J
Jiabin Yang 已提交
576 577 578 579 580 581 582 583
  const framework::OpInfo& Info() const { return op_->Info(); }

  void ClearBackwardTrace();

  const std::vector<OpBase*>& GradPendingOps() const {
    return grad_pending_ops_;
  }

H
hong 已提交
584 585 586 587
  void SetGradPendingOps(std::vector<OpBase*> vec_temp) {
    grad_pending_ops_.swap(vec_temp);
  }

J
Jiabin Yang 已提交
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
  void InsertGradPendingOps(OpBase* op) { grad_pending_ops_.emplace_back(op); }

  void SortGradPendingOps() {
    std::sort(grad_pending_ops_.begin(), grad_pending_ops_.end(),
              [](OpBase* op1, OpBase* op2) { return op1->id() > op2->id(); });
  }
  NameVarBaseMap* GetMutableOutsMap() { return &outs_; }
  NameVarBaseMap* GetMutableInsMap() { return &ins_; }
  const NameVarBaseMap& GetInsMap() { return ins_; }
  const NameVarBaseMap& GetOutsMap() { return outs_; }
  const platform::Place& place() const { return place_; }

  // TODO(jiabin) prepare for backward hook
  void RegisterBackwardHooks(const std::function<void()>& func) {
    backward_hooks_.emplace_back(func);
  }

  void InvokeBackwardHooks() {
    for (const auto& func : backward_hooks_) {
      func();
      VLOG(5) << "Invoke Backward Hook for: " << Type() << std::endl;
    }
  }

 private:
  OpBase(size_t id, const std::string& type, const NameVarBaseMap& ins,
H
hong 已提交
614
         const NameVarBaseMap& outs, const framework::AttributeMap& attrs,
J
Jiabin Yang 已提交
615 616
         const platform::Place& place);

H
hong 已提交
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 650 651 652 653 654 655 656 657 658 659 660
 public:
  OpBase() {}

  void SetType(const std::string& type) { type_ = type; }
  void SetInput(const std::string& name,
                std::vector<std::shared_ptr<VarBase>> vec_var_base) {
    ins_[name] = std::move(vec_var_base);
  }
  void SetOutput(const std::string& name,
                 std::vector<std::shared_ptr<VarBase>> vec_var_base) {
    outs_[name] = std::move(vec_var_base);
  }
  void SetAttrMap(const framework::AttributeMap& attrs) { attrs_ = attrs; }
  void SetAttr(const std::string& name, const framework::Attribute& v) {
    attrs_[name] = v;
  }
  void SetBlockAttr(const std::string& name, framework::BlockDesc* block) {
    PADDLE_THROW("SetBlockAttr is not support in dygraph OpBase");
  }

  const framework::AttributeMap& Attrs() { return attrs_; }

  void CreateOperatorBase();

  void SetId(size_t id) { id_ = id; }
  void SetPlace(platform::Place place) { place_ = place; }

  bool HasAttr(const std::string& name) const {
    return attrs_.find(name) != attrs_.end();
  }

  const framework::Attribute& GetAttr(const std::string& name) const {
    auto it = attrs_.find(name);
    PADDLE_ENFORCE(it != attrs_.end(), "can not find attribute [%s]", name);

    return it->second;
  }

  template <typename T>
  inline const T& Attr(const std::string& name) const {
    return boost::get<T>(GetAttr(name));
  }

 private:
J
Jiabin Yang 已提交
661 662 663 664 665 666 667 668 669
  size_t id_;

  std::unique_ptr<framework::OperatorBase> op_;

  std::vector<std::function<void()>> backward_hooks_;
  platform::Place place_;

  // Not need to be std::weak_ptr, because op is binded to a certain Tracer,
  // and would not be used by a Tracer that does not create itself.
H
hong 已提交
670

J
Jiabin Yang 已提交
671 672 673 674 675
  std::vector<OpBase*> grad_pending_ops_;

  // This part is only used for backward
  NameVarBaseMap ins_;
  NameVarBaseMap outs_;
H
hong 已提交
676 677
  std::string type_;
  framework::AttributeMap attrs_;
678 679
};

H
hong 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 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 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
class DygraphInferShapeContext : public framework::InferShapeContext {
  using DDim = framework::DDim;

 public:
  DygraphInferShapeContext(const NameVarBaseMap* in, const NameVarBaseMap* out,
                           const framework::AttributeMap* attr)
      : var_base_map_in_(in), var_base_map_out_(out), attrs_(attr) {}

  bool HasInput(const std::string& name) const override {
    // has only one input
    auto it = var_base_map_in_->find(name);

    if (it == var_base_map_in_->end()) {
      return false;
    }
    const auto& in = it->second;
    if (in.size() == 0) return false;
    PADDLE_ENFORCE_EQ(
        in.size(), 1UL,
        platform::errors::PreconditionNotMet(
            "Input %s should not have more than one inputs", name));
    return in[0] != nullptr;
  }

  bool HasOutput(const std::string& name) const override {
    // has only one output
    auto it = var_base_map_out_->find(name);
    if (it == var_base_map_out_->end()) {
      return false;
    }
    const auto& out = it->second;
    if (out.size() == 0) {
      return false;
    }
    PADDLE_ENFORCE_EQ(
        out.size(), 1UL,
        platform::errors::PreconditionNotMet(
            "Output %s should not have more than one outputs", name));
    return out[0] != nullptr;
  }

  bool HasInputs(const std::string& name) const override {
    auto it = var_base_map_in_->find(name);
    if (it == var_base_map_in_->end() || it->second.empty()) {
      return false;
    }
    for (auto& input : it->second) {
      if (input == nullptr) {
        return false;
      }
    }
    return true;
  }

  bool HasOutputs(const std::string& name) const override {
    auto it = var_base_map_out_->find(name);
    if (it == var_base_map_out_->end() || it->second.empty()) {
      return false;
    }
    for (auto& output : it->second) {
      if (output == nullptr) {
        return false;
      }
    }
    return true;
  }

  framework::AttrReader Attrs() const override {
    return framework::AttrReader(*attrs_);
  }

  std::vector<std::string> Inputs(const std::string& name) const override {
    // return op_.Inputs(name);
    std::vector<std::string> vec_res;
    auto it = var_base_map_in_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_in_->end(),
        platform::errors::NotFound("can not find [%s] in input", name));

    vec_res.reserve(it->second.size());
    for (auto& var : it->second) {
      vec_res.push_back(var->Name());
    }

    return vec_res;
  }

  std::vector<std::string> Outputs(const std::string& name) const override {
    std::vector<std::string> vec_res;
    auto it = var_base_map_out_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_->end(),
        platform::errors::NotFound("can not find [%s] in output", name));

    vec_res.reserve(it->second.size());
    for (auto& var : it->second) {
      vec_res.push_back(var->Name());
    }

    return vec_res;
  }

  void ShareDim(const std::string& in, const std::string& out, size_t i = 0,
                size_t j = 0) override {
    auto in_it = var_base_map_in_->find(in);
    auto out_it = var_base_map_out_->find(out);
    PADDLE_ENFORCE_NE(
        in_it, var_base_map_in_->end(),
        platform::errors::NotFound("can not found [%s] in input", in));
    PADDLE_ENFORCE_GT(in_it->second.size(), i,
                      platform::errors::PreconditionNotMet(
                          "Inputs %s should have %llu argument", in, i));
    PADDLE_ENFORCE_NE(
        out_it, var_base_map_out_->end(),
        platform::errors::NotFound("can not found [%s] in input", in));
    PADDLE_ENFORCE_GT(out_it->second.size(), j,
                      platform::errors::PreconditionNotMet(
                          "Outputs %s should have %llu argument", out, j));

    framework::Variable* in_var = in_it->second[i]->MutableVar();
    framework::Variable* out_var = out_it->second[j]->MutableVar();

    PADDLE_ENFORCE_EQ(in_var->Type(), out_var->Type(),
                      platform::errors::PreconditionNotMet(
                          "The type of %s and %s is not the same.", in, out));

806 807 808 809 810 811 812 813 814 815 816
    if (in_var->IsType<framework::LoDTensor>()) {
      auto& in_lod_tensor = in_var->Get<framework::LoDTensor>();
      auto* out_lod_tensor = out_var->GetMutable<framework::LoDTensor>();
      out_lod_tensor->Resize(in_lod_tensor.dims());
    } else {
      auto& in_sele_rows = in_var->Get<framework::SelectedRows>();
      auto out_sele_rows = out_var->GetMutable<framework::SelectedRows>();
      out_sele_rows->mutable_value()->Resize(in_sele_rows.value().dims());
      out_sele_rows->set_rows(in_sele_rows.rows());
      out_sele_rows->set_height(in_sele_rows.height());
    }
H
hong 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 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 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
  }

  void ShareAllLoD(const std::string& in,
                   const std::string& out) const override {
    // do nothing
  }
  void ShareLoD(const std::string& in, const std::string& out, size_t i = 0,
                size_t j = 0) const override {
    // do nothing
  }

  bool IsRuntime() const override { return true; }

  // TODO(paddle-dev): Can this be template?
  std::vector<framework::InferShapeVarPtr> GetInputVarPtrs(
      const std::string& name) override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "GetInputVarPtrs not support in dygraph runtime context"));
  }

  std::vector<framework::InferShapeVarPtr> GetOutputVarPtrs(
      const std::string& name) override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "GetOutputVarPtrs not support in dygraph runtime context"));
  }

  DDim GetInputDim(const std::string& name) const override {
    auto it = var_base_map_in_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_in_->end(),
        platform::errors::NotFound("can not find [%s] in input", name));
    PADDLE_ENFORCE_EQ(
        it->second.size(), 1UL,
        platform::errors::PreconditionNotMet(
            "Input(%s) should hold one element, but now it holds %d", name,
            it->second.size()));
    return this->GetDim(it->second[0]->MutableVar());
  }

  std::vector<DDim> GetInputsDim(const std::string& name) const override {
    // const std::vector<Variable*>& vars = InputVars(name);
    std::vector<DDim> vec_res;
    auto it = var_base_map_in_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_in_->end(),
        platform::errors::NotFound("can not find [%s] in output", name));
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.emplace_back(GetDim(it->second[i]->MutableVar()));
    }

    return vec_res;
  }

  std::vector<framework::proto::VarType::Type> GetInputsVarType(
      const std::string& name) const override {
    std::vector<framework::proto::VarType::Type> vec_res;
    auto it = var_base_map_in_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_in_->end(),
        platform::errors::NotFound("can not find [%s] in input", name));
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.emplace_back(
          framework::ToVarType(it->second[i]->MutableVar()->Type()));
    }
    return vec_res;
  }

  std::vector<framework::proto::VarType::Type> GetOutputsVarType(
      const std::string& name) const override {
    std::vector<framework::proto::VarType::Type> vec_res;
    auto it = var_base_map_out_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_->end(),
        platform::errors::NotFound("can not find [%s] in output", name));
    vec_res.reserve(it->second.size());
    for (size_t i = 0; i < it->second.size(); ++i) {
      vec_res.emplace_back(
          framework::ToVarType(it->second[i]->MutableVar()->Type()));
    }
    return vec_res;
  }

  void SetOutputDim(const std::string& name, const DDim& dim) override {
    auto it = var_base_map_out_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_->end(),
        platform::errors::NotFound("can not find [%s] in output", name));

    SetDim(it->second[0]->MutableVar(), dim);
  }

  void SetOutputsDim(const std::string& name,
                     const std::vector<DDim>& dims) override {
    // auto& vars = OutputVars(name);
    // SetDims(vars, dims);

    auto it = var_base_map_out_->find(name);
    PADDLE_ENFORCE_NE(
        it, var_base_map_out_->end(),
        platform::errors::NotFound("can not find [%s] in output", name));

    PADDLE_ENFORCE_EQ(it->second.size(), dims.size(),
                      platform::errors::PreconditionNotMet(
                          "dim size [%d] is not match output var number [%d]",
                          dims.size(), it->second.size()));

    for (size_t i = 0; i < dims.size(); ++i) {
      SetDim(it->second[i]->MutableVar(), dims[i]);
    }
  }

  int32_t GetLoDLevel(const std::string& in, size_t i = 0) const override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "GetLoDLevel function not support in dygraph mode"));
  }

  void SetLoDLevel(const std::string& out, int32_t lod_level,
                   size_t j = 0) const override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "SetLoDLevel function not support in dygraph mode"));
  }

 protected:
  DDim GetDim(framework::Variable* var) const {
    PADDLE_ENFORCE_NOT_NULL(var, platform::errors::PreconditionNotMet(
                                     "Input variable should not be null"));
    if (var->IsType<framework::LoDTensor>()) {
      return var->Get<framework::LoDTensor>().dims();
    } else if (var->IsType<framework::SelectedRows>()) {
      return var->Get<framework::SelectedRows>().GetCompleteDims();
    } else {
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Only LoDTensor/SelectedRows support 'GetDim', but Variables "
          "type_id is xx."));
    }
  }

  std::vector<DDim> GetRepeatedDims(const std::string& name) const override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "GetRepeatedDims not support in dygraph runtime"));
  }

  void SetDim(framework::Variable* var, const DDim& dim) {
    if (var->IsType<framework::LoDTensor>()) {
      var->GetMutable<framework::LoDTensor>()->Resize(dim);
    } else if (var->IsType<framework::SelectedRows>()) {
      var->GetMutable<framework::SelectedRows>()->set_height(dim[0]);
    } else {
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Variable type_id %s, expect LoDTensor/SelectedRows."));
    }
  }

  void SetDims(const std::vector<framework::Variable*>& vars,
               const std::vector<DDim>& dims) {
    size_t length = vars.size();
    PADDLE_ENFORCE_EQ(
        length, dims.size(),
        platform::errors::PreconditionNotMet(
            "Vars number [%d] should be equal with dims number [%d]", length,
            dims.size()));
    for (size_t i = 0; i < length; ++i) {
      if (vars[i] == nullptr) {
        continue;
      }
      SetDim(vars[i], dims[i]);
    }
  }

  void SetRepeatedDims(const std::string& name,
                       const std::vector<DDim>& dims) override {
    PADDLE_THROW(platform::errors::PermissionDenied(
        "SetRepeatedDims not support in dygraph runtime"));
  }

 private:
  const NameVarBaseMap* var_base_map_in_;
  const NameVarBaseMap* var_base_map_out_;
  std::string type_;
  const framework::AttributeMap* attrs_;
};

1001 1002
}  // namespace imperative
}  // namespace paddle