executor.cpp 39.2 KB
Newer Older
W
wangliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

H
hjchen2 已提交
15
#include "framework/executor.h"
D
dolphin8 已提交
16
#include <algorithm>
17
#include <unordered_map>
18
#include <utility>
W
wangliu 已提交
19
#include <vector>
L
liuruilong 已提交
20
#include "common/enforce.h"
L
liuruilong 已提交
21
#include "common/log.h"
22
#include "framework/context.h"
L
liuruilong 已提交
23
#include "framework/framework.pb-c.h"
L
liuruilong 已提交
24 25
#include "framework/lod_tensor.h"
#include "framework/operator.h"
L
liuruilong 已提交
26
#include "framework/program/program-optimize/program_optimize.h"
L
liuruilong 已提交
27 28 29 30
#include "framework/program/program_desc.h"
#include "framework/program/var_desc.h"
#include "framework/scope.h"
#include "framework/tensor.h"
H
hjchen2 已提交
31
#include "memory/t_malloc.h"
32
#include "pass/memory_optimize.h"
33
#include "pass/model_obfuscate.h"
L
update  
liuruilong 已提交
34 35
#ifdef PADDLE_MOBILE_CL
#include "framework/cl/cl_image.h"
36
#include "pass/memory_optimize_cl.h"
L
update  
liuruilong 已提交
37
#endif
W
wangliu 已提交
38 39

