light_api.cc 5.1 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/light_api.h"
16
#include <algorithm>
Y
Yan Chunwei 已提交
17 18 19 20 21

namespace paddle {
namespace lite {

void LightPredictor::Build(const std::string& model_dir,
22 23 24 25
                           const std::string& model_buffer,
                           const std::string& param_buffer,
                           lite_api::LiteModelType model_type,
                           bool model_from_memory) {
Y
Yan Chunwei 已提交
26 27 28
  switch (model_type) {
#ifndef LITE_ON_TINY_PUBLISH
    case lite_api::LiteModelType::kProtobuf:
29
      LoadModelPb(model_dir, "", "", scope_.get(), &cpp_program_desc_);
Y
Yan Chunwei 已提交
30 31
      break;
#endif
32 33 34
    case lite_api::LiteModelType::kNaiveBuffer: {
      if (model_from_memory) {
        LoadModelNaiveFromMemory(
35
            model_buffer, param_buffer, scope_.get(), &cpp_program_desc_);
36
      } else {
37
        LoadModelNaive(model_dir, scope_.get(), &cpp_program_desc_);
38
      }
Y
Yan Chunwei 已提交
39
      break;
40
    }
Y
Yan Chunwei 已提交
41 42 43
    default:
      LOG(FATAL) << "Unknown model type";
  }
44
  BuildRuntimeProgram(cpp_program_desc_);
45
  PrepareFeedFetch();
Y
Yan Chunwei 已提交
46 47 48
}

Tensor* LightPredictor::GetInput(size_t offset) {
49 50 51 52 53 54 55
  CHECK(input_names_.size() > offset)
      << "The network has " << input_names_.size() << " inputs"
      << ", the offset should be less than this.";
  auto* in_var = program_->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 已提交
56 57
}

58 59
// get input by name
Tensor* LightPredictor::GetInputByName(const std::string& name) {
60 61
  auto element = std::find(input_names_.begin(), input_names_.end(), name);
  if (element == input_names_.end()) {
62 63 64 65 66
    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] << "]";
    }
67
    return nullptr;
68
  } else {
69 70
    int position = std::distance(input_names_.begin(), element);
    return GetInput(position);
71 72 73
  }
}

Y
Yan Chunwei 已提交
74
const Tensor* LightPredictor::GetOutput(size_t offset) {
75 76 77 78 79 80 81
  CHECK(output_names_.size() > offset)
      << "The network has " << output_names_.size() << " outputs"
      << ", the offset should be less than this.";
  auto* out_var = program_->exec_scope()->FindVar(output_names_.at(offset));
  CHECK(out_var) << "no fatch variable " << output_names_.at(offset)
                 << " in exec_scope";
  return out_var->GetMutable<lite::Tensor>();
Y
Yan Chunwei 已提交
82
}
83
// get inputs names
84 85
const std::vector<std::string>& LightPredictor::GetInputNames() {
  return input_names_;
86 87
}
// get outputnames
88 89
const std::vector<std::string>& LightPredictor::GetOutputNames() {
  return output_names_;
90 91 92 93
}
// append the names of inputs and outputs into input_names_ and output_names_
void LightPredictor::PrepareFeedFetch() {
  auto current_block = cpp_program_desc_.GetBlock<cpp::BlockDesc>(0);
94 95
  std::vector<cpp::OpDesc*> feeds;
  std::vector<cpp::OpDesc*> fetchs;
96 97 98
  for (int i = 0; i < current_block->OpsSize(); i++) {
    auto op = current_block->GetOp<cpp::OpDesc>(i);
    if (op->Type() == "feed") {
99
      feeds.push_back(op);
100
    } else if (op->Type() == "fetch") {
101
      fetchs.push_back(op);
102 103
    }
  }
104 105 106 107 108 109 110 111 112 113
  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();
  }
114
}
Y
Yan Chunwei 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

void LightPredictor::BuildRuntimeProgram(const cpp::ProgramDesc& prog) {
  std::vector<Instruction> insts;
  // 1. Create op first
  Program program(prog, scope_, {});

  // 2. Create Instructs

  // Create the kernels of the target places, and filter out the specific
  // kernel with the target alias.
  for (auto& op : program.ops()) {
    auto kernel_type = op->op_info()->GetAttr<std::string>(kKernelTypeAttr);
    std::string op_type, alias;
    Place place;
    KernelBase::ParseKernelType(kernel_type, &op_type, &alias, &place);
    auto kernels = op->CreateKernels({place});
    // filter out a kernel
    auto it = std::find_if(
        kernels.begin(), kernels.end(), [&](std::unique_ptr<KernelBase>& it) {
          return it->alias() == alias;
        });
    CHECK(it != kernels.end());
    (*it)->SetContext(ContextScheduler::Global().NewContext((*it)->target()));
138

Y
Yan Chunwei 已提交
139 140 141
    insts.emplace_back(op, std::move(*it));
  }
  program_.reset(new RuntimeProgram(std::move(insts)));
142

Y
Yan Chunwei 已提交
143 144 145 146 147 148
  CHECK(program.exec_scope());
  program_->set_exec_scope(program.exec_scope());
}

}  // namespace lite
}  // namespace paddle