program_desc_tracer.cc 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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/imperative/jit/program_desc_tracer.h"
16

W
wanghuancoder 已提交
17 18 19 20 21
namespace paddle {
namespace imperative {
class VarBase;
}  // namespace imperative
}  // namespace paddle
22 23 24 25 26

namespace paddle {
namespace imperative {
namespace jit {

Z
Zeng Jinle 已提交
27 28 29 30
// A helper class to generate unique name for each non-persistable var
class UniqueBlockVarGenerator {
 public:
  UniqueBlockVarGenerator(const VarDescMetaMap &all_vars,
31
                          const VarBaseSet &non_exist_input_vars,
Z
Zeng Jinle 已提交
32
                          framework::BlockDesc *block);
33

Z
Zeng Jinle 已提交
34 35
  std::string NameOf(const std::weak_ptr<VarBase> &var,
                     const std::string &prefix);
36

Z
Zeng Jinle 已提交
37 38 39
 private:
  void InsertNewVarInBlock(const std::weak_ptr<VarBase> &var,
                           const framework::VarDesc &ref_desc,
40 41
                           const std::string &name,
                           bool force_persistable = false);
42

Z
Zeng Jinle 已提交
43 44 45 46
 private:
  const VarDescMetaMap &all_vars_;
  framework::BlockDesc *block_;
  std::unordered_map<std::string, size_t> counter_;
47

Z
Zeng Jinle 已提交
48 49 50 51 52 53
  std::map<std::weak_ptr<VarBase>, std::string,
           std::owner_less<std::weak_ptr<VarBase>>>
      var_to_name_;
  std::unordered_set<std::string> existing_names_;
};

54 55 56
UniqueBlockVarGenerator::UniqueBlockVarGenerator(
    const VarDescMetaMap &all_vars, const VarBaseSet &non_exist_input_vars,
    framework::BlockDesc *block)
Z
Zeng Jinle 已提交
57 58 59 60 61
    : all_vars_(all_vars), block_(block) {
  for (auto &var_pair : all_vars_) {
    auto *var_desc = var_pair.second.get();
    if (var_desc->Persistable()) {
      InsertNewVarInBlock(var_pair.first, *var_desc, var_desc->Name());
62 63 64 65
    } else if (non_exist_input_vars.count(var_pair.first.lock()) > 0) {
      VLOG(10) << "Mark " << var_desc->Name() << " as persistable";
      InsertNewVarInBlock(var_pair.first, *var_desc, var_desc->Name(),
                          /*force_persistable=*/true);
Z
Zeng Jinle 已提交
66
    }
67 68 69
  }
}

Z
Zeng Jinle 已提交
70 71
std::string UniqueBlockVarGenerator::NameOf(const std::weak_ptr<VarBase> &var,
                                            const std::string &prefix) {
72
  VLOG(3) << "Finding: " << var.lock()->Name();
Z
Zeng Jinle 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  auto all_vars_iter = all_vars_.find(var);
  PADDLE_ENFORCE_EQ(all_vars_iter != all_vars_.end(), true,
                    platform::errors::NotFound(
                        "Variable is not found in UniqueBlockVarGenerator"));

  auto iter = var_to_name_.find(var);
  if (iter != var_to_name_.end()) {
    VLOG(5) << "Return existing var name " << iter->second;
    return iter->second;
  } else {
    auto generate_unique_name = [this, &prefix] {
      auto &cnt = counter_[prefix];
      do {
        auto name = prefix + std::to_string(cnt++);
        if (existing_names_.count(name) == 0) {
          return name;
        }
      } while (cnt > 0);
      PADDLE_THROW(
          platform::errors::OutOfRange("Too many vars in the program"));
    };

    auto unique_name = generate_unique_name();
    VLOG(5) << "Generate new var name " << unique_name;
    InsertNewVarInBlock(var, *(all_vars_iter->second), unique_name);
    return unique_name;
99
  }
Z
Zeng Jinle 已提交
100
}
101

Z
Zeng Jinle 已提交
102 103
void UniqueBlockVarGenerator::InsertNewVarInBlock(
    const std::weak_ptr<VarBase> &var, const framework::VarDesc &var_desc,
104
    const std::string &name, bool force_persistable) {
Z
Zeng Jinle 已提交
105 106 107 108 109
  var_to_name_[var] = name;
  existing_names_.insert(name);
  auto *new_var_desc = block_->Var(name);
  *new_var_desc = var_desc;
  new_var_desc->SetName(name);
110 111 112
  if (force_persistable) {
    new_var_desc->SetPersistable(true);
  }
113 114
}

115 116 117 118 119 120 121 122 123
bool ProgramDescTracer::ContainVar(const std::weak_ptr<VarBase> &var) const {
  auto vars_iter = vars_.find(var);
  bool ret = (vars_iter != vars_.end());
  if (!ret) {
    VLOG(5) << "Can't found variable: " << var.lock()->Name();
  }
  return ret;
}

124 125 126 127 128 129 130 131
void ProgramDescTracer::InsertOp(const std::string &type,
                                 const NameVarBaseMap &inputs,
                                 const NameVarBaseMap &outputs,
                                 const framework::AttributeMap &attrs) {
  ops_.emplace_back(new OpDescMeta(type, inputs, outputs, attrs));
  auto &new_op = ops_.back();
  for (auto &pair : new_op->Inputs()) {
    for (auto &var : pair.second) {
132
      InsertVarIfNotExist(var.lock(), true);
133 134 135 136 137
    }
  }

  for (auto &pair : new_op->Outputs()) {
    for (auto &var : pair.second) {
138
      InsertVarIfNotExist(var.lock(), false);
139 140 141 142
    }
  }
}

Z
Zeng Jinle 已提交
143 144 145 146 147
TracedProgramTuple ProgramDescTracer::CreateProgramDesc(
    const std::vector<std::shared_ptr<VarBase>> &feed_vars,
    const std::string &feed_prefix,
    const std::vector<std::shared_ptr<VarBase>> &fetch_vars,
    const std::string &fetch_prefix, const std::string &tmp_prefix) const {
148 149 150
  std::unique_ptr<framework::ProgramDesc> prog(new framework::ProgramDesc());
  auto *block = prog->MutableBlock(0);

151 152 153 154 155 156
  auto non_exist_vars_copy = non_exist_input_vars_;
  for (auto &feed_var : feed_vars) {
    non_exist_vars_copy.erase(feed_var);
  }

  UniqueBlockVarGenerator generator(vars_, non_exist_vars_copy, block);
157

Z
Zeng Jinle 已提交
158 159
  std::vector<std::string> feed_var_names;
  for (auto &feed_var : feed_vars) {
160 161 162
    if (ContainVar(feed_var)) {
      feed_var_names.emplace_back(generator.NameOf(feed_var, feed_prefix));
    }
163 164
  }

Z
Zeng Jinle 已提交
165 166
  std::vector<std::string> fetch_var_names;
  for (auto &fetch_var : fetch_vars) {
167 168 169
    if (ContainVar(fetch_var)) {
      fetch_var_names.emplace_back(generator.NameOf(fetch_var, fetch_prefix));
    }
170 171 172 173 174 175 176 177 178 179 180
  }

  for (auto &op : ops_) {
    auto *op_desc = block->AppendOp();
    op_desc->SetType(op->Type());
    op_desc->SetAttrMap(op->Attrs());

    for (auto &pair : op->Inputs()) {
      std::vector<std::string> names;
      names.reserve(pair.second.size());
      for (auto &var : pair.second) {
181 182 183
        if (ContainVar(var)) {
          names.emplace_back(generator.NameOf(var, tmp_prefix));
        }
184 185 186 187 188 189 190 191 192
      }

      op_desc->SetInput(pair.first, std::move(names));
    }

    for (auto &pair : op->Outputs()) {
      std::vector<std::string> names;
      names.reserve(pair.second.size());
      for (auto &var : pair.second) {
193 194 195
        if (ContainVar(var)) {
          names.emplace_back(generator.NameOf(var, tmp_prefix));
        }
196 197 198 199 200 201 202
      }

      op_desc->SetOutput(pair.first, std::move(names));
    }
  }

  prog->Flush();
203 204 205 206 207 208 209 210 211 212 213 214

  std::vector<std::shared_ptr<VarBase>> persistable_vars(
      non_exist_vars_copy.begin(), non_exist_vars_copy.end());
  for (auto &pair : vars_) {
    if (pair.second->Persistable()) {
      auto var = pair.first.lock();
      PADDLE_ENFORCE_NOT_NULL(
          var, platform::errors::NotFound("Persistable var %s does not exist",
                                          pair.second->Name()));
      persistable_vars.emplace_back(var);
    }
  }
Z
Zeng Jinle 已提交
215
  return std::make_tuple(std::move(prog), std::move(feed_var_names),
216 217
                         std::move(fetch_var_names),
                         std::move(persistable_vars));
218 219 220
}

void ProgramDescTracer::InsertVarIfNotExist(
221
    const std::shared_ptr<VarBase> &new_var, bool is_input) {
222 223
  PADDLE_ENFORCE_NOT_NULL(new_var, platform::errors::InvalidArgument(
                                       "The variable to insert is NULL."));
224 225 226
  if (vars_.count(new_var) != 0) return;

  auto new_var_desc = new framework::VarDesc("");
Z
Zeng Jinle 已提交
227
  vars_[new_var].reset(new_var_desc);
228

229
  if (new_var->Persistable() || is_input) {
230
    new_var_desc->SetName(new_var->Name());
231 232 233 234
    new_var_desc->SetPersistable(new_var->Persistable());
    if (!new_var->Persistable()) {
      non_exist_input_vars_.insert(new_var);
    }
235 236 237 238 239
  } else {
    new_var_desc->SetPersistable(false);
  }

  const auto &inner_var = new_var->Var();
240 241 242
  PADDLE_ENFORCE_EQ(inner_var.IsInitialized(), true,
                    platform::errors::InvalidArgument(
                        "The variable to insert is not initialized."));
243 244 245 246 247 248 249 250 251 252 253
  if (inner_var.IsType<framework::LoDTensor>()) {
    const auto &tensor = inner_var.Get<framework::LoDTensor>();
    new_var_desc->SetType(framework::proto::VarType::LOD_TENSOR);
    new_var_desc->SetShape(framework::vectorize<int64_t>(tensor.dims()));
    new_var_desc->SetLoDLevel(tensor.lod().size());
    if (tensor.IsInitialized()) {
      new_var_desc->SetDataType(tensor.type());
    } else {
      new_var_desc->SetDataType(framework::proto::VarType::FP32);
    }
  } else {
254 255 256
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Not support variable type %s.",
        framework::ToTypeName(inner_var.Type())));
257 258 259 260 261 262
  }
}

void ProgramDescTracer::Reset() {
  ops_.clear();
  vars_.clear();
263
  non_exist_input_vars_.clear();
264 265 266 267 268
}

}  // namespace jit
}  // namespace imperative
}  // namespace paddle