cxx_api.cc 7.5 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.

#include "lite/api/cxx_api.h"
16
#include <algorithm>
Y
Yan Chunwei 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "lite/utils/io.h"

namespace paddle {
namespace lite {

void Predictor::SaveModel(const std::string &dir,
                          lite_api::LiteModelType model_type) {
  if (!program_) {
    GenRuntimeProgram();
  }
  program_->SaveOpInfosToProgram(&program_desc_);
32
  program_->UpdateVarsOfProgram(&program_desc_);
Y
Yan Chunwei 已提交
33 34
  switch (model_type) {
    case lite_api::LiteModelType::kProtobuf:
35
      SaveModelPb(dir, *program_->exec_scope(), program_desc_, true);
Y
Yan Chunwei 已提交
36 37 38 39 40 41 42 43 44 45
      break;
    case lite_api::LiteModelType::kNaiveBuffer:
      SaveModelNaive(dir, *program_->exec_scope(), program_desc_);
      break;
    default:
      LOG(FATAL) << "Unknown model type";
  }
}

lite::Tensor *Predictor::GetInput(size_t offset) {
46 47 48 49 50 51 52
  CHECK(input_names_.size() > offset)
      << "The network has " << input_names_.size() << " inputs"
      << ", the offset should be less than this.";
  auto *in_var = exec_scope_->FindVar(input_names_[offset]);
  CHECK(in_var) << "no fatch variable " << input_names_[offset]
                << " in exec_scope";
  return in_var->GetMutable<lite::Tensor>();
Y
Yan Chunwei 已提交
53 54
}

55
// get inputs names
56 57
const std::vector<std::string> &Predictor::GetInputNames() {
  return input_names_;
58 59
}
// get outputnames
60 61
const std::vector<std::string> &Predictor::GetOutputNames() {
  return output_names_;
62 63 64 65
}
// append the names of inputs and outputs into input_names_ and output_names_
void Predictor::PrepareFeedFetch() {
  auto current_block = program_desc_.GetBlock<cpp::BlockDesc>(0);
66 67
  std::vector<cpp::OpDesc *> feeds;
  std::vector<cpp::OpDesc *> fetchs;
68 69 70
  for (int i = 0; i < current_block->OpsSize(); i++) {
    auto op = current_block->GetOp<cpp::OpDesc>(i);
    if (op->Type() == "feed") {
71
      feeds.push_back(op);
72
    } else if (op->Type() == "fetch") {
73
      fetchs.push_back(op);
74 75
    }
  }
76 77 78 79 80 81 82 83 84 85
  input_names_.resize(feeds.size());
  output_names_.resize(fetchs.size());
  for (int i = 0; i < feeds.size(); i++) {
    input_names_[feeds[i]->GetAttr<int>("col")] =
        feeds[i]->Output("Out").front();
  }
  for (int i = 0; i < fetchs.size(); i++) {
    output_names_[fetchs[i]->GetAttr<int>("col")] =
        fetchs[i]->Input("X").front();
  }
86 87
}

Y
Yan Chunwei 已提交
88
const lite::Tensor *Predictor::GetOutput(size_t offset) const {
89 90 91 92 93 94 95
  CHECK(output_names_.size() > offset)
      << "The network has " << output_names_.size() << " outputs"
      << ", the offset should be less than this.";
  const std::string name = output_names_.at(offset);
  auto *out_var = exec_scope_->FindVar(name);
  CHECK(out_var) << "no fatch variable " << name << " in exec_scope";
  return out_var->GetMutable<lite::Tensor>();
Y
Yan Chunwei 已提交
96 97
}

98 99 100 101 102 103 104 105
std::vector<const lite::Tensor *> Predictor::GetOutputs() const {
  std::vector<const lite::Tensor *> outputs;
  size_t out_size = output_names_.size();
  for (size_t i = 0; i < out_size; i++) {
    const std::string name = output_names_.at(i);
    outputs.push_back(GetTensor(name));
  }
  return outputs;
T
TianXiaogang 已提交
106 107
}

Y
Yan Chunwei 已提交
108 109 110 111 112
const cpp::ProgramDesc &Predictor::program_desc() const {
  return program_desc_;
}
const RuntimeProgram &Predictor::runtime_program() const { return *program_; }

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
void Predictor::Build(const lite_api::CxxConfig &config,
                      const std::vector<Place> &valid_places,
                      const std::vector<std::string> &passes,
                      lite_api::LiteModelType model_type) {
  const std::string &model_path = config.model_dir();
  const std::string &model_file = config.model_file();
  const std::string &param_file = config.param_file();
  const bool model_from_memory = config.model_from_memory();
  LOG(INFO) << "load from memory " << model_from_memory;

  Build(model_path,
        model_file,
        param_file,
        valid_places,
        passes,
        model_type,
        model_from_memory);
}
Y
Yan Chunwei 已提交
131
void Predictor::Build(const std::string &model_path,
132 133
                      const std::string &model_file,
                      const std::string &param_file,
Y
Yan Chunwei 已提交
134 135
                      const std::vector<Place> &valid_places,
                      const std::vector<std::string> &passes,
136 137
                      lite_api::LiteModelType model_type,
                      bool model_from_memory) {
Y
Yan Chunwei 已提交
138
  switch (model_type) {
139 140 141 142 143 144 145 146 147 148
    case lite_api::LiteModelType::kProtobuf: {
      bool combined_param = false;
      if (!model_file.empty() && !param_file.empty()) {
        combined_param = true;
      }
      LoadModelPb(model_path,
                  model_file,
                  param_file,
                  scope_.get(),
                  &program_desc_,
149 150
                  combined_param,
                  model_from_memory);
151
    } break;
Y
Yan Chunwei 已提交
152
    case lite_api::LiteModelType::kNaiveBuffer:
153 154
      CHECK(!model_path.empty())
          << "NaiveBuffer backend only supported combined param";
Y
Yan Chunwei 已提交
155 156 157 158 159
      LoadModelNaive(model_path, scope_.get(), &program_desc_);
      break;
    default:
      LOG(FATAL) << "Unknown model type";
  }
160
  Build(program_desc_, valid_places, passes);
Y
Yan Chunwei 已提交
161 162 163 164 165 166
}

void Predictor::Build(const cpp::ProgramDesc &desc,
                      const std::vector<Place> &valid_places,
                      const std::vector<std::string> &passes) {
  program_desc_ = desc;
167 168 169 170 171 172
  std::vector<Place> inner_places = valid_places;
  inner_places.emplace_back(TARGET(kHost), PRECISION(kAny), DATALAYOUT(kAny));
  inner_places.emplace_back(
      TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kNCHW));
  Program program(desc, scope_, inner_places);
  /// The first place in valid_places is
Y
Yan Chunwei 已提交
173 174 175
  core::KernelPickFactor factor;
  factor.ConsiderTarget();
  factor.ConsiderPrecision();
176
  factor.ConsiderDataLayout();
177
  optimizer_.Run(std::move(program), inner_places, factor, passes);
Y
Yan Chunwei 已提交
178
  exec_scope_ = optimizer_.exec_scope();
179
  PrepareFeedFetch();
Y
Yan Chunwei 已提交
180 181 182 183 184 185 186 187 188 189 190 191
}

void Predictor::GenRuntimeProgram() {
  program_ = optimizer_.GenRuntimeProgram();
  CHECK_EQ(exec_scope_, program_->exec_scope());
  program_generated_ = true;
}

const lite::Tensor *Predictor::GetTensor(const std::string &name) const {
  auto *var = exec_scope_->FindVar(name);
  return &var->Get<lite::Tensor>();
}
192 193
// get input by name
lite::Tensor *Predictor::GetInputByName(const std::string &name) {
194 195
  auto element = std::find(input_names_.begin(), input_names_.end(), name);
  if (element == input_names_.end()) {
196 197 198 199 200
    LOG(ERROR) << "Model do not have input named with: [" << name
               << "], model's inputs include:";
    for (int i = 0; i < input_names_.size(); i++) {
      LOG(ERROR) << "[" << input_names_[i] << "]";
    }
201
    return nullptr;
202
  } else {
203 204
    int position = std::distance(input_names_.begin(), element);
    return GetInput(position);
205 206
  }
}
Y
Yan Chunwei 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220

#ifdef LITE_WITH_TRAIN
void Predictor::FeedVars(const std::vector<framework::Tensor> &tensors) {
  auto var = scope_->FindVar("feed");
  auto &feed_list = *(var->GetMutable<std::vector<lite::Tensor>>());
  feed_list.resize(tensors.size());

  for (size_t i = 0; i < tensors.size(); ++i)
    feed_list[i].ShareDataWith(tensors[i]);
}
#endif

}  // namespace lite
}  // namespace paddle