light_api.cc 9.7 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>
17
#include <unordered_map>
18 19
#include "paddle_use_kernels.h"  // NOLINT
#include "paddle_use_ops.h"      // NOLINT
Y
Yan Chunwei 已提交
20 21 22 23

namespace paddle {
namespace lite {

24 25 26 27 28 29 30
void LightPredictor::Build(const std::string& lite_model_file,
                           bool model_from_memory) {
  if (model_from_memory) {
    LoadModelNaiveFromMemory(lite_model_file, scope_.get(), &cpp_program_desc_);
  } else {
    LoadModelNaiveFromFile(lite_model_file, scope_.get(), &cpp_program_desc_);
  }
31

C
cc 已提交
32 33
  // For weight quantization of post training, load the int8/16 weights
  // for optimized model, and dequant it to fp32.
34
  DequantizeWeight();
C
cc 已提交
35

36 37 38 39
  BuildRuntimeProgram(cpp_program_desc_);
  PrepareFeedFetch();
}

Y
Yan Chunwei 已提交
40
void LightPredictor::Build(const std::string& model_dir,
41 42 43 44
                           const std::string& model_buffer,
                           const std::string& param_buffer,
                           lite_api::LiteModelType model_type,
                           bool model_from_memory) {
Y
Yan Chunwei 已提交
45 46 47
  switch (model_type) {
#ifndef LITE_ON_TINY_PUBLISH
    case lite_api::LiteModelType::kProtobuf:
48
      LoadModelPb(model_dir, "", "", scope_.get(), &cpp_program_desc_);
Y
Yan Chunwei 已提交
49 50
      break;
#endif
51 52 53
    case lite_api::LiteModelType::kNaiveBuffer: {
      if (model_from_memory) {
        LoadModelNaiveFromMemory(
54
            model_buffer, param_buffer, scope_.get(), &cpp_program_desc_);
55
      } else {
56
        LoadModelNaive(model_dir, scope_.get(), &cpp_program_desc_);
57
      }
Y
Yan Chunwei 已提交
58
      break;
59
    }
Y
Yan Chunwei 已提交
60 61 62
    default:
      LOG(FATAL) << "Unknown model type";
  }
J
juncaipeng 已提交
63 64

  DequantizeWeight();
65
  BuildRuntimeProgram(cpp_program_desc_);
66
  PrepareFeedFetch();
Y
Yan Chunwei 已提交
67 68 69
}

Tensor* LightPredictor::GetInput(size_t offset) {
70 71 72 73 74 75 76
  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 已提交
77 78
}

79 80
// get input by name
Tensor* LightPredictor::GetInputByName(const std::string& name) {
81 82
  auto element = std::find(input_names_.begin(), input_names_.end(), name);
  if (element == input_names_.end()) {
83 84
    LOG(ERROR) << "Model do not have input named with: [" << name
               << "], model's inputs include:";
85
    for (size_t i = 0; i < input_names_.size(); i++) {
86 87
      LOG(ERROR) << "[" << input_names_[i] << "]";
    }
88
    return nullptr;
89
  } else {
90 91
    int position = std::distance(input_names_.begin(), element);
    return GetInput(position);
92 93 94
  }
}

Y
Yan Chunwei 已提交
95
const Tensor* LightPredictor::GetOutput(size_t offset) {
96 97 98 99 100 101 102
  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 已提交
103
}
104
// get inputs names
S
sangoly 已提交
105
std::vector<std::string> LightPredictor::GetInputNames() {
106
  return input_names_;
107 108
}
// get outputnames
S
sangoly 已提交
109
std::vector<std::string> LightPredictor::GetOutputNames() {
110
  return output_names_;
111 112 113 114
}
// 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);
115 116
  std::vector<cpp::OpDesc*> feeds;
  std::vector<cpp::OpDesc*> fetchs;
117
  for (size_t i = 0; i < current_block->OpsSize(); i++) {
118 119
    auto op = current_block->GetOp<cpp::OpDesc>(i);
    if (op->Type() == "feed") {
120
      feeds.push_back(op);
121
    } else if (op->Type() == "fetch") {
122
      fetchs.push_back(op);
123 124
    }
  }
125 126
  input_names_.resize(feeds.size());
  output_names_.resize(fetchs.size());
127
  for (size_t i = 0; i < feeds.size(); i++) {
128 129 130
    input_names_[feeds[i]->GetAttr<int>("col")] =
        feeds[i]->Output("Out").front();
  }
131
  for (size_t i = 0; i < fetchs.size(); i++) {
132 133 134
    output_names_[fetchs[i]->GetAttr<int>("col")] =
        fetchs[i]->Input("X").front();
  }
135
}
Y
Yan Chunwei 已提交
136 137 138 139 140 141

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

142 143 144 145 146 147
// 2. Create Instructs
#ifdef LITE_WITH_OPENCL
  using OpenCLContext = Context<TargetType::kOpenCL>;
  std::unique_ptr<KernelContext> local_ctx(new KernelContext());
  local_ctx->As<OpenCLContext>().InitOnce();
#endif
Y
Yan Chunwei 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

