optimizer.h 8.4 KB
Newer Older
Y
Yan Chunwei 已提交
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.

#pragma once
16
#include <map>
Y
Yan Chunwei 已提交
17 18 19 20 21
#include <memory>
#include <string>
#include <vector>
#include "lite/core/mir/generate_program_pass.h"
#include "lite/core/mir/pass_manager.h"
22
#include "lite/core/mir/pass_utils.h"
Y
Yan Chunwei 已提交
23 24 25 26 27 28 29 30 31
#include "lite/core/mir/ssa_graph.h"
#include "lite/core/mir/static_kernel_pick_pass.h"
#include "lite/core/mir/type_target_cast_pass.h"
#include "lite/core/program.h"
#include "lite/core/types.h"
#include "lite/model_parser/model_parser.h"
#ifdef LITE_WITH_NPU
#include "lite/core/mir/subgraph/generate_npu_program_pass.h"
#endif
32 33 34
#ifdef LITE_WITH_XPU
#include "lite/core/mir/subgraph/generate_xpu_program_pass.h"
#endif
Y
Yan Chunwei 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

namespace paddle {
namespace lite {

/*
 * lite::Optimizer optimize a program. It utilize the mir passes to analysis the
 * program and export an optimized program.
 */
class Optimizer {
 public:
  void Run(Program&& program,
           const std::vector<Place>& valid_places,
           core::KernelPickFactor kernel_pick_factor,
           const std::vector<std::string>& passes = {}) {
    program_ = &program;
    valid_places_ = valid_places;
    CHECK(!valid_places.empty()) << "At least one valid_place should be set";
    CHECK(!graph_) << "duplicate optimize found";
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    auto valid_places_has_target = [&](TargetType t) -> bool {
      for (auto& p : valid_places) {
        if (p.target == t) {
          return true;
        }
      }
      return false;
    };
    std::map<std::string, bool> lite_with_targets{
        {"kOpenCL", valid_places_has_target(TARGET(kOpenCL))},
        {"kNPU", valid_places_has_target(TARGET(kNPU))},
        {"kXPU", valid_places_has_target(TARGET(kXPU))}};
    VLOG(4) << "lite_with_targets['kOpenCL']:" << lite_with_targets["kOpenCL"];
    VLOG(4) << "lite_with_targets['kNPU']:" << lite_with_targets["kNPU"];
    VLOG(4) << "lite_with_targets['kXPU']:" << lite_with_targets["kXPU"];

Y
Yan Chunwei 已提交
69 70 71 72 73 74 75 76
    graph_.reset(new mir::SSAGraph);
    graph_->Build(program, valid_places);
    graph_->SetValidPlaces(valid_places);

    SpecifyKernelPickTactic(kernel_pick_factor);
    InitTargetTypeTransformPass();

    if (passes.empty()) {
77
      std::vector<std::string> passes_local{
78 79 80 81
          {"lite_quant_dequant_fuse_pass",     //
           "lite_conv_elementwise_fuse_pass",  // conv-elemwise-bn
           "lite_conv_bn_fuse_pass",           //
           "lite_conv_elementwise_fuse_pass",  // conv-bn-elemwise
Y
Yan Chunwei 已提交
82 83
           // TODO(Superjomn) Refine the fusion related design to select fusion
           // kernels for devices automatically.
84 85 86 87
           "lite_conv_activation_fuse_pass",              //
           "lite_fc_fuse_pass",                           //
           "lite_shuffle_channel_fuse_pass",              //
           "lite_transpose_softmax_transpose_fuse_pass",  //
Z
zhupengyang 已提交
88
           "lite_interpolate_fuse_pass",                  //
89
           "identity_scale_eliminate_pass",               //
Y
Yan Chunwei 已提交
90 91 92
#ifdef LITE_WITH_LIGHT_WEIGHT_FRAMEWORK
           "lite_elementwise_add_activation_fuse_pass",  //
#endif
93 94 95 96 97 98 99
           "static_kernel_pick_pass",        // pick original kernel from graph
           "variable_place_inference_pass",  // inference arg/var's
           // info(target/precision/layout/device)
           // using kernel info
           "argument_type_display_pass",  // debug pass: show arg-type-node's
                                          // info
                                          // (target/precision/layout/device)
Y
Yan Chunwei 已提交
100

101 102 103
           "type_target_cast_pass",  // add io_copy/io_copy_once if meet
                                     // different targets when last and next
                                     // node
Y
Yan Chunwei 已提交
104 105 106
           "variable_place_inference_pass",  //
           "argument_type_display_pass",     //

107 108 109
           "io_copy_kernel_pick_pass",    //
           "argument_type_display_pass",  //

Y
Yan Chunwei 已提交
110 111 112 113 114 115 116
           "variable_place_inference_pass",  //
           "argument_type_display_pass",     //

           "type_precision_cast_pass",       //
           "variable_place_inference_pass",  //
           "argument_type_display_pass",     //

117 118 119 120
           "type_layout_cast_pass",  // add layout/layout_once op if meet
                                     // different layout when last and next node
           "argument_type_display_pass",  //

Y
Yan Chunwei 已提交
121
           "variable_place_inference_pass",  //
122
           "argument_type_display_pass",
Y
Yan Chunwei 已提交
123 124

           "runtime_context_assign_pass",
125 126 127 128 129 130 131 132
           "argument_type_display_pass"}};
      if ((!lite_with_targets["kOpenCL"]) && (!lite_with_targets["kNPU"]) &&
          (!lite_with_targets["kXPU"])) {
        // TODO(ysh329): cause CL_INVALID_MEM_OBJECT when setArg in OpenCL
        // kernel
        passes_local.emplace_back("memory_optimize_pass");
      }
      RunPasses(passes_local);
Y
Yan Chunwei 已提交
133 134 135 136 137 138 139 140 141 142
    } else {
      RunPasses(passes);
    }
    exec_scope_ = program.exec_scope();
  }

