engine.cc 5.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 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/kernels/npu/bridges/engine.h"
#include <sys/time.h>
#include <time.h>
18
#include <algorithm>
19 20 21 22 23 24 25
#include <utility>
#include "lite/kernels/npu/bridges/registry.h"

namespace paddle {
namespace lite {
namespace subgraph {

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
Engine::Engine(KernelContext *ctx,
               int block_idx,
               cpp::BlockDesc *block_desc,
               const std::vector<std::string> &input_names,
               const std::vector<std::string> &output_names,
               lite::Scope *scope)
    : ctx_(ctx), block_idx_(block_idx), block_desc_(block_desc), scope_(scope) {
  input_names_ = input_names;
  output_names_ = output_names;
  // Sort the name of input and output tensors, it's convenient for us to get
  // the info of input and output tensors in the same order from the device
  // program, because the result of subgraph division may be different but right
  // at each call of the subgraph pass.
  std::stable_sort(input_names_.begin(), input_names_.end());
  std::stable_sort(output_names_.begin(), output_names_.end());
}

bool Engine::Run() {
  if (is_first_epoch_) {
    PrepareWorkspaceForDeviceProgram();
    is_first_epoch_ = false;
  }
  if (InputShapeChanged()) {
    BuildDeviceProgram();
  }
  return LaunchDeviceProgram();
}
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67
bool Engine::PrepareWorkspaceForOriginProgram() {
  origin_idims_.resize(input_names_.size());
  origin_itensors_.resize(input_names_.size());
  for (int i = 0; i < input_names_.size(); i++) {
    origin_itensors_[i] = scope_->FindMutableTensor(input_names_[i]);
    CHECK(origin_itensors_[i]);
  }
  origin_otensors_.resize(output_names_.size());
  for (int i = 0; i < output_names_.size(); i++) {
    origin_otensors_[i] = scope_->FindMutableTensor(output_names_[i]);
    CHECK(origin_otensors_[i]);
  }
  return true;
}
68

69
bool Engine::BuildOriginProgram() {
70 71 72
  // TODO(hong19860320) The block_desc need to be divided into subgraphs during
  // the exection time. But only see them as a subgraph now.
  origin_program_.clear();
73
  for (size_t op_idx = 0; op_idx < block_desc_->OpsSize(); op_idx++) {
74 75 76
    auto op_desc = block_desc_->GetOp<cpp::OpDesc>(op_idx);
    CHECK(op_desc);
    std::string op_type = op_desc->Type();
77
    // Create op and pick up the best kernel
78
    auto op = LiteOpRegistry::Global().Create(op_desc->Type());
79
    CHECK(op) << "no Op found for " << op_type;
80 81 82
    op->Attach(*op_desc, scope_);
    std::unique_ptr<KernelBase> picked_kernel;
    if (op_desc->HasAttr(kKernelTypeAttr)) {
83 84
      // Create op and pick up the best kernel according to the
      // kKernelTypeAttr attribute
85 86 87 88 89 90 91
      auto kernel_type = op_desc->GetAttr<std::string>(kKernelTypeAttr);
      std::string alias;
      Place place;
      KernelBase::ParseKernelType(kernel_type, &op_type, &alias, &place);
      VLOG(3) << "Found the attr '" << kKernelTypeAttr << "': " << kernel_type
              << " for " << op_type;
      auto kernels = op->CreateKernels({place});
92
      CHECK_GT(kernels.size(), 0u) << "No kernels found for " << op_type;
93
      auto it = std::find_if(
94
          kernels.begin(), kernels.end(), [&](std::unique_ptr<KernelBase> &it) {
95 96 97 98 99
            return it->alias() == alias;
          });
      CHECK(it != kernels.end());
      picked_kernel = std::move(*it);
    } else {
100 101
      // TODO(hong19860320) add kernel picking according to the type of input
      // and output tensors
102 103
      VLOG(3) << "The attr '" << kKernelTypeAttr
              << "' not found, pick the first kernel for " << op_type;
104
      std::vector<std::unique_ptr<KernelBase>> kernels;
105
#if defined(LITE_WITH_ARM)
106
      kernels = op->CreateKernels({Place{TARGET(kARM)}, Place{TARGET(kHost)}});
107
#elif defined(LITE_WITH_X86)
108
      kernels = op->CreateKernels({Place{TARGET(kX86)}, Place{TARGET(kHost)}});
109
#endif
110 111 112 113 114 115 116 117 118
      if (kernels.size() > 0) {
        picked_kernel = std::move(kernels.front());
      } else {
        LOG(WARNING) << "No kernels found for " << op_type;
      }
    }
    if (picked_kernel != nullptr) {
      picked_kernel->SetContext(
          ContextScheduler::Global().NewContext(picked_kernel->target()));
119 120 121
    }
    origin_program_.emplace_back(std::move(op), std::move(picked_kernel));
  }
122 123
  CHECK(!origin_program_.empty()) << "no instructions";
  return true;
124 125
}

126 127 128 129 130 131 132 133 134 135 136
bool Engine::LaunchOriginProgram() {
  if (origin_program_.empty()) {
    BuildOriginProgram();
  }
  if (!origin_program_.empty()) {
    for (auto &inst : origin_program_) {
      auto op_type = inst.op()->op_info()->Type();
      if (op_type == "feed" || op_type == "fetch") continue;
      inst.Run();
    }
    return true;
137
  }
138
  return false;
139 140
}

141 142
bool Engine::PrepareWorkspaceForDeviceProgram() {
  return PrepareWorkspaceForOriginProgram();
143 144
}

145 146 147 148
bool Engine::BuildDeviceProgram() { return BuildOriginProgram(); }

bool Engine::LaunchDeviceProgram() { return LaunchOriginProgram(); }

149
bool Engine::InputShapeChanged() {
150
  bool changed = false;
151
  for (size_t i = 0; i < origin_itensors_.size(); i++) {
152 153 154
    auto origin_idim = origin_itensors_[i]->dims().Vectorize();
    changed |= origin_idim != origin_idims_[i];
    origin_idims_[i] = origin_idim;
155
  }
156
  return changed;
157 158 159 160 161
}

}  // namespace subgraph
}  // namespace lite
}  // namespace paddle