  // 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());
163 164 165 166 167 168 169 170 171 172

#ifdef LITE_WITH_OPENCL
    if ((*it)->target() == TARGET(kOpenCL)) {
      std::unique_ptr<KernelContext> ctx(new KernelContext());
      (*local_ctx).As<OpenCLContext>().CopySharedTo(&ctx->As<OpenCLContext>());
      (*it)->SetContext(std::move(ctx));
    } else {
      (*it)->SetContext(ContextScheduler::Global().NewContext((*it)->target()));
    }
#else
Y
Yan Chunwei 已提交
173
    (*it)->SetContext(ContextScheduler::Global().NewContext((*it)->target()));
174
#endif
175

Y
Yan Chunwei 已提交
176 177 178
    insts.emplace_back(op, std::move(*it));
  }
  program_.reset(new RuntimeProgram(std::move(insts)));
179

Y
Yan Chunwei 已提交
180 181 182 183
  CHECK(program.exec_scope());
  program_->set_exec_scope(program.exec_scope());
}

J
juncaipeng 已提交
184
void LightPredictor::DequantizeWeight() {
C
cc 已提交
185 186 187 188 189
#define PROCESS_CONV2D_DATA()                                             \
  for (int64_t i = 0; i < ch; ++i) {                                      \
    for (int64_t j = 0; j < offset; ++j) {                                \
      fp_data[i * offset + j] = scale_list[i] * int_data[i * offset + j]; \
    }                                                                     \
J
juncaipeng 已提交
190 191
  }

C
cc 已提交
192 193 194 195 196
#define PROCESS_FC_DATA()                                               \
  for (int64_t i = 0; i < chin; i++) {                                  \
    for (int64_t j = 0; j < chout; j++) {                               \
      fp_data[i * chout + j] = scale_list[j] * int_data[i * chout + j]; \
    }                                                                   \
J
juncaipeng 已提交
197 198
  }

C
cc 已提交
199 200 201 202 203 204 205 206 207 208 209 210
  auto is_weight_quantized_op = [](const cpp::OpDesc* op_desc) {
    bool result = false;
    if (op_desc->HasAttr("quantization_type")) {
      std::string type = op_desc->GetAttr<std::string>("quantization_type");
      result = (type == "post_weight_abs_max") ||
               (type == "post_weight_channel_wise_abs_max");
    } else {
      result = op_desc->HasAttr("quantize_weight_bits");
    }
    return result;
  };

J
juncaipeng 已提交
211
  Tensor tmp_tensor;
C
cc 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  for (size_t i = 0; i < cpp_program_desc_.BlocksSize(); i++) {
    auto* block = cpp_program_desc_.GetBlock<cpp::BlockDesc>(i);
    for (size_t k = 0; k < block->OpsSize(); ++k) {
      auto* op_desc = block->GetOp<cpp::OpDesc>(k);
      if (is_weight_quantized_op(op_desc)) {
        auto input_names = op_desc->input_vars();
        for (auto& input_name : input_names) {
          std::string input_scale_name = input_name + "_quant_scale";
          if (op_desc->HasAttr(input_scale_name)) {  // the input is quantized
            auto input_tensor =
                scope_->FindVar(input_name)->GetMutable<lite::Tensor>();
            tmp_tensor.CopyDataFrom(*input_tensor);
            auto scale_list =
                op_desc->GetAttr<std::vector<float>>(input_scale_name);

            int quantize_weight_bits =
                op_desc->GetAttr<int>("quantize_weight_bits");
            CHECK(quantize_weight_bits == 8 || quantize_weight_bits == 16);
            float* fp_data = input_tensor->mutable_data<float>();

            std::string op_type = op_desc->Type();
            if (op_type == "conv2d" || op_type == "depthwise_conv2d") {
              int64_t ch = input_tensor->dims()[0];
              int64_t offset = input_tensor->numel() / ch;
              CHECK_EQ(scale_list.size(), ch);
              if (quantize_weight_bits == 8) {
                const int8_t* int_data = tmp_tensor.data<int8_t>();
                PROCESS_CONV2D_DATA()
              } else {
                const int16_t* int_data = tmp_tensor.data<int16_t>();
                PROCESS_CONV2D_DATA()
              }
            } else if (op_type == "fc" || op_type == "mul") {
              int64_t chin = input_tensor->dims()[0];
              int64_t chout = input_tensor->dims()[1];
              CHECK_EQ(scale_list.size(), chout);
              if (quantize_weight_bits == 8) {
                const int8_t* int_data = tmp_tensor.data<int8_t>();
                PROCESS_FC_DATA()
              } else {
                const int16_t* int_data = tmp_tensor.data<int16_t>();
                PROCESS_FC_DATA()
              }
J
juncaipeng 已提交
255 256 257 258 259 260 261 262 263 264 265
            }
          }
        }
      }
    }
  }

#undef PROCESS_CONV2D_DATA
#undef PROCESS_FC_DATA
}

Y
Yan Chunwei 已提交
266 267
}  // namespace lite
}  // namespace paddle