  const lite::Scope* exec_scope() const { return exec_scope_; }

  // Generate a new program based on the mir graph.
  std::unique_ptr<RuntimeProgram> GenRuntimeProgram() {
143 144
#if defined(LITE_WITH_NPU) || defined(LITE_WITH_XPU)
    auto target_place = Place{
145
#ifdef LITE_WITH_NPU
146 147 148 149 150 151 152
        TARGET(kNPU),
#endif
#ifdef LITE_WITH_XPU
        TARGET(kXPU),
#endif
        PRECISION(kFloat)};
    if (std::find(valid_places_.begin(), valid_places_.end(), target_place) !=
153
        valid_places_.end()) {
154
#ifdef LITE_WITH_NPU
155 156 157
      auto pass = mir::PassManager::Global()
                      .LookUp<mir::subgraph::GenerateNPUProgramPass>(
                          "generate_npu_program_pass");
158
#endif
159

160 161 162 163 164
#ifdef LITE_WITH_XPU
      auto pass = mir::PassManager::Global()
                      .LookUp<mir::subgraph::GenerateXPUProgramPass>(
                          "generate_xpu_program_pass");
#endif
165 166 167
      try {
        pass->Apply(graph_);
        auto program = pass->GenProgram();
168 169 170
        CHECK(exec_scope_);
        program->set_exec_scope(exec_scope_);
        return program;
171
      } catch (...) {
172 173
        LOG(WARNING) << "Build " << TargetToStr(target_place.target)
                     << " program failed!";
174 175 176
      }
    }
#endif
Y
Yan Chunwei 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    auto pass = mir::PassManager::Global().LookUp<mir::GenerateProgramPass>(
        "generate_program_pass");
    pass->Apply(graph_);
    auto program = pass->GenProgram();
    CHECK(exec_scope_);
    program->set_exec_scope(exec_scope_);
    return program;
  }

  void InitTargetTypeTransformPass() {
    auto* pass =
        mir::PassManager::Global().LookUp<mir::TypeTargetTransformPass>(
            "type_target_cast_pass");
    CHECK(pass);
    CHECK(!valid_places_.empty());
    pass->SetValidPlaces(valid_places_);
  }

  // Generate C++ code which combines the inference program, model and weights.
  void GenCode(const std::string& code_dir);

  const mir::SSAGraph& ssa_graph() const {
    CHECK(graph_);
    return *graph_;
  }

  mir::SSAGraph* mutable_ssa_graph() {
    CHECK(graph_);
    return graph_.get();
  }

  lite::Scope* exec_scope() { return exec_scope_; }

 protected:
  void SpecifyKernelPickTactic(core::KernelPickFactor factor);

  // Specify the passes and run them.
  void RunPasses(const std::vector<std::string>& passes) {
    for (auto& x : passes) {
216 217
      LOG(INFO) << "== Running pass: " << x;
      mir::Pass* pass = mir::PassManager::Global().LookUp(x);
Y
Yan Chunwei 已提交
218
      CHECK(pass) << "Can not find pass: " << x;
219
      bool matched = false;
220
      for (const auto& place : valid_places_) {
221 222
        if (PassMatchesTarget(*pass, place.target)) {
          matched = true;
223 224
        }
      }
225
      matched = matched && PassMatchesKernels(*pass);
226
      if (!matched) {
227 228
        LOG(INFO) << "   - Skip " << x
                  << " because the target or kernel does not match.";
229 230 231 232
      } else {
        pass->Apply(graph_);
        LOG(INFO) << "== Finished running: " << x;
      }
Y
Yan Chunwei 已提交
233 234 235 236 237 238 239 240 241 242 243 244
    }
  }

 private:
  std::unique_ptr<mir::SSAGraph> graph_;
  std::vector<Place> valid_places_;
  lite::Scope* exec_scope_{};
  Program* program_{};
};

}  // namespace lite
}  // namespace paddle