namespace paddle_mobile {
40
namespace framework {
41

W
wangliu 已提交
42 43
#pragma mark - executor

44
template <typename Device, typename T>
45 46
void Executor<Device, T>::SetThreadNum(int thread_num, PowerMode power_mode) {
  CPUContext::Context()->set_thread_num(thread_num, power_mode);
47 48
}

49
template <typename Device, typename T>
xiebaiyuan's avatar
xiebaiyuan 已提交
50 51 52 53
Executor<Device, T>::Executor(const Program<Device> &program,
                              paddle_mobile::PaddleMobileConfigInternal config,
                              int batch_size, const bool use_optimize,
                              const bool lod_mode)
54
    : program_(program),
H
hjchen2 已提交
55 56
      batch_size_(batch_size),
      use_optimize_(use_optimize),
xiebaiyuan's avatar
xiebaiyuan 已提交
57 58
      lod_mode_(lod_mode),
      config_(config) {
59
  DLOG << "executor in lod mode: " << lod_mode;
60

W
wangliu 已提交
61
  Variable *variable_ptr = program_.scope->Var("batch_size");
H
hjchen2 已提交
62
  variable_ptr->SetValue<int>(batch_size);
63 64

  program_desc_ =
Refine  
陈后江 已提交
65
      use_optimize_ ? program_.optimizeProgram : program_.originProgram;
66 67
  PADDLE_MOBILE_ENFORCE(program_desc_ != nullptr,
                        "program_desc_ should not be nullptr");
C
Chon 已提交
68 69
#if !defined(PADDLE_MOBILE_FPGA) && !defined(PADDLE_MOBILE_FPGA_KD) && \
    !defined(PADDLE_MOBILE_CL)
70
  if (config_.memory_optimization_level != NoMemoryOptimization) {
71 72
    pass::MemoryOptPass()(program_desc_.get(), program_.scope.get(),
                          config_.memory_optimization_level);
Y
Yanzhan Yang 已提交
73
  }
74
#endif
75 76 77 78
  // resize feed and fetch list
  // should init feed and fetch variables before infer shape
  InitFeedFetchList();
  const auto &blocks = program_desc_->Blocks();
79 80 81 82
  std::shared_ptr<BlockDesc> block_desc = blocks[0];
  std::vector<std::shared_ptr<OpDesc>> ops = block_desc->Ops();
  for (int j = 0; j < ops.size(); ++j) {
    std::shared_ptr<OpDesc> op_desc = ops[j];
83
    LOG(kLOG_INFO) << "create op[" << j << "]: " << op_desc->Type();
84 85 86

    auto op_handler = OpRegistry<Device>::CreateOp(
        op_desc->Type(), op_desc->GetInputs(), op_desc->GetOutputs(),
87
        op_desc->GetAttrMap(), program_.scope.get());
88 89 90 91
    // infer shape to reshape inputs and outputs before predict,
    // but for lod mode, it still need to infer shape in runtime
    if (!lod_mode) {
      op_handler->InferShape();
W
wangliu 已提交
92
    }
93
    ops_of_block0_.push_back(op_handler);
W
wangliu 已提交
94
  }
95 96 97
#ifdef PADDLE_MOBILE_FPGA_V2
  InitQuantMemory();
#endif
W
wangliu 已提交
98
  if (program_.combined) {
L
liuruilong 已提交
99 100 101 102
    InitCombineMemory();
  } else {
    InitMemory();
  }
103
  int count = 0;
Z
zp7 已提交
104
#ifdef PADDLE_MOBILE_PROFILE
105 106 107
  std::vector<ProfInfo> profile(ops_of_block0_.size());
  struct timespec ts;
  int op_index = 0;
Z
zp7 已提交
108
#endif
109
  for (auto &op_handler : ops_of_block0_) {
Z
zp7 已提交
110 111 112 113
#ifdef PADDLE_MOBILE_PROFILE
    clock_gettime(CLOCK_MONOTONIC, &ts);
    profile[op_index].runBegin = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
#endif
114 115
    LOG(kLOG_INFO) << "Initialize op[" << count++
                   << "]: " << op_handler->Type();
116 117 118
    if (op_handler->Type() == "feed" || op_handler->Type() == "fetch") {
      op_handler->setPrePostType(config_.pre_post_type);
    }
119
    op_handler->Init();
Z
zp7 已提交
120 121
#ifdef PADDLE_MOBILE_PROFILE
    clock_gettime(CLOCK_MONOTONIC, &ts);
122 123
    profile[op_index].runEnd = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
    ++op_index;
Z
zp7 已提交
124
#endif
L
liuruilong 已提交
125
  }
Z
zp7 已提交
126 127 128 129
#ifdef PADDLE_MOBILE_PROFILE
  printf("================[ op init profile ]==================\n");
  PrintProfile(profile);
#endif
130 131 132 133 134 135
  ApplyMemoryOptimise(config, lod_mode);
}

template <typename Device, typename T>
void Executor<Device, T>::ApplyMemoryOptimise(
    const PaddleMobileConfigInternal &config, const bool lod_mode) const {}
136 137

#ifdef PADDLE_MOBILE_CL
138 139 140
template <>
void Executor<GPU_CL, float>::ApplyMemoryOptimise(
    const PaddleMobileConfigInternal &config, const bool lod_mode) const {
141 142 143 144 145
  if (!config.load_when_predict && !lod_mode &&
      config_.memory_optimization_level != NoMemoryOptimization) {
    pass::MemoryOptPassCl()(program_desc_.get(), program_.scope.get(),
                            config_.memory_optimization_level);
  }
W
wangliu 已提交
146
}
147
#endif
W
wangliu 已提交
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
template <typename Device, typename T>
void Executor<Device, T>::InitFeedFetchList() {
  std::unordered_map<std::string, int> feed_indices, fetch_indices;
  for (const auto &block : program_desc_->Blocks()) {
    for (const auto &op_desc : block->Ops()) {
      if (op_desc->Type() == "feed") {
        std::string name = op_desc->Output("Out")[0];
        feed_indices[name] = op_desc->GetAttr("col").Get<int>();
      } else if (op_desc->Type() == "fetch") {
        std::string name = op_desc->Input("X")[0];
        fetch_indices[name] = op_desc->GetAttr("col").Get<int>();
      }
    }
  }
  feed_indices_.swap(feed_indices);
  fetch_indices_.swap(fetch_indices);

  auto *feed_var = program_.scope->Var("feed");
  auto *feed_list = feed_var->template GetMutable<framework::LoDTensorArray>();
  feed_list->resize(feed_indices_.size());

  auto *fetch_var = program_.scope->Var("fetch");
  auto *fetch_list =
      fetch_var->template GetMutable<framework::LoDTensorArray>();
  fetch_list->resize(fetch_indices_.size());
}

176
template <typename T>
177 178 179 180
static void LoadMemInternal(void **in_data, void *out_data, int64_t size,
                            bool quant_uint8 = false, int quant_fold = 1) {
  char **data_buf = reinterpret_cast<char **>(in_data);
  T *tensor_data = reinterpret_cast<T *>(out_data);
181
  if (quant_uint8) {
182 183
    const int minimal_fold_size = 2;
    quant_fold = fmin(fmax(1, size / minimal_fold_size), quant_fold);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    int step = fmax(size / quant_fold, 1);
    int visited_fold = 0;
    while (visited_fold * step < size) {
      // should be moved into operator init function
      float min_value;
      float max_value;
      memory::Copy(&min_value, *data_buf, sizeof(float));
      memory::Copy(&max_value, *data_buf + sizeof(float), sizeof(float));
      *data_buf += 2 * sizeof(float);
      const float factor = (max_value - min_value) / 255.0;
      const uint8_t *uint8_data = reinterpret_cast<uint8_t *>(*data_buf);
      int k = 0;
      for (; k < step; ++k) {
        int tensor_data_idx = visited_fold * step + k;
        if (tensor_data_idx >= size) {
          break;
        }
        tensor_data[tensor_data_idx] = uint8_data[k] * factor + min_value;
      }
      *data_buf += k * sizeof(uint8_t);
      visited_fold++;
W
wangliu 已提交
205
    }
206
  } else {
207 208
    memory::Copy(tensor_data, *data_buf, size * sizeof(T));
    *data_buf += size * sizeof(T);
L
liuruilong 已提交
209
  }
210
}
W
wangliu 已提交
211

212 213 214 215
template <typename Device, typename T>
void Executor<Device, T>::LoadMemory(void **data,
                                     const std::shared_ptr<VarDesc> var_desc,
                                     LoDTensor *tensor) {
216
  char **data_buf = reinterpret_cast<char **>(data);
217
  // version
218
  uint32_t version = *(reinterpret_cast<uint32_t *>(*data_buf));
Refine  
陈后江 已提交
219
  *data_buf += sizeof(uint32_t);
220
  // lod information
H
hjchen2 已提交
221 222
  // uint64_t lod_level = *(reinterpret_cast<uint64_t *>(*data_buf));
  uint64_t lod_level = 0;
Z
zhangyang 已提交
223
  memory::Copy(&lod_level, *data_buf, sizeof(uint64_t));
Refine  
陈后江 已提交
224
  *data_buf += sizeof(uint64_t);
225 226 227 228

  auto *lod = tensor->mutable_lod();
  lod->resize(lod_level);
  for (uint64_t i = 0; i < lod_level; ++i) {
229
    uint64_t size = *(reinterpret_cast<uint64_t *>(*data_buf));
Refine  
陈后江 已提交
230
    *data_buf += sizeof(uint64_t);
231
    std::vector<size_t> tmp_dim(size / sizeof(size_t));
Z
zhangyang 已提交
232
    memory::Copy(tmp_dim.data(), *data_buf, size);
233
    (*lod)[i] = std::move(tmp_dim);
Refine  
陈后江 已提交
234
    *data_buf += size;
W
wangliu 已提交
235
  }
236
  // tensor version
237
  uint32_t tensor_version = *(reinterpret_cast<uint32_t *>(*data_buf));
Refine  
陈后江 已提交
238
  *data_buf += sizeof(uint32_t);
239
  // tensor desc size
240
  int32_t tensor_desc_size = *(reinterpret_cast<int32_t *>(*data_buf));
Refine  
陈后江 已提交
241
  *data_buf += sizeof(int32_t);
242
  // skip tensor desc
Refine  
陈后江 已提交
243
  *data_buf += tensor_desc_size;
244

245 246
  const TensorDesc &tensor_desc = var_desc->Tensor_desc();
  tensor->Resize(make_ddim(tensor_desc.Dims()));
247 248
  // parse tensor from stream
  switch (tensor_desc.DataType()) {
249
    case VARTYPE_TYPE_FP32:
250 251 252 253
      LoadMemInternal<float>(
          reinterpret_cast<void **>(data_buf),
          reinterpret_cast<void *>(tensor->mutable_data<T>()), tensor->numel(),
          program_.quantification, program_.quantification_fold);
W
wangliu 已提交
254
      break;
255
    case VARTYPE_TYPE_INT8:
256 257 258
      LoadMemInternal<int8_t>(
          reinterpret_cast<void **>(data_buf),
          reinterpret_cast<void *>(tensor->mutable_data<T>()), tensor->numel());
W
wangliu 已提交
259
      break;
260
    case VARTYPE_TYPE_INT32:
261 262 263
      LoadMemInternal<int>(reinterpret_cast<void **>(data_buf),
                           reinterpret_cast<void *>(tensor->mutable_data<T>()),
                           tensor->numel());
W
wangliu 已提交
264 265
      break;
    default:
266
      LOG(kLOG_ERROR) << "data type is not supported";
L
liuruilong 已提交
267
  }
W
wangliu 已提交
268 269
}

270 271 272
template <typename Device, typename T>
void Executor<Device, T>::InitMemory() {
  for (const auto &block : program_desc_->Blocks()) {
W
wangliu 已提交
273 274 275 276
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
      if (var_desc->Persistable()) {
        if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
H
update  
hjchen2 已提交
277
          var->template GetMutable<framework::LoDTensorArray>();
W
wangliu 已提交
278 279
          continue;
        }
H
hjchen2 已提交
280
        DLOG << "init persistable var: " << var_desc->Name();
Refine  
陈后江 已提交
281
        char *origin_data =
Refine  
陈后江 已提交
282
            ReadFileToBuff(program_.model_path + "/" + var_desc->Name());
Refine  
陈后江 已提交
283
        char *data = origin_data;
H
update  
hjchen2 已提交
284
        auto tensor = var->template GetMutable<LoDTensor>();
285 286
        LoadMemory(reinterpret_cast<void **>(&data), var_desc, tensor);
        delete[] origin_data;
W
wangliu 已提交
287
      } else {
288
        DLOG << "init no persistable var: " << var_desc->Name();
H
update  
hjchen2 已提交
289
        varInputMemory(var_desc, var);
W
wangliu 已提交
290 291 292 293 294
      }
    }
  }
}

295 296
template <typename Device, typename T>
void Executor<Device, T>::InitCombineMemory() {
Refine  
陈后江 已提交
297
  char *origin_data = nullptr;
Refine  
陈后江 已提交
298
  bool self_alloc = false;
299
  if (program_.combined_params_buf && program_.combined_params_len) {
300 301
    origin_data = reinterpret_cast<char *>(
        const_cast<uint8_t *>(program_.combined_params_buf));
302 303 304 305
    if (config_.model_obfuscate_key != "") {
      auto obfuscator = pass::ModelObfuscatePass(config_.model_obfuscate_key);
      obfuscator.convert_data(origin_data, program_.combined_params_len);
    }
306
  } else {
Refine  
陈后江 已提交
307
    self_alloc = true;
Refine  
陈后江 已提交
308
    origin_data = ReadFileToBuff(program_.para_path);
309 310 311 312
    if (config_.model_obfuscate_key != "") {
      auto obfuscator = pass::ModelObfuscatePass(config_.model_obfuscate_key);
      obfuscator.convert_data(origin_data, GetFileLength(program_.para_path));
    }
313
  }
Refine  
陈后江 已提交
314 315
  PADDLE_MOBILE_ENFORCE(origin_data != nullptr, "data == nullptr");
  char *data = origin_data;
316
  for (const auto &block : program_desc_->Blocks()) {
L
liuruilong 已提交
317 318 319 320
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
      if (var_desc->Persistable()) {
        if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
H
update  
hjchen2 已提交
321
          var->template GetMutable<framework::LoDTensorArray>();
L
liuruilong 已提交
322 323
          continue;
        }
L
liuruilong 已提交
324 325

        DLOG << " init combine memory persistable: " << var_desc->Name();
H
update  
hjchen2 已提交
326
        auto tensor = var->template GetMutable<LoDTensor>();
327
        LoadMemory(reinterpret_cast<void **>(&data), var_desc, tensor);
L
liuruilong 已提交
328
      } else {
H
update  
hjchen2 已提交
329 330
        DLOG << " init combine memory no persistable: " << var_desc->Name();
        varInputMemory(var_desc, var);
L
liuruilong 已提交
331 332 333
      }
    }
  }
Refine  
陈后江 已提交
334
  if (self_alloc) {
335
    delete[] origin_data;
Refine  
陈后江 已提交
336 337
  }
  LOG(kLOG_INFO) << "init combine memory finish";
L
liuruilong 已提交
338
}
339

C
Chon 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353
static void ClearNoPersistableTensorArray(const framework::ProgramDesc *program,
                                          framework::Scope *scope) {
  for (const auto &block : program->Blocks()) {
    for (const auto &var_desc : block->Vars()) {
      if (!var_desc->Persistable() &&
          var_desc->Type() == VARTYPE_TYPE_STEP_LOD_TENSOR_ARRAY) {
        auto var = scope->Var(var_desc->Name());
        auto array = var->template GetMutable<framework::LoDTensorArray>();
        array->resize(1);
      }
    }
  }
}

L
liuruilong 已提交
354
template <typename Device, typename T>
L
liuruilong 已提交
355
void Executor<Device, T>::InitNoPersistableMemory(const Tensor &input_tensor) {
356 357 358
  if (input_tensor.dims().size() != 4) {
    return;
  }
L
liuruilong 已提交
359 360 361
  for (const auto &block : program_desc_->Blocks()) {
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
362 363 364 365 366
      if (!var_desc->Persistable() &&
          var_desc->Type() == VARTYPE_TYPE_LOD_TENSOR) {
        DLOG << "InitNoPersistableMemory var " << var_desc->Name();
        auto tensor = var->template GetMutable<LoDTensor>();
        if (tensor->IsInitialized() && tensor->dims().size() == 4) {
367 368 369 370
          // don't change user's input and avoid memory leaks
          if (feed_indices_.find(var_desc->Name()) != feed_indices_.end()) {
            break;
          }
L
liuruilong 已提交
371
          DDim tensor_dim = tensor->dims();
xiebaiyuan's avatar
xiebaiyuan 已提交
372 373 374 375
          DDim new_dim =
              make_ddim({tensor_dim[0], tensor_dim[1], input_tensor.dims()[2],
                         input_tensor.dims()[3]});
          tensor->Resize(new_dim);
376 377 378
          tensor->template mutable_data_new<T>();
          DLOG << "var's tensor dims " << tensor_dim;
          DLOG << "var's tensor new dims " << new_dim;
H
update  
hjchen2 已提交
379
        } else {
380
          DLOG << "var's tensor is not Initialized ???";
L
liuruilong 已提交
381 382 383 384 385 386
        }
      }
    }
  }
}

387 388
template <typename Device, typename T>
bool Executor<Device, T>::varInputMemory(
H
update  
hjchen2 已提交
389
    const std::shared_ptr<VarDesc> &var_desc, Variable *var) const {
390
#ifdef PADDLE_MOBILE_FPGA
H
hjchen2 已提交
391
  framework::LoDTensor *tensor = var->template GetMutable<LoDTensor>();
392 393 394
#ifdef PADDLE_MOBILE_FPGA_V2
  tensor->init(type_id<int8_t>().hash_code());
#else
395
  tensor->init(type_id<float>().hash_code());
396
#endif
397 398
  return true;
#endif
H
update  
hjchen2 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411

  auto type = var_desc->Type();
  if (type == VARTYPE_TYPE_LOD_TENSOR) {
    auto data_type = var_desc->Tensor_desc().DataType();
    framework::LoDTensor *tensor = var->template GetMutable<LoDTensor>();
  } else if (type == VARTYPE_TYPE_STEP_SCOPES) {
    std::vector<framework::Scope *> *step_scopes =
        var->template GetMutable<std::vector<framework::Scope *>>();
  } else if (type == VARTYPE_TYPE_STEP_LOD_TENSOR_ARRAY) {
    framework::LoDTensorArray *tensor_array =
        var->template GetMutable<framework::LoDTensorArray>();
  } else {
    PADDLE_MOBILE_THROW_EXCEPTION("got unhandled var type `%d`", type);
xiebaiyuan's avatar
xiebaiyuan 已提交
412
  }
H
update  
hjchen2 已提交
413
  return true;
xiebaiyuan's avatar
xiebaiyuan 已提交
414
}
L
liuruilong 已提交
415

416 417 418 419 420
template <typename Device, typename T>
PMStatus Executor<Device, T>::Predict(
    const std::vector<std::pair<std::string, Tensor>> &inputs) {
  for (const auto &input : inputs) {
    SetInput(input.second, input.first);
D
dolphin8 已提交
421
  }
422 423 424 425 426 427 428 429
  return this->Predict();
}

template <typename Device, typename T>
PMStatus Executor<Device, T>::Predict(
    const std::vector<std::pair<std::string, LoDTensor>> &inputs) {
  for (const auto &input : inputs) {
    SetInput(input.second, input.first);
D
dolphin8 已提交
430
  }
431
  return this->Predict();
W
wangliu 已提交
432
}
xiebaiyuan's avatar
xiebaiyuan 已提交
433

434 435 436
template <typename Device, typename T>
std::vector<T> Executor<Device, T>::Predict(const std::vector<T> &input,
                                            const std::vector<int64_t> &dims) {
437 438 439 440 441 442 443
  PADDLE_MOBILE_ENFORCE(feed_indices_.size() != 0,
                        "We don't know which tensor should be assign, since no "
                        "feed op found in this model");
  PADDLE_MOBILE_ENFORCE(fetch_indices_.size() != 0,
                        "We don't know which tensor should be fetch out, since "
                        "no fetch op found in this model");
  std::string input_name = feed_indices_.begin()->first;
444
  Tensor feed_tensor(input, make_ddim(dims));
445
  SetInput(feed_tensor, input_name);
446 447
  std::vector<T> output;
  if (this->Predict() == PMSuccess) {
448 449
    std::string output_name = fetch_indices_.begin()->first;
    const auto output_tensor = GetOutput(output_name);
450 451 452 453 454 455
    output.resize(output_tensor->numel());
    memcpy(output.data(), output_tensor->template data<T>(),
           output.size() * sizeof(T));
  }
  return output;
}
xiebaiyuan's avatar
xiebaiyuan 已提交
456

457 458 459
template <typename Device, typename T>
void Executor<Device, T>::SetInput(const Tensor &input,
                                   const std::string &var_name) {
H
hjchen2 已提交
460
  int index = 0;
461
  if (feed_indices_.find(var_name) != feed_indices_.end()) {
H
hjchen2 已提交
462
    index = feed_indices_.find(var_name)->second;
463
  }
H
hjchen2 已提交
464 465 466 467 468 469
  auto *feed_var = program_.scope->Var("feed");
  framework::LoDTensor &target =
      feed_var->template GetMutable<framework::LoDTensorArray>()->at(index);

  target.Resize(input.dims());
  target.ShareDataWith(input);
470 471
  if (feed_indices_.size() == 1) {
    auto &dim = input.dims();
472 473 474
    if (lod_mode_ && product(dim) < 0.9 * product(input_dim_last_)) {
      InitNoPersistableMemory(target);
    }
475 476 477
    input_dim_has_changed_ = input_dim_last_ != dim;
    input_dim_last_ = static_cast<DDim>(dim);
  }
478
}
xiebaiyuan's avatar
xiebaiyuan 已提交
479

480 481 482
template <typename Device, typename T>
void Executor<Device, T>::SetInput(const LoDTensor &input,
                                   const std::string &var_name) {
H
hjchen2 已提交
483
  int index = 0;
484
  if (feed_indices_.find(var_name) != feed_indices_.end()) {
H
hjchen2 已提交
485
    index = feed_indices_.find(var_name)->second;
486
  }
H
hjchen2 已提交
487 488 489 490 491 492 493
  auto *feed_var = program_.scope->Var("feed");
  framework::LoDTensor &target =
      feed_var->template GetMutable<framework::LoDTensorArray>()->at(index);

  target.Resize(input.dims());
  target.ShareDataWith(input);
  target.set_lod(input.lod());
494 495
  if (feed_indices_.size() == 1) {
    auto &dim = input.dims();
496 497 498
    if (lod_mode_ && product(dim) < 0.9 * product(input_dim_last_)) {
      InitNoPersistableMemory(target);
    }
499 500 501
    input_dim_has_changed_ = input_dim_last_ != dim;
    input_dim_last_ = static_cast<DDim>(dim);
  }
502 503 504 505 506
}

template <typename Device, typename T>
std::shared_ptr<LoDTensor> Executor<Device, T>::GetOutput(
    const std::string &var_name) {
507 508 509 510 511 512 513 514 515
  const auto &iter = fetch_indices_.find(var_name);
  if (var_name == "fetch" || iter != fetch_indices_.end()) {
    int index = 0;
    if (iter != fetch_indices_.end()) {
      index = iter->second;
    }
    auto *fetch_var = program_.scope->Var("fetch");
    framework::LoDTensor &target =
        fetch_var->template GetMutable<framework::LoDTensorArray>()->at(index);
H
hjchen2 已提交
516

517 518 519 520 521 522 523
    return std::make_shared<LoDTensor>(target);
  } else {
    auto *fetch_var = program_.scope->Var(var_name);
    framework::LoDTensor *target =
        fetch_var->template GetMutable<framework::LoDTensor>();
    return std::make_shared<LoDTensor>(*target);
  }
524
}
xiebaiyuan's avatar
xiebaiyuan 已提交
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539
#ifdef PADDLE_MOBILE_CL
template <typename Device, typename T>
const CLImage *Executor<Device, T>::GetOutputImage(
    const std::string &var_name) {
  auto var = program_.scope->FindVar(var_name);
  if (var->IsInitialized() && var->template IsType<framework::CLImage>()) {
    const CLImage *cl_image = var->template Get<framework::CLImage>();
    return cl_image;
  } else {
    return nullptr;
  }
}
#endif

540 541
template <typename Device, typename T>
PMStatus Executor<Device, T>::Predict() {
542
  try {
543
#if _OPENMP
544
    omp_set_num_threads(CPUContext::Context()->get_thread_num());
545
#endif
546 547 548
    // clear all no persistable tensor array since write_to_array
    // is always push back a new tensor in the array
    ClearNoPersistableTensorArray(program_desc_.get(), program_.scope.get());
549

xiebaiyuan's avatar
xiebaiyuan 已提交
550
#ifdef PADDLE_MOBILE_PROFILE
551 552 553
    std::vector<ProfInfo> profile(ops_of_block0_.size());
    struct timespec ts;
    int op_index = 0;
xiebaiyuan's avatar
xiebaiyuan 已提交
554
#endif
555 556
    for (int i = 0; i < ops_of_block0_.size(); ++i) {
      auto &op_handler = ops_of_block0_[i];
xiebaiyuan's avatar
xiebaiyuan 已提交
557
#ifdef PADDLE_MOBILE_PROFILE
558 559
      clock_gettime(CLOCK_MONOTONIC, &ts);
      profile[op_index].runBegin = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
xiebaiyuan's avatar
xiebaiyuan 已提交
560
#endif
561 562
      LOG(paddle_mobile::kLOG_INFO) << i << "th, "
                                    << "run op: " << op_handler->Type();
563 564 565 566
      if (lod_mode_ && input_dim_has_changed_) {
        op_handler->InferShape();
      }
      op_handler->Run();
xiebaiyuan's avatar
xiebaiyuan 已提交
567
#ifdef PADDLE_MOBILE_PROFILE
568 569 570
      clock_gettime(CLOCK_MONOTONIC, &ts);
      profile[op_index].runEnd = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
      ++op_index;
xiebaiyuan's avatar
xiebaiyuan 已提交
571
#endif
572 573 574 575
    }
    if (feed_indices_.size() == 1) {
      input_dim_has_changed_ = false;
    }
576 577

#ifdef PADDLE_MOBILE_PROFILE
578
    PrintProfile(profile);
579
#endif
580 581 582 583 584 585 586 587
    return PMSuccess;
  } catch (PaddleMobileException &e) {
    exception_msg_ = e.what();
    return PMException;
  } catch (std::exception &e) {
    exception_msg_ = e.what();
    return PMException;
  }
588 589
}

xiebaiyuan's avatar
xiebaiyuan 已提交
590
#ifdef PADDLE_MOBILE_PROFILE
591 592 593
template <typename Device, typename T>
void Executor<Device, T>::PrintProfile(
    const vector<Executor<Device, T>::ProfInfo> &profile) const {
xiebaiyuan's avatar
xiebaiyuan 已提交
594 595 596 597
  std::unordered_map<std::string, uint64_t> _tp;
  for (int i = 0; i < profile.size(); i++) {
    const auto &pInfo = profile[i];
    uint64_t timeCost = pInfo.runEnd - pInfo.runBegin;
598 599 600 601 602 603
    if (this->ops_of_block0_[i]->Type() == "conv2d" ||
        this->ops_of_block0_[i]->Type() == "depthwise_conv2d") {
      auto inputs = this->ops_of_block0_[i]->Inputs();

      auto *filter = GetVarValue<ProfileTensorType>("Filter", inputs,
                                                    *(this->program_.scope));
604
      int kernel_size = filter->dims()[2];
605 606
      _tp[this->ops_of_block0_[i]->Type() + "_" +
          std::to_string(kernel_size)] += timeCost;
607
    } else {
608
      _tp[this->ops_of_block0_[i]->Type()] += timeCost;
609
    }
xiebaiyuan's avatar
xiebaiyuan 已提交
610
  }
H
hjchen2 已提交
611
  printf("====================[ profile ]======================\n");
612
  typedef std::pair<std::string, uint64_t> prof_t;
xiebaiyuan's avatar
xiebaiyuan 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
  std::vector<prof_t> _tv(_tp.begin(), _tp.end());
  uint64_t _ptotal = 0;
  for (auto const &p : _tv) {
    _ptotal += p.second;
  }
  auto compf = [](const prof_t &a, const prof_t &b) {
    return a.second > b.second;
  };
  std::sort(_tv.begin(), _tv.end(), compf);
  _tv.push_back(std::make_pair("total", _ptotal));
  for (auto const &p : _tv) {
    printf("%-16s\t%-10.0f\t%-2.4f\n", p.first.c_str(),
           static_cast<float>(p.second),
           static_cast<float>(p.second) / _ptotal * 100.0);
  }
H
hjchen2 已提交
628
  printf("====================[---------]======================\n");
xiebaiyuan's avatar
xiebaiyuan 已提交
629
}
630
#endif
xiebaiyuan's avatar
xiebaiyuan 已提交
631

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
template <typename Device, typename T>
void Executor<Device, T>::FeedTensorData(const vector<framework::Tensor> &v) {
  auto input_size = v.size();
  auto *feed_var = program_.scope->Var("feed");

  PADDLE_MOBILE_ENFORCE(input_size == feed_indices_.size(),
                        "input data number not correct");
  for (int i = 0; i < input_size; i++) {
    framework::LoDTensor &target =
        feed_var->template GetMutable<framework::LoDTensorArray>()->at(i);
    target.ShareDataWith(v[input_size - i - 1]);
  }
}

template <typename Device, typename T>
void Executor<Device, T>::GetTensorResults(
    std::vector<framework::Tensor *> *v) {
  auto *fetch_var = program_.scope->Var("fetch");
  auto output_size = fetch_indices_.size();
  for (int i = 0; i < output_size; i++) {
    framework::LoDTensor &target =
        fetch_var->template GetMutable<framework::LoDTensorArray>()->at(i);
    v->push_back(&target);
  }
}

658 659 660 661 662
template <typename Device, typename T>
std::string Executor<Device, T>::GetExceptionMsg() {
  return exception_msg_;
}

663
#ifdef PADDLE_MOBILE_FPGA
664 665 666 667
template <typename Device, typename T>
void Executor<Device, T>::InjectVariable(const Tensor &t,
                                         std::string var_name) {
  Variable *g_feed_value = program_.scope->Var(var_name);
668
  Tensor *feed_tensor = g_feed_value->template GetMutable<LoDTensor>();
669 670
  feed_tensor->Resize(t.dims());
  feed_tensor->ShareDataWith(t);
671
}
672

673 674
template <typename Device, typename T>
void Executor<Device, T>::FeedData(const Tensor &t) {
Z
zhangyang0701 已提交
675
  InjectVariable(t, "feed0");
676
}
677

678
template <typename Device, typename T>
679
void Executor<Device, T>::FeedData(const std::vector<void *> &v) {
680
  auto input_size = v.size();
Z
zhangyang0701 已提交
681
  int index = 0;
682 683 684
  // auto vars = program_.scope->VarContain("feed", &index);
  // PADDLE_MOBILE_ENFORCE(input_size == vars.size(),
  //                    "input data number not correct");
685
  for (int i = 0; i < input_size; i++) {
Z
zhangyang0701 已提交
686
    auto var = program_.scope->Var("feed", i + index);
687 688 689 690 691 692 693 694 695
    auto feed_tensor = var->template GetMutable<LoDTensor>();
    feed_tensor->external_data = v[i];
  }
}

template <typename Device, typename T>
void Executor<Device, T>::GetResults(std::vector<void *> *v) {
  auto output_size = v->size();
  PADDLE_MOBILE_ENFORCE(output_size > 0, "Empty output");
Z
zhangyang0701 已提交
696 697
  int index = 0;
  auto vars = program_.scope->VarContain("fetch", &index);
698 699
  PADDLE_MOBILE_ENFORCE(output_size == vars.size(),
                        "output data number not correct");
700

701
  for (int i = 0; i < output_size; i++) {
Z
zhangyang0701 已提交
702
    auto var = program_.scope->Var("fetch", i + index);
703 704
    auto fetch_tensor = var->template GetMutable<LoDTensor>();
    (*v)[i] = fetch_tensor->template data<float>();
705
  }
706
}
707

708
template <typename Device, typename T>
709 710 711 712
framework::Tensor *Executor<Device, T>::GetTensorByName(
    const std::string &name) {
  auto var = program_.scope->Var(name);
  return var->template GetMutable<LoDTensor>();
H
hjchen2 已提交
713
}
714

715 716
template <typename Device, typename T>
std::shared_ptr<Tensor> Executor<Device, T>::FetchResult(int id) {
717
  auto &ops = ops_of_block0_;
718

Z
zhangyang 已提交
719 720 721 722 723
  PADDLE_MOBILE_ENFORCE(id < (int)ops.size(), "Index out of range");
  auto op = id < 0 ? ops[ops.size() - 1] : ops[id];
  auto output_map = op->Outputs();
  std::vector<std::string> out_keys = op->GetOutKeys();
  PADDLE_MOBILE_ENFORCE(!out_keys.empty(), "this op contains no output");
724 725 726
  auto *output_tensor =
      GetVarValue<LoDTensor>(out_keys[0], output_map, *(program_.scope));
  return std::make_shared<Tensor>(Tensor(*output_tensor));
727
}
728

729 730
template <typename Device, typename T>
void Executor<Device, T>::Predict_From_To(int start, int end) {
731
  auto &ops = ops_of_block0_;
732
  end = end < 0 ? static_cast<int>(ops.size()) : end;
733 734 735 736 737 738 739 740 741 742 743 744
  PADDLE_MOBILE_ENFORCE(start >= 0 && start < end && end <= ops.size(),
                        "start or end parameter is wrong");

#ifdef PADDLE_MOBILE_PROFILE
  std::vector<ProfInfo> profile(ops.size());
#endif
  for (int i = start; i < end; i++) {
#ifdef PADDLE_MOBILE_PROFILE
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    profile[i].runBegin = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
#endif
Z
zhangyang 已提交
745
    DLOG << "Running op: " << i << "  " << ops[i]->Type();
746 747 748 749 750 751 752
    ops[i]->Run();

#ifdef PADDLE_MOBILE_PROFILE
    clock_gettime(CLOCK_MONOTONIC, &ts);
    profile[i].runEnd = (uint64_t)ts.tv_sec * 1e9 + ts.tv_nsec;
#endif
  }
753
}
754

755 756
template <typename Device, typename T>
void Executor<Device, T>::Predict_From(int start) {
757
  Predict_From_To(start);
758
}
759

760 761
template <typename Device, typename T>
void Executor<Device, T>::Predict_To(int end) {
762
  Predict_From_To(0, end);
763
}
764 765 766 767 768 769
#ifdef PADDLE_MOBILE_FPGA_V2
std::map<std::string, float> LoadQuantValFromFile(std::string filename) {
  std::map<std::string, float> quantValList;
  std::ifstream in;
  in.open(filename, std::ios::in);
  if (!in.is_open()) {
770 771
    // std::cout << "open File Failed." << std::endl;
    DLOG << "open File Failed.";
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    exit(-1);
  }

  std::string line;
  while (getline(in, line)) {
    std::string splitStr = " : ";
    std::string::size_type pos;
    pos = line.find(splitStr);
    std::string subStr[2];
    subStr[0] = line.substr(0, pos);
    subStr[1] = line.substr(pos + splitStr.size(), line.size());
    quantValList.insert(std::make_pair(subStr[0], atof(subStr[1].c_str())));
  }
  in.close();
  return quantValList;
}
788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
template <typename Device, typename T>
void Executor<Device, T>::InitQuantMemory() {
  std::string quantValFilePath;
  if (program_.combined) {
    quantValFilePath = program_.para_path;
    quantValFilePath =
        quantValFilePath.substr(0, (quantValFilePath.length() - 6));
    quantValFilePath = quantValFilePath + "scale";
  } else {
    quantValFilePath = program_.model_path + "/scale";
  }
  std::map<std::string, float> quantValList =
      LoadQuantValFromFile(quantValFilePath);
  auto ops = ops_of_block0_;
  for (int id = 0; id < ops.size(); id++) {
    auto op = ops[id];
    auto input_keys = op->GetInputKeys();
    auto inputs = op->Inputs();
    for (auto key = input_keys.begin(); key != input_keys.end(); key++) {
      auto inputs_vars = inputs[*key];
      int count = inputs_vars.size();
      for (int i = 0; i < count; i++) {
811 812 813 814 815 816
        if (inputs_vars[i] != "feed") {
          auto tensor = GetTensorByName(inputs_vars[i]);
          tensor->scale[0] = quantValList[inputs_vars[i]];
          DLOG << "input variance name : " << inputs_vars[i]
               << ", scale value : " << tensor->scale[0];
        }
817 818 819 820 821 822 823 824
      }
    }
    auto output_keys = op->GetOutKeys();
    auto outputs = op->Outputs();
    for (auto key = output_keys.begin(); key != output_keys.end(); key++) {
      auto outputs_vars = outputs[*key];
      int count = outputs_vars.size();
      for (int i = 0; i < count; i++) {
825 826 827 828 829 830
        if (outputs_vars[i] != "fetch") {
          auto tensor = GetTensorByName(outputs_vars[i]);
          tensor->scale[0] = quantValList[outputs_vars[i]];
          DLOG << "output variance name : " << outputs_vars[i]
               << ", scale value : " << tensor->scale[0];
        }
831 832 833 834 835 836
      }
    }
  }
}
#endif
#endif
Y
yangfei 已提交
837
#ifdef PADDLE_MOBILE_CL
xiebaiyuan's avatar
xiebaiyuan 已提交
838 839
template <>
void Executor<GPU_CL, float>::InitNoPersistableMemory(
840
    const Tensor &input_tensor) {
xiebaiyuan's avatar
xiebaiyuan 已提交
841 842 843 844 845 846 847
  DLOG << "CL InitNoPersistableMemory ";
  for (const auto &block : program_desc_->Blocks()) {
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());

      if (var_desc->Persistable()) {
        if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
848
          var->template GetMutable<framework::LoDTensorArray>();
xiebaiyuan's avatar
xiebaiyuan 已提交
849 850 851 852
          continue;
        }
      } else {
        if (var_desc->Type() == VARTYPE_TYPE_LOD_TENSOR) {
853
          auto cl_image = var->template GetMutable<CLImage>();
xiebaiyuan's avatar
xiebaiyuan 已提交
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
          cl_context context = program_.scope->GetCLScpoe()->Context();
          cl_command_queue command_queue =
              program_.scope->GetCLScpoe()->CommandQueue();

          DDim tensor_dim = cl_image->dims();
          DDim new_dim =
              make_ddim({tensor_dim[0], tensor_dim[1], input_tensor.dims()[2],
                         input_tensor.dims()[3]});
          cl_image->Resize(new_dim);
          cl_image->InitEmptyImage(context, command_queue, new_dim);
        }
      }
    }
  }
  std::shared_ptr<LoDTensor> output = GetOutput("fetch");
  output->Resize(input_tensor.dims());
  output->mutable_data<float>();
}
H
hjchen2 已提交
872

xiebaiyuan's avatar
xiebaiyuan 已提交
873 874 875
template <>
void Executor<GPU_CL, float>::SetInput(const Tensor &input,
                                       const std::string &var_name) {
H
hjchen2 已提交
876 877 878 879 880
  int index = 0;
  if (feed_indices_.find(var_name) != feed_indices_.end()) {
    index = feed_indices_.find(var_name)->second;
  }
  auto *feed_var = program_.scope->Var("feed");
881
  framework::LoDTensor *input_tensor =
H
hjchen2 已提交
882
      &(feed_var->template GetMutable<framework::LoDTensorArray>()->at(index));
xiebaiyuan's avatar
xiebaiyuan 已提交
883 884

  DLOG << "config_.load_when_predict   " << config_.load_when_predict;
885 886
  DLOG << "target_tensor->IsInitialized() " << input_tensor->IsInitialized();
  DLOG << "target_tensor->dims()   " << input_tensor->dims();
xiebaiyuan's avatar
xiebaiyuan 已提交
887
  DLOG << "input.dims()   " << input.dims();
888
  DLOG << "input_dim_last_   " << input_dim_last_;
xiebaiyuan's avatar
xiebaiyuan 已提交
889
  if (config_.load_when_predict) {
xiebaiyuan's avatar
xiebaiyuan 已提交
890
    if (input_dim_last_ != input.dims()) {
891
      DLOG << "SetInput ---- > resize1";
892 893
      input_tensor->Resize(input.dims());
      input_tensor->mutable_data<float>();
894 895 896 897 898 899 900
      if (config_.memory_optimization_level == NoMemoryOptimization) {
        InitNoPersistableMemory(*input_tensor);
      } else {
        pass::MemoryOptPassCl()(program_desc_.get(), program_.scope.get(),
                                config_.memory_optimization_level,
                                input.dims());
      }
xiebaiyuan's avatar
xiebaiyuan 已提交
901 902 903
    }
  } else {
    DLOG << "SetInput ---- > resize2";
904
    input_tensor->Resize(input.dims());
xiebaiyuan's avatar
xiebaiyuan 已提交
905 906
    DLOG << "SetInput ---- > ShareDataWith";
  }
907
  input_tensor->ShareDataWith(input);
908 909 910
  if (feed_indices_.size() == 1) {
    input_dim_has_changed_ = input_dim_last_ != input.dims();
  }
911 912
  auto &dim = input.dims();
  input_dim_last_ = static_cast<DDim>(dim);
xiebaiyuan's avatar
xiebaiyuan 已提交
913 914
}

915 916 917
template <typename Device, typename T>
void Executor<Device, T>::LoadMemory(const VarDesc var_desc, float *tensorInput,
                                     char **data) {}
L
liuruilong 已提交
918

Y
yangfei 已提交
919
template <>
H
hjchen2 已提交
920 921
void Executor<GPU_CL, float>::LoadMemory(const VarDesc var_desc,
                                         float *tensorInput, char **data) {
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
  // 1. version
  uint32_t version = *reinterpret_cast<uint32_t *>(*data);

  (*data) += sizeof(uint32_t);

  // 2 Lod information
  uint64_t *lod_level_ptr = new uint64_t();
  memcpy(lod_level_ptr, (*data), sizeof(uint64_t));
  uint64_t lod_level = *lod_level_ptr;
  delete lod_level_ptr;
  (*data) += sizeof(uint64_t);

  for (uint64_t i = 0; i < lod_level; ++i) {
    uint64_t size = *reinterpret_cast<uint64_t *>(*data);
    (*data) += sizeof(uint64_t);
    std::vector<size_t> tmp(size / sizeof(size_t));

    for (int k = 0; k < tmp.size(); ++k) {
      tmp[k] = *reinterpret_cast<size_t *>(*data);
      (*data) += sizeof(size_t);
    }
  }

  // 3. tensor version
  uint32_t tensor_version = *reinterpret_cast<uint32_t *>(*data);
  (*data) += sizeof(uint32_t);

  // 4. tensor desc
  int32_t size = *reinterpret_cast<int32_t *>(*data);
  (*data) += sizeof(int32_t);

  std::unique_ptr<char[]> buf(new char[size]);
  for (int m = 0; m < size; ++m) {
    buf.get()[m] = (*data)[m];
  }
  (*data) += (sizeof(char) * size);

959
  const TensorDesc &desc = var_desc.Tensor_desc();
960 961 962 963 964 965 966 967
  int memory_size = 1;
  for (auto l : desc.Dims()) {
    memory_size *= l;
  }

  void *memory = nullptr;
  int type_size = 4;
  memory = tensorInput;
968 969 970 971

  LoadMemInternal<float>(reinterpret_cast<void **>(data),
                         reinterpret_cast<void *>(memory), memory_size,
                         program_.quantification, program_.quantification_fold);
972
}
973

Y
yangfei 已提交
974
template <>
975 976
void Executor<GPU_CL, float>::InitMemory() {
  for (const auto &block : program_desc_->Blocks()) {
Y
yangfei 已提交
977 978 979
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
      if (var_desc->Persistable()) {
L
liuruilong 已提交
980
        CLImage *cl_image = nullptr;
Y
yangfei 已提交
981
        if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
H
hjchen2 已提交
982
          var->template GetMutable<framework::LoDTensorArray>();
Y
yangfei 已提交
983
          continue;
L
liuruilong 已提交
984
        } else {
985
          cl_image = var->template GetMutable<CLImage>();
Y
yangfei 已提交
986
        }
L
liuruilong 已提交
987

Y
yangfei 已提交
988
        char *origin_data =
L
liuruilong 已提交
989
            ReadFileToBuff(program_.model_path + "/" + var_desc->Name());
990
        char *data = origin_data;
Y
yangfei 已提交
991
        cl_context context = program_.scope->GetCLScpoe()->Context();
992
        const TensorDesc &desc = var_desc->Tensor_desc();
993 994 995 996 997
        int numel = 1;
        for (auto l : desc.Dims()) {
          numel *= l;
        }
        DLOG << var_desc->Name();
Y
yangfei 已提交
998
        float *tensorInput = static_cast<float *>(
999 1000
            paddle_mobile::memory::Alloc(sizeof(float) * numel));
        LoadMemory(*var_desc, tensorInput, &data);
Y
yangfei 已提交
1001

1002
        DDim ddim = make_ddim(desc.Dims());
Y
yangfei 已提交
1003

L
liuruilong 已提交
1004 1005
        // has not init
        cl_image->SetTensorData(tensorInput, ddim);
Y
yangfei 已提交
1006

1007
        delete origin_data;
Y
yangfei 已提交
1008
        paddle_mobile::memory::Free(tensorInput);
1009
      } else {
1010 1011
        if (var_desc->Type() == VARTYPE_TYPE_LOD_TENSOR) {
          auto cl_image = var->template GetMutable<CLImage>();
1012
          cl_context context = program_.scope->GetCLScpoe()->Context();
L
liuruilong 已提交
1013 1014
          cl_command_queue command_queue =
              program_.scope->GetCLScpoe()->CommandQueue();
Y
yangfei 已提交
1015

1016 1017 1018
          const TensorDesc &desc = var_desc->Tensor_desc();
          //          DDim ddim = make_ddim(desc.Dims());
          DDim ddim = cl_image->dims();
1019
          LOG(kLOG_DEBUG1) << "init image of " << var_desc->Name();
L
liuruilong 已提交
1020
          cl_image->InitEmptyImage(context, command_queue, ddim);
1021
        }
Y
yangfei 已提交
1022 1023 1024 1025
      }
    }
  }
}
1026

Y
yangfei 已提交
1027
template <>
1028
void Executor<GPU_CL, float>::InitCombineMemory() {
xiebaiyuan's avatar
xiebaiyuan 已提交
1029 1030
  DLOG << "CL InitCombineMemory---- "
       << "config_.load_when_predict: " << config_.load_when_predict;
Y
yangfei 已提交
1031 1032
  char *origin_data = nullptr;
  bool self_alloc = false;
Y
yangfei 已提交
1033 1034
  if (program_.combined_params_buf && program_.combined_params_len) {
    LOG(kLOG_INFO) << "use outter memory";
1035
    origin_data = reinterpret_cast<char *>(program_.combined_params_buf);
1036 1037 1038 1039
    if (config_.model_obfuscate_key != "") {
      auto obfuscator = pass::ModelObfuscatePass(config_.model_obfuscate_key);
      obfuscator.convert_data(origin_data, program_.combined_params_len);
    }
Y
yangfei 已提交
1040 1041
  } else {
    LOG(kLOG_INFO) << " begin init combine memory";
Y
yangfei 已提交
1042
    self_alloc = true;
L
liuruilong 已提交
1043
    origin_data = ReadFileToBuff(program_.para_path);
1044 1045 1046 1047
    if (config_.model_obfuscate_key != "") {
      auto obfuscator = pass::ModelObfuscatePass(config_.model_obfuscate_key);
      obfuscator.convert_data(origin_data, GetFileLength(program_.para_path));
    }
Y
yangfei 已提交
1048 1049
  }
  PADDLE_MOBILE_ENFORCE(origin_data != nullptr, "origin_data==nullptr!!!");
1050
  float *data = reinterpret_cast<float *>(origin_data);
Y
yangfei 已提交
1051

1052
  for (const auto &block : program_desc_->Blocks()) {
Y
yangfei 已提交
1053 1054 1055
    for (const auto &var_desc : block->Vars()) {
      auto var = program_.scope->Var(var_desc->Name());
      if (var_desc->Persistable()) {
L
liuruilong 已提交
1056
        CLImage *cl_image = nullptr;
Y
yangfei 已提交
1057
        if (var_desc->Name() == "feed" || var_desc->Name() == "fetch") {
H
hjchen2 已提交
1058
          var->template GetMutable<framework::LoDTensorArray>();
Y
yangfei 已提交
1059
          continue;
L
liuruilong 已提交
1060
        } else {
1061
          cl_image = var->template GetMutable<CLImage>();
Y
yangfei 已提交
1062 1063 1064 1065
        }

        cl_context context = program_.scope->GetCLScpoe()->Context();

1066 1067
        const TensorDesc &desc = var_desc->Tensor_desc();
        DDim ddim = make_ddim(desc.Dims());
Y
yangfei 已提交
1068 1069 1070 1071 1072

        int numel = 1;
        for (int i = 0; i < ddim.size(); i++) {
          numel = numel * ddim[i];
        }
1073 1074 1075
        float *tensorInput = static_cast<float *>(
            paddle_mobile::memory::Alloc(sizeof(float) * numel));
        LoadMemory(*var_desc, tensorInput, &origin_data);
L
liuruilong 已提交
1076 1077 1078 1079

        // has not init
        cl_image->SetTensorData(tensorInput, ddim);

1080 1081
        paddle_mobile::memory::Free(tensorInput);
      } else {
1082
        auto cl_image = var->template GetMutable<CLImage>();
Y
yangfei 已提交
1083
        cl_context context = program_.scope->GetCLScpoe()->Context();
L
liuruilong 已提交
1084 1085
        cl_command_queue command_queue =
            program_.scope->GetCLScpoe()->CommandQueue();
1086 1087
        const TensorDesc &desc = var_desc->Tensor_desc();
        DDim ddim = cl_image->dims();
1088 1089 1090
        bool shouldResize = true;
        if (ddim.size() > 4) {
          for (int i = 0; i < ddim.size() - 4; ++i) {
1091
            if (ddim[i] != 0 && ddim[i] != 1) {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
              shouldResize = false;
              break;
            }
          }
          if (shouldResize) {
            std::vector<int64_t> temp_intput_dims;
            temp_intput_dims.reserve(static_cast<size_t>(4));
            for (int i = ddim.size() - 4; i < ddim.size(); ++i) {
              temp_intput_dims.push_back(ddim[i]);
            }
            ddim = framework::make_ddim(temp_intput_dims);
          }
        }
1105
        //  DDim ddim = make_ddim(desc.Dims());
L
liuruilong 已提交
1106
        cl_image->InitEmptyImage(context, command_queue, ddim);
Y
yangfei 已提交
1107 1108 1109
      }
    }
  }
Y
yangfei 已提交
1110
  if (self_alloc) {
1111
    delete data;
Y
yangfei 已提交
1112
  }
Y
yangfei 已提交
1113
  LOG(kLOG_INFO) << " end init combine memory ";
1114
}
Y
yangfei 已提交
1115 1116 1117

#endif

1118
template class Executor<CPU, float>;
Y
yangfei 已提交
1119

1120
template class Executor<FPGA, float>;
W
wangliu 已提交
1121

1122
template class Executor<GPU_CL, float>;
Y
yangfei 已提交
1123 1124

}  // namespace framework
W
wangliu 已提交
1125
}  // namespace paddle_mobile