block_desc.cc 9.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
F
fengjiayi 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/block_desc.h"
M
minqiyang 已提交
16

17
#include <queue>
M
minqiyang 已提交
18

Y
Yi Wang 已提交
19 20
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
F
fengjiayi 已提交
21 22 23 24

namespace paddle {
namespace framework {

Y
Yu Yang 已提交
25
VarDesc *BlockDesc::Var(const std::string &name) {
F
fengjiayi 已提交
26
  auto it = vars_.find(name);
D
Dong Zhihong 已提交
27
  if (it != vars_.end()) {
D
Dong Zhihong 已提交
28
    return it->second.get();
D
Dong Zhihong 已提交
29
  }
30
  need_update_ = true;
Y
Yu Yang 已提交
31
  auto *var = new VarDesc(name);
F
fengjiayi 已提交
32 33 34 35
  vars_[name].reset(var);
  return var;
}

Y
Yu Yang 已提交
36
VarDesc *BlockDesc::FindVar(const std::string &name) const {
F
fengjiayi 已提交
37
  auto it = vars_.find(name);
D
Dong Zhihong 已提交
38 39 40
  if (it == vars_.end()) {
    return nullptr;
  }
F
fengjiayi 已提交
41 42 43
  return it->second.get();
}

Y
Yu Yang 已提交
44
bool BlockDesc::HasVar(const std::string &name) const {
Q
qiaolongfei 已提交
45
  return vars_.find(name) != vars_.end();
Q
qiaolongfei 已提交
46 47
}

T
wip  
typhoonzero 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61
VarDesc *BlockDesc::RenameVar(const std::string &old_name,
                              const std::string &new_name) {
  if (!this->HasVar(old_name)) {
    return nullptr;
  }
  need_update_ = true;
  auto *var = this->Var(old_name);
  VarDesc *new_var = new VarDesc(*(var->Proto()));
  new_var->SetName(new_name);
  vars_[new_name].reset(new_var);
  // rename inputs and outputs
  for (const auto &op : ops_) {
    auto *it = op.get();
    it->Rename(old_name, new_name);
T
typhoonzero 已提交
62
  }
T
wip  
typhoonzero 已提交
63 64
  vars_.erase(old_name);
  return new_var;
T
typhoonzero 已提交
65 66
}

Y
Yu Yang 已提交
67
VarDesc *BlockDesc::FindVarRecursive(const std::string &name) const {
68 69
  if (name == kEmptyVarName) return nullptr;

Y
Yu Yang 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  std::queue<const BlockDesc *> frontier;
  std::unordered_set<const BlockDesc *> visited;

  frontier.push(this);

  while (!frontier.empty()) {  // BFS
    auto cur = frontier.front();
    frontier.pop();
    if (visited.count(cur) != 0) {
      continue;
    }
    auto var = cur->FindVar(name);
    if (var != nullptr) {
      return var;
    }

    auto fwd = cur->ForwardBlock();
    auto parent = cur->ParentBlock();

    if (fwd != nullptr) {
      frontier.push(fwd);
    }
    if (parent != nullptr) {
      frontier.push(parent);
    }

    visited.insert(cur);
97
  }
Y
Yu Yang 已提交
98 99

  return nullptr;
100 101
}

Y
Yang Yu 已提交
102
VarDesc &BlockDesc::FindRecursiveOrCreateVar(const std::string &name_bytes) {
Y
Yu Yang 已提交
103
  VarDesc *res = FindVarRecursive(name_bytes);
Y
Yang Yang(Tony) 已提交
104 105 106
  if (res == nullptr) {
    res = Var(name_bytes);
  }
Y
Yang Yu 已提交
107
  return *res;
Y
Yang Yang(Tony) 已提交
108 109
}

Y
Yu Yang 已提交
110
bool BlockDesc::HasVarRecursive(const std::string &name) const {
111 112 113
  return FindVarRecursive(name) != nullptr;
}

Y
Yu Yang 已提交
114 115
std::vector<VarDesc *> BlockDesc::AllVars() const {
  std::vector<VarDesc *> res;
F
fengjiayi 已提交
116 117 118 119 120 121
  for (const auto &p : vars_) {
    res.push_back(p.second.get());
  }
  return res;
}

Y
Yu Yang 已提交
122
OpDesc *BlockDesc::AppendOp() {
F
fengjiayi 已提交
123
  need_update_ = true;
124
  ops_.emplace_back(new OpDesc(this));
F
fengjiayi 已提交
125 126 127
  return ops_.back().get();
}

Y
Yu Yang 已提交
128
void BlockDesc::AppendAllocatedOp(std::unique_ptr<OpDesc> &&op_desc) {
129 130 131 132
  need_update_ = true;
  ops_.emplace_back(std::move(op_desc));
}

Y
Yu Yang 已提交
133
OpDesc *BlockDesc::PrependOp() {
F
fengjiayi 已提交
134
  need_update_ = true;
135
  ops_.emplace_front(new OpDesc(this));
F
fengjiayi 已提交
136 137 138
  return ops_.front().get();
}

Y
Yao Cheng 已提交
139 140 141 142 143
void BlockDesc::PrependAllocatedOp(std::unique_ptr<OpDesc> &&op_desc) {
  need_update_ = true;
  ops_.emplace_front(std::move(op_desc));
}

144 145 146 147 148 149 150 151
OpDesc *BlockDesc::InsertOp(size_t index) {
  need_update_ = true;
  auto it = ops_.begin() + index;
  std::unique_ptr<OpDesc> new_op(new OpDesc(this));
  it = ops_.insert(it, std::move(new_op));
  return (*it).get();
}

T
typhoonzero 已提交
152
void BlockDesc::RemoveOp(size_t s, size_t e) {
Y
Yancey 已提交
153
  if (ops_.begin() + s >= ops_.end() || ops_.begin() + e > ops_.end()) {
T
typhoonzero 已提交
154 155 156 157 158 159
    return;
  }
  need_update_ = true;
  ops_.erase(ops_.begin() + s, ops_.begin() + e);
}

160
void BlockDesc::RemoveOpInternal(const OpDesc *op_desc) {
M
minqiyang 已提交
161
  // TODO(minqiyang): make this faster
162 163 164
  for (auto it = ops_.begin(); it != ops_.end(); ++it) {
    if (it->get() == op_desc) {
      ops_.erase(it);
165
      break;
166 167 168 169
    }
  }
}

Y
Yu Yang 已提交
170 171
std::vector<OpDesc *> BlockDesc::AllOps() const {
  std::vector<OpDesc *> res;
F
fengjiayi 已提交
172 173 174 175 176 177
  for (const auto &op : ops_) {
    res.push_back(op.get());
  }
  return res;
}

Y
Yu Yang 已提交
178
void BlockDesc::Flush() {
L
Leo Chen 已提交
179
  auto need_update = NeedUpdate(true);
180 181 182
  for (auto &op_desc : ops_) {
    op_desc->Flush();
  }
L
Leo Chen 已提交
183 184 185
  // no flush for var_desc? or is op_desc flush really needed?
  VLOG(10) << "Flush " << NeedUpdate(true) << " " << need_update << std::endl;
  if (need_update) {
Q
Qiao Longfei 已提交
186
    this->desc_->mutable_ops()->Clear();
F
fengjiayi 已提交
187
    for (auto &op_desc : ops_) {
Q
Qiao Longfei 已提交
188
      this->desc_->mutable_ops()->Add()->CopyFrom(*op_desc->Proto());
L
Leo Chen 已提交
189
      // op_desc's need_update is set to false in op_desc->Flush();
F
fengjiayi 已提交
190
    }
L
Leo Chen 已提交
191 192 193 194 195 196 197 198 199 200

    std::vector<std::string> var_names;
    std::set<std::string> var_names_set;

    // keep order
    for (const auto &var : this->desc_->vars()) {
      var_names.emplace_back(var.name());
      var_names_set.insert(var.name());
    }

Q
Qiao Longfei 已提交
201
    this->desc_->mutable_vars()->Clear();
L
Leo Chen 已提交
202 203 204 205 206 207 208
    for (const auto &name : var_names) {
      if (vars_.count(name)) {
        this->desc_->mutable_vars()->Add()->CopyFrom(*vars_[name]->Proto());
        vars_[name]->SetNeedUpdate(false);
      }
    }

F
Fix bug  
fengjiayi 已提交
209
    for (auto &var_desc : vars_) {
L
Leo Chen 已提交
210 211 212 213
      if (var_names_set.count(var_desc.first) != 1) {
        this->desc_->mutable_vars()->Add()->CopyFrom(*var_desc.second->Proto());
        var_desc.second->SetNeedUpdate(false);
      }
F
Fix bug  
fengjiayi 已提交
214
    }
L
Leo Chen 已提交
215 216 217 218 219 220

    // this->desc_->mutable_vars()->Clear();
    // for (auto &var_desc : vars_) {
    //   this->desc_->mutable_vars()->Add()->CopyFrom(*var_desc.second->Proto());
    //   var_desc.second->SetNeedUpdate(false);
    // }
F
fengjiayi 已提交
221 222 223 224
    need_update_ = false;
  }
}

Y
Yu Yang 已提交
225
BlockDesc *BlockDesc::ParentBlock() const {
Y
Yu Yang 已提交
226
  return prog_->MutableBlock(static_cast<size_t>(desc_->parent_idx()));
F
fengjiayi 已提交
227 228
}

Y
Yu Yang 已提交
229
proto::BlockDesc *BlockDesc::Proto() {
230 231 232
  Flush();
  return desc_;
}
233

Y
Yu Yang 已提交
234
BlockDesc::BlockDesc(ProgramDesc *prog, proto::BlockDesc *desc)
235
    : prog_(prog), desc_(desc), need_update_(false) {
236
  for (const proto::VarDesc &var_desc : desc_->vars()) {
Y
Yu Yang 已提交
237
    vars_[var_desc.name()].reset(new VarDesc(var_desc));
238
  }
L
Leo Chen 已提交
239

240
  for (const proto::OpDesc &op_desc : desc_->ops()) {
F
fengjiayi 已提交
241
    ops_.emplace_back(new OpDesc(op_desc, this));
242 243 244
  }
}

245 246
BlockDesc::BlockDesc(const BlockDesc &other,
                     proto::BlockDesc *desc,
Y
Yu Yang 已提交
247
                     ProgramDesc *prog)
Y
Yu Yang 已提交
248 249
    : prog_(prog), desc_(desc) {
  need_update_ = true;
250 251
  // NOTE(dev): Init vars_ firstly so we can find them
  // while constructing OpDesc.
Y
Yu Yang 已提交
252
  for (auto &it : other.vars_) {
Y
Yu Yang 已提交
253
    auto *var = new VarDesc(*it.second);
Y
Yu Yang 已提交
254 255
    vars_[it.first].reset(var);
  }
256 257 258
  for (auto &op : other.ops_) {
    ops_.emplace_back(new OpDesc(*op, this));
  }
Y
Yu Yang 已提交
259
}
260

Y
Yu Yang 已提交
261
void BlockDesc::SetForwardBlockID(int32_t forward_block_id) {
262
  PADDLE_ENFORCE_EQ(
263 264
      desc_->has_forward_block_idx(),
      false,
265 266
      platform::errors::PreconditionNotMet(
          "Block %d's parent block ID has been set to %d, cannot be set to %d.",
267 268 269
          desc_->idx(),
          desc_->forward_block_idx(),
          forward_block_id));
Y
Yu Yang 已提交
270 271 272 273 274 275 276
  desc_->set_forward_block_idx(forward_block_id);
}

BlockDesc *BlockDesc::ForwardBlock() const {
  return prog_->MutableBlock(static_cast<size_t>(desc_->forward_block_idx()));
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
void BlockDesc::MoveFrom(BlockDesc *block) {
  PADDLE_ENFORCE_NOT_NULL(
      block, platform::errors::InvalidArgument("Block must be provided."));
  if (this == block) {
    return;
  }

  for (auto &pair : block->vars_) {
    const auto &name = pair.first;
    auto &var_ptr = pair.second;
    auto &old_var_ptr = vars_[name];
    if (old_var_ptr == nullptr) {
      VLOG(10) << "Create new variable " << var_ptr->Name();
      old_var_ptr = std::move(var_ptr);
    } else {
      // NOTE(zjl): cannot release old_var_ptr, because Python
      // Variable holds the reference of the C++ VarDesc object.
      // If the C++ VarDesc object is destructed, any call to the
      // methods of Python Variable may raise segmentation fault.
      VLOG(10) << "Update old variable " << var_ptr->Name();
      *old_var_ptr = *var_ptr;
    }
  }
  ops_.clear();
  for (const auto &src_op : block->ops_) {
302 303 304 305 306
    auto *dst_op = AppendOp();
    dst_op->CopyFrom(*src_op);
    for (const auto &pair : src_op->GetAttrMap()) {
      const auto &attr_name = pair.first;
      const auto &attr_value = pair.second;
R
Ruibiao Chen 已提交
307
      auto attr_type = static_cast<proto::AttrType>(attr_value.index() - 1);
308 309 310 311
      if (attr_type == proto::AttrType::VAR ||
          attr_type == proto::AttrType::VARS) {
        dst_op->UpdateVarAttr(attr_name, attr_value);
      } else if (attr_type == proto::AttrType::BLOCK) {
R
Ruibiao Chen 已提交
312
        auto block_id = PADDLE_GET_CONST(BlockDesc *, attr_value)->ID();
313 314 315
        dst_op->SetBlockAttr(attr_name, prog_->MutableBlock(block_id));
        VLOG(10) << "Set block attr " << attr_name << " id " << block_id;
      } else if (attr_type == proto::AttrType::BLOCKS) {
R
Ruibiao Chen 已提交
316 317
        auto old_blocks =
            PADDLE_GET_CONST(std::vector<BlockDesc *>, attr_value);
318 319 320 321 322 323 324 325 326
        std::vector<BlockDesc *> new_blocks;
        new_blocks.reserve(old_blocks.size());
        for (auto *b : old_blocks) {
          VLOG(10) << "Set block attr " << attr_name << " id " << b->ID();
          new_blocks.push_back(prog_->MutableBlock(b->ID()));
        }
        dst_op->SetBlocksAttr(attr_name, new_blocks);
      }
    }
327 328 329 330 331 332 333 334 335 336
  }
  need_update_ = true;
  Flush();

  block->ops_.clear();
  block->vars_.clear();
  block->need_update_ = true;
  block->Flush();
}

L
Leo Chen 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
bool BlockDesc::NeedUpdate(bool include_subs) {
  bool need = need_update_;
  if (include_subs) {
    for (const auto &op : ops_) {
      if (op->NeedUpdate()) {
        need = true;
        break;
      }
    }
    for (const auto &pair : vars_) {
      if (pair.second->NeedUpdate()) {
        need = true;
        break;
      }
    }
  }
  return need;
}

F
fengjiayi 已提交
356 357
}  // namespace framework
}  // namespace paddle