layer.cc 14.3 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.

#include "paddle/fluid/imperative/layer.h"
16
#include <algorithm>
J
Jiabin Yang 已提交
17
#include <queue>
18
#include <utility>
19
#include "paddle/fluid/framework/framework.pb.h"
20
#include "paddle/fluid/framework/op_registry.h"
J
Jiabin Yang 已提交
21
#include "paddle/fluid/framework/variable_helper.h"
22 23 24 25
#include "paddle/fluid/imperative/execution_context.h"
#include "paddle/fluid/imperative/infer_shape_context.h"
#include "paddle/fluid/imperative/infer_var_type_context.h"
#include "paddle/fluid/imperative/op_base.h"
J
Jiabin Yang 已提交
26 27
#include "paddle/fluid/imperative/prepared_operator.h"
#include "paddle/fluid/operators/math/math_function.h"
M
minqiyang 已提交
28
#include "paddle/fluid/platform/device_context.h"
J
Jiabin Yang 已提交
29
#include "paddle/fluid/platform/enforce.h"
C
chengduo 已提交
30
#include "paddle/fluid/platform/profiler.h"
31 32 33 34

namespace paddle {
namespace imperative {

J
Jiabin Yang 已提交
35
using framework::Variable;
Z
Zeng Jinle 已提交
36 37 38 39 40 41 42 43
void ThreadSafeNameSet::Insert(const std::string& name) {
  std::lock_guard<std::mutex> guard(mtx_);
  set_.insert(name);
}

void ThreadSafeNameSet::Remove(const std::string& name) {
  std::lock_guard<std::mutex> guard(mtx_);
  auto iter = set_.find(name);
J
Jiabin Yang 已提交
44
  PADDLE_ENFORCE_EQ(iter != set_.end(), true, "%s does not exist", name);
Z
Zeng Jinle 已提交
45 46 47 48 49 50 51 52 53 54 55 56
  set_.erase(iter);
}

std::vector<std::string> ThreadSafeNameSet::Names() const {
  std::lock_guard<std::mutex> guard(mtx_);
  return std::vector<std::string>(set_.begin(), set_.end());
}

ThreadSafeNameSet VarBase::name_set_;

std::vector<std::string> VarBase::AliveVarNames() { return name_set_.Names(); }

J
Jiabin Yang 已提交
57 58 59 60
static framework::VariableNameMap CreateVarNameMap(
    const framework::OpInfo& op_info, const std::string& op_type,
    const NameVarBaseMap& varbase_map, bool is_input) {
  if (op_info.proto_ == nullptr) {
H
hong 已提交
61 62 63 64 65 66 67 68 69 70 71 72
    framework::VariableNameMap result;

    for (auto& it : varbase_map) {
      auto& var_vector = it.second;
      std::vector<std::string> args;
      args.reserve(var_vector.size());
      for (auto& var_base : var_vector) {
        args.emplace_back(var_base->Name());
      }
      result[it.first] = std::move(args);
    }
    return result;
M
minqiyang 已提交
73 74
  }

J
Jiabin Yang 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
  framework::VariableNameMap result;

  for (auto& var :
       is_input ? op_info.Proto().inputs() : op_info.Proto().outputs()) {
    auto it = varbase_map.find(var.name());
    if (it == varbase_map.end()) {
      PADDLE_ENFORCE_EQ(
          var.dispensable(), true,
          "Var: %s not dispensable and there are no such var in inputs",
          var.name());
      result[var.name()] = {};
    } else {
      auto& var_vector = it->second;
      std::vector<std::string> args;
      args.reserve(var_vector.size());
      for (auto& var_base : var_vector) {
        args.emplace_back(var_base->Name());
      }
      result[var.name()] = std::move(args);
    }
M
minqiyang 已提交
95
  }
J
Jiabin Yang 已提交
96 97
  return result;
}
M
minqiyang 已提交
98

J
Jiabin Yang 已提交
99 100 101 102 103 104 105 106 107
static framework::RuntimeContext PrepareRuntimeContext(
    const NameVarBaseMap& ins, const NameVarBaseMap& outs) {
  framework::VariableValueMap inputs, outputs;
  for (auto& in_pair : ins) {
    auto& in_ctx = inputs[in_pair.first];
    in_ctx.reserve(in_pair.second.size());
    for (auto& in_var : in_pair.second) {
      in_ctx.emplace_back(in_var->MutableVar());
    }
M
minqiyang 已提交
108 109
  }

J
Jiabin Yang 已提交
110 111 112 113 114
  for (auto& out_pair : outs) {
    auto& out_ctx = outputs[out_pair.first];
    out_ctx.reserve(out_pair.second.size());
    for (auto& out_var : out_pair.second) {
      out_ctx.emplace_back(out_var->MutableVar());
115
    }
J
Jiabin Yang 已提交
116 117 118 119
  }
  return framework::RuntimeContext(std::move(inputs), std::move(outputs));
}

120
template <typename VarType>
J
Jiabin Yang 已提交
121 122
static std::string DebugString(
    const std::string& name,
123
    const std::vector<std::shared_ptr<VarType>>& vars) {
J
Jiabin Yang 已提交
124 125
  std::stringstream ss;
  ss << name << "{";
M
minqiyang 已提交
126

J
Jiabin Yang 已提交
127 128
  for (size_t i = 0; i < vars.size(); ++i) {
    if (i > 0) ss << ", ";
M
minqiyang 已提交
129

J
Jiabin Yang 已提交
130 131 132 133 134
    if (vars[i] == nullptr) {
      ss << "NULL";
      continue;
    }
    ss << vars[i]->Name() << "[";
135
    const framework::Variable& var = vars[i]->Var();
J
Jiabin Yang 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148
    if (!var.IsInitialized()) {
      ss << "NOT_INITED_VAR";
    } else if (var.IsType<framework::LoDTensor>()) {
      auto& tensor = var.Get<framework::LoDTensor>();
      ss << "LoDTensor<";
      if (tensor.IsInitialized()) {
        ss << framework::DataTypeToString(tensor.type()) << ", ";
        ss << tensor.place() << ", ";
        ss << "(" << tensor.dims() << ")";
      } else {
        ss << "NOT_INITED";
      }
      ss << ">";
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    } else if (var.IsType<framework::SelectedRows>()) {
      ss << "SelectedRows<";
      auto& selected_rows = var.Get<framework::SelectedRows>();
      auto& tensor = selected_rows.value();
      auto& rows = selected_rows.rows();
      if (tensor.IsInitialized()) {
        ss << framework::DataTypeToString(tensor.type()) << ", ";
        ss << tensor.place() << ", ";
        ss << "height(" << selected_rows.height() << "), rows(";
        std::for_each(rows.cbegin(), rows.cend(),
                      [&ss](const int64_t r) { ss << r << " "; });
        ss << "), dims(" << tensor.dims() << ")";
      } else {
        ss << "NOT_INITED";
      }
      ss << ">";
J
Jiabin Yang 已提交
165 166 167 168
    } else {
      ss << "UNRESOLVED_TYPE";
    }
    ss << "]";
169
  }
170

J
Jiabin Yang 已提交
171 172
  ss << "}";
  return ss.str();
173 174
}

175 176 177 178
template <typename VarType>
static std::string LayerDebugStringImpl(const std::string& op_type,
                                        const NameVarMap<VarType>& ins,
                                        const NameVarMap<VarType>& outs) {
J
Jiabin Yang 已提交
179 180 181 182 183 184 185 186
  std::stringstream ss;
  ss << "Op(" << op_type << "): ";

  ss << "Inputs: ";

  size_t i = 0;
  for (auto& pair : ins) {
    if (i > 0) ss << ", ";
187
    ss << DebugString<VarType>(pair.first, pair.second);
J
Jiabin Yang 已提交
188
    ++i;
189 190
  }

J
Jiabin Yang 已提交
191 192 193 194
  ss << ",   Outputs: ";
  i = 0;
  for (auto& pair : outs) {
    if (i > 0) ss << ", ";
195
    ss << DebugString<VarType>(pair.first, pair.second);
J
Jiabin Yang 已提交
196 197 198 199
    ++i;
  }
  return ss.str();
}
200

201 202 203 204 205 206 207 208 209 210
std::string LayerDebugString(const std::string& op_type,
                             const NameVarMap<VarBase>& ins,
                             const NameVarMap<VarBase>& outs) {
  return LayerDebugStringImpl<VarBase>(op_type, ins, outs);
}

std::string LayerDebugString(const std::string& op_type,
                             const NameVarMap<VariableWrapper>& ins,
                             const NameVarMap<VariableWrapper>& outs) {
  return LayerDebugStringImpl<VariableWrapper>(op_type, ins, outs);
J
Jiabin Yang 已提交
211
}
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
VarBase::VarBase(bool has_grad, const std::shared_ptr<VariableWrapper>& var)
    : var_(var), grad_node_(var->GetGradNode()) {
  if (has_grad) {
    if (auto grad_var = var_->GetGradVar()) {
      grad_var_ = std::make_shared<VarBase>(false, grad_var);
    } else {
      grad_var_ = std::make_shared<VarBase>(false, GradVarName());
      var_->SetGradVar(grad_var_->var_);
    }
  }

  if (IsDebugEnabled()) {
    VLOG(10) << "Construct VarBase: " << Name();
    name_set_.Insert(Name());
  }
}

size_t VarBase::GradOpNum() const {
  return grad_node_ ? grad_node_->size() : 0;
}

J
Jiabin Yang 已提交
234 235
void VarBase::ClearGradient() {
  if (grad_var_) {
236 237 238
    if (grad_var_->Var().IsType<framework::SelectedRows>()) {
      auto* grad_t =
          grad_var_->MutableVar()->GetMutable<framework::SelectedRows>();
239 240 241 242 243
      if (grad_t->mutable_value()->IsInitialized()) {
        grad_t->mutable_rows()->clear();
        grad_t->mutable_value()->clear();
      }
    } else {
244 245
      auto* grad_t =
          grad_var_->MutableVar()->GetMutable<framework::LoDTensor>();
246 247 248 249 250
      if (grad_t->IsInitialized()) {
        auto* dev_ctx =
            platform::DeviceContextPool::Instance().Get(grad_t->place());
        operators::math::set_constant(*dev_ctx, grad_t, 0.0);
      }
251 252
    }
  }
J
Jiabin Yang 已提交
253
}
254

J
Jiabin Yang 已提交
255
std::shared_ptr<VarBase> VarBase::NewVarBase(const platform::Place& dst_place,
M
minqiyang 已提交
256
                                             const bool blocking) const {
257
  PADDLE_ENFORCE_EQ(
258 259
      Var().IsInitialized() && (Var().IsType<framework::LoDTensor>() ||
                                Var().IsType<framework::SelectedRows>()),
260 261 262
      true, platform::errors::InvalidArgument(
                "Variable is not initialized or Variable's type is not "
                "LoDTensor or SelectedRows when getting numpy tensor"));
263 264
  if (Var().IsType<framework::LoDTensor>()) {
    auto& src_tensor = Var().Get<framework::LoDTensor>();
265 266 267

    // TODO(Jiabin): change this after move unique_name generator to CXX
    auto new_var = std::make_shared<VarBase>(
268
        true, Name() + std::to_string(copied_counter_++));
269

270 271
    auto* dst_tensor =
        new_var->MutableVar()->GetMutable<framework::LoDTensor>();
272
    dst_tensor->set_lod(src_tensor.lod());
273 274 275
    new_var->SetPersistable(Persistable());
    new_var->SetDataType(DataType());
    new_var->SetType(Type());
276 277 278 279 280 281 282
    framework::TensorCopy(src_tensor, dst_place, dst_tensor);
    if (blocking) {
      platform::DeviceContextPool::Instance().Get(dst_place)->Wait();
      auto src_place = src_tensor.place();
      if (!(src_place == dst_place)) {
        platform::DeviceContextPool::Instance().Get(src_place)->Wait();
      }
283
    }
P
Paddle CI 已提交
284

285 286 287 288 289
    if (platform::is_gpu_place(dst_place)) {
      VLOG(3) << "copy tensor " << Name() << " from gpu";
    }
    return new_var;
  } else {
290
    auto& src_selected_rows = Var().Get<framework::SelectedRows>();
291 292 293 294
    auto new_var = std::make_shared<VarBase>(
        false, "Itmp" + std::to_string(copied_counter_++));
    new_var->SetType(framework::proto::VarType::SELECTED_ROWS);
    auto* dst_selected_rows =
295
        new_var->MutableVar()->GetMutable<framework::SelectedRows>();
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

    framework::TensorCopy(src_selected_rows.value(), dst_place,
                          dst_selected_rows->mutable_value());
    if (blocking) {
      platform::DeviceContextPool::Instance().Get(dst_place)->Wait();
      auto src_place = src_selected_rows.place();
      if (!(src_place == dst_place)) {
        platform::DeviceContextPool::Instance().Get(src_place)->Wait();
      }
    }
    dst_selected_rows->set_height(src_selected_rows.height());
    dst_selected_rows->set_rows(src_selected_rows.rows());
    if (platform::is_gpu_place(dst_place)) {
      VLOG(3) << "copy selected rows " << Name() << " from gpu";
    }
    return new_var;
  }
M
minqiyang 已提交
313 314
}

315
void OpBase::SetType(const std::string& type) {
H
hong 已提交
316
  op_ = framework::OpRegistry::CreateOp(type, {}, {}, {}, false);
J
Jiabin Yang 已提交
317
}
318

319 320 321
void OpBase::ClearBackwardTrace() {
  ins_.clear();
  outs_.clear();
H
hong 已提交
322 323
}

324 325 326 327 328 329 330
template <typename VarType>
static void OpBaseRunImpl(const framework::OperatorBase& op,
                          const NameVarMap<VarType>& ins,
                          const NameVarMap<VarType>& outs,
                          const framework::AttributeMap& attrs,
                          const platform::Place& place) {
  auto* op_kernel = dynamic_cast<const framework::OperatorWithKernel*>(&op);
J
Jiabin Yang 已提交
331
  PADDLE_ENFORCE_NOT_NULL(op_kernel, "only support op with kernel");
332
  auto& info = op.Info();
J
Jiabin Yang 已提交
333
  if (info.infer_var_type_) {
334
    RuntimeInferVarTypeContext<VarType> infer_var_type_ctx(ins, outs, attrs);
J
Jiabin Yang 已提交
335
    info.infer_var_type_(&infer_var_type_ctx);
X
Xin Pan 已提交
336
  }
337

J
Jiabin Yang 已提交
338 339 340
  // Initialize output var type
  for (auto& var_pair : outs) {
    for (auto& var : var_pair.second) {
341 342 343
      if (var) {
        InitializeVariable(var->MutableVar(), var->Type());
      }
344 345
    }
  }
X
Xin Pan 已提交
346

347 348 349
  // VLOG(3) << "Running Op " << op.Type();
  VLOG(5) << LayerDebugString(op.Type(), ins, outs);
  auto prepared_op = PreparedOp::Prepare(ins, outs, *op_kernel, place, attrs);
350

351
  prepared_op.Run(ins, outs, attrs);
352

353
  VLOG(4) << LayerDebugString(op.Type(), ins, outs);
354 355
}

356 357 358 359 360 361 362 363 364 365 366 367 368 369
void OpBase::Run(const framework::OperatorBase& op,
                 const NameVarMap<VarBase>& ins,
                 const NameVarMap<VarBase>& outs,
                 const framework::AttributeMap& attrs,
                 const platform::Place& place) {
  OpBaseRunImpl<VarBase>(op, ins, outs, attrs, place);
}

void OpBase::Run(const framework::OperatorBase& op,
                 const NameVarMap<VariableWrapper>& ins,
                 const NameVarMap<VariableWrapper>& outs,
                 const framework::AttributeMap& attrs,
                 const platform::Place& place) {
  OpBaseRunImpl<VariableWrapper>(op, ins, outs, attrs, place);
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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
static void ClearNoNeedBufferInputs(OpBase* op) {
  auto& inferer = op->Info().NoNeedBufferVarsInferer();
  if (!inferer) return;
  auto* ins = op->GetMutableInsMap();
  const auto& no_need_buffer_slots =
      inferer(*ins, op->GetOutsMap(), op->Attrs());
  if (no_need_buffer_slots.empty()) return;

  for (auto& slot : no_need_buffer_slots) {
    auto iter = ins->find(slot);
    if (iter == ins->end()) continue;
    VLOG(2) << "Clear data buffer of " << slot << " in " << op->Type();

    PADDLE_ENFORCE_EQ(
        iter->second.IsGrad(), false,
        platform::errors::InvalidArgument(
            "Only forward variable buffers can be clear, this may be a bug"));

    for (auto& each_var : *(iter->second.MutableVarList())) {
      if (!each_var) continue;

      auto& var = each_var->Var();
      PADDLE_ENFORCE_EQ(var.IsType<framework::LoDTensor>(), true,
                        platform::errors::PermissionDenied(
                            "NoNeedBufferVars only support LoDTensor"));
      // TODO(zjl): support higher order derivatives
      auto new_var = new VariableWrapper(each_var->Name());
      auto* new_tensor =
          new_var->MutableVar()->GetMutable<framework::LoDTensor>();
      auto& old_tensor = var.Get<framework::LoDTensor>();
      new_tensor->Resize(old_tensor.dims());
      new_tensor->set_lod(old_tensor.lod());
      each_var.reset(new_var);
    }
  }
}

std::shared_ptr<GradOpNode> CreateGradOpNode(
    const framework::OperatorBase& op, const NameVarBaseMap& ins,
    const NameVarBaseMap& outs, const framework::AttributeMap& attrs,
    const platform::Place& place) {
  const auto& info = op.Info();
  if (!info.dygraph_grad_op_maker_) {
    return nullptr;
  }

  auto grad_node = info.dygraph_grad_op_maker_(op.Type(), ins, outs, attrs);
  if (grad_node && !grad_node->empty()) {
    for (auto& op : *grad_node) {
      op.SetId(OpBase::GenerateUniqueId());
      op.SetPlace(place);
      ClearNoNeedBufferInputs(&op);
    }
    return grad_node;
  } else {
    return nullptr;
  }
}

431 432
}  // namespace imperative
}  // namespace paddle