memory_optimize_pass.h 2.1 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2018 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.

#pragma once
16
#include <string>
17 18
#include <unordered_map>
#include <unordered_set>
19 20
#include <utility>
#include <vector>
W
wanghuancoder 已提交
21

Y
Yan Chunwei 已提交
22
#include "paddle/fluid/inference/analysis/analysis_pass.h"
Y
Yan Chunwei 已提交
23
#include "paddle/fluid/platform/port.h"
Y
Yan Chunwei 已提交
24

W
wanghuancoder 已提交
25 26 27 28 29 30 31 32
namespace paddle {
namespace framework {
namespace ir {
class Graph;
}  // namespace ir
}  // namespace framework
}  // namespace paddle

Y
Yan Chunwei 已提交
33 34 35 36
namespace paddle {
namespace inference {
namespace analysis {

37 38 39 40 41 42 43 44 45 46 47
/* Memory optimization.
* We will perform the following operation:
* 1. Collect all var's lifetime.
* 2. Make reuse plan: the vars can be reused if there is no overlap(on lifetime)
* between
* them.
* The final plan is a mapping table in which the key represents the original
* name of var and the value in the table represents the current name of var.
* 3. Perform reuse plan: Replace all var's name in the model according to the
* mapping table.
*/
Y
Yan Chunwei 已提交
48 49 50 51 52 53 54 55 56 57 58 59
class MemoryOptimizePass : public AnalysisPass {
 public:
  using space_table_t = std::unordered_map<std::string, size_t>;
  using lifecycle_t = std::pair<int, int>;

  virtual ~MemoryOptimizePass() = default;

 protected:
  void RunImpl(Argument *argument) override;

 private:
  void CollectLifeCycle(
60
      framework::ir::Graph *graph,
Y
Yan Chunwei 已提交
61 62 63
      std::unordered_map<std::string, lifecycle_t> *lifecycles,
      int sort_kind) const;

64 65
  void CollectVarMemorySize(framework::ir::Graph *graph,
                            space_table_t *space_table) const;
Y
Yan Chunwei 已提交
66 67 68 69 70 71 72 73

 public:
  std::string repr() const override;
};

}  // namespace analysis
}  // namespace inference
}  // namespace paddle