op_lite.cc 10.5 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// 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/core/op_lite.h"
#include <list>
#include <set>
#include <utility>
#include <vector>
#include "lite/core/op_registry.h"
21
#include "lite/utils/string.h"
Y
Yan Chunwei 已提交
22 23 24 25

namespace paddle {
namespace lite {

26 27 28
bool OpLite::InferShape() {
  // if input_tensor_ptrs and output_tensor_ptrs are overloaded in param_
  // InferShapeByMemoryInternal will be applied.
29 30
  if (op_param_ && op_param_->input_tensor_ptrs() &&
      op_param_->output_tensor_ptrs()) {
31 32 33 34 35 36 37
    return this->InferShapeWithCache();
  } else {
    return this->InferShapeImpl();
  }
}
bool OpLite::InferShapeWithCache() {
  // 1. Get vector of current input tensors
38
  auto *current_inputs = op_param_->input_tensor_ptrs();
39
  // 2. Get hash value of current inputs shape and lod
40 41 42 43 44 45 46
  bool use_cache = true;
  if (last_input_shapes.size() == current_inputs->size()) {
    for (int i = 0; i < current_inputs->size(); i++) {
      if (last_input_shapes[i] != current_inputs->at(i)->dims() ||
          last_input_lods[i] != current_inputs->at(i)->lod()) {
        use_cache = false;
        break;
47 48
      }
    }
49 50
  } else {
    use_cache = false;
51
  }
52

53
  // 3. infer shapes of output tensors
54
  if (use_cache) {
55 56
    // if current hash value is consistent with io_shape_lod_hash_,
    // previous outputs shape and lod are reused.
57
    auto *current_outputs = op_param_->output_tensor_ptrs();
58
    for (size_t i = 0; i < current_outputs->size(); i++) {
59 60 61 62 63 64
      current_outputs->at(i)->Resize(last_output_shapes[i]);
      current_outputs->at(i)->set_lod(last_output_lods[i]);
    }
  } else {
    // otherwise, current hash value is changed, InferShapeImpl will apply.
    this->InferShapeImpl();
65 66 67
    auto *current_outputs = op_param_->output_tensor_ptrs();
    last_output_shapes.clear();
    last_output_lods.clear();
68
    for (size_t i = 0; i < current_outputs->size(); i++) {
69 70
      last_output_shapes.push_back(current_outputs->at(i)->dims());
      last_output_lods.push_back(current_outputs->at(i)->lod());
71
    }
72 73 74 75 76 77
    last_input_shapes.clear();
    last_input_lods.clear();
    for (size_t i = 0; i < current_inputs->size(); i++) {
      last_input_shapes.push_back(current_inputs->at(i)->dims());
      last_input_lods.push_back(current_inputs->at(i)->lod());
    }
78 79 80 81
  }
  return true;
}

Y
Yan Chunwei 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
std::vector<std::unique_ptr<KernelBase>> OpLite::CreateKernels(
    const std::vector<Place> &places, const std::string &kernel_type) {
  std::vector<std::unique_ptr<KernelBase>> kernels;
  CHECK(!op_type_.empty()) << "op_type_ should be set first";

  auto pick_kernel = [&](const Place &place) {
    auto ks = KernelRegistry::Global().Create(
        op_type_, place.target, place.precision, place.layout);
    VLOG(5) << "pick kernel for " << op_info()->Type() << " "
            << place.DebugString() << " get " << ks.size() << " kernels";
    for (auto &&it : ks) {
      AttachKernel(it.get());
      kernels.emplace_back(std::move(it));
    }
  };

  if (!kernel_type.empty()) {
    Place place;
    std::string op_type, alias;
    KernelBase::ParseKernelType(kernel_type, &op_type, &alias, &place);
    pick_kernel(place);
    CHECK(!kernels.empty()) << "no kernel for kernel type " << kernel_type;
    return kernels;
  }

107 108 109 110 111 112 113 114 115
  std::set<Place> expanded_places(places.begin(), places.end());
  for (auto &place : places) {
    // Pick kernels those support any Precision and any DataLayout, For example:
    // kARM,kFloat,kNCHW -> kARM,kFloat,kAny; kARM,kAny,kNCHW; kARM,kAny,kAny
    expanded_places.insert(
        Place(place.target, place.precision, DATALAYOUT(kAny)));
    expanded_places.insert(Place(place.target, PRECISION(kAny), place.layout));
    expanded_places.insert(
        Place(place.target, PRECISION(kAny), DATALAYOUT(kAny)));
Y
Yan Chunwei 已提交
116 117 118
  }

  std::set<TargetType> targets;
119
  for (auto place : expanded_places) {
Y
Yan Chunwei 已提交
120 121 122 123
    pick_kernel(place);
    targets.insert(place.target);
  }

Z
Zhaolong Xing 已提交
124
  VLOG(5) << "op " << op_type_ << " get " << kernels.size() << " kernels";
Y
Yan Chunwei 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  return kernels;
}

bool OpLite::Run() {
  CHECK(kernel_);
  SyncInputEvents();

  kernel_->Launch();

  RecordOutputEvents();
  return true;
}

bool OpLite::Attach(const cpp::OpDesc &opdesc, lite::Scope *scope) {
  // valid_places_.clear();
  CHECK(scope != nullptr);
  // CHECK(!op_info_.get());
  scope_ = scope;
  op_info_.reset(
      new OpInfo(opdesc));  // Force clean the out-of-date infomation.
  return AttachImpl(*op_info(), scope);
}

const Tensor *OpLite::GetTensor(lite::Scope *scope,
                                const std::string &name) const {
  auto *var = scope->FindVar(name);
  CHECK(var) << "no variable called " << name << " found";
  return &var->Get<lite::Tensor>();
}

Tensor *OpLite::GetMutableTensor(lite::Scope *scope,
                                 const std::string &name) const {
  auto *var = scope->FindVar(name);
  CHECK(var) << "no variable called " << name << " found";
  return var->GetMutable<lite::Tensor>();
}

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
void OpLite::AttachInput(const cpp::OpDesc &op_desc,
                         lite::Scope *scope,
                         const std::string &input_name,
                         bool is_dispensable,
                         lite::Tensor **input_var) {
  bool is_have_input =
      op_desc.HasInput(input_name) && op_desc.Input(input_name).size() > 0;
  CHECK(is_dispensable || is_have_input);
  if (is_have_input) {
    std::string input_var_name = op_desc.Input(input_name).front();
    *input_var = scope->FindVar(input_var_name)->GetMutable<lite::Tensor>();
  }
}

void OpLite::AttachOutput(const cpp::OpDesc &op_desc,
                          lite::Scope *scope,
                          const std::string &output_name,
                          bool is_dispensable,
                          lite::Tensor **output_var) {
  bool is_have_output =
      op_desc.HasOutput(output_name) && op_desc.Output(output_name).size() > 0;
  CHECK(is_dispensable || is_have_output);
  if (is_have_output) {
    std::string output_var_name = op_desc.Output(output_name).front();
    *output_var = scope->FindVar(output_var_name)->GetMutable<lite::Tensor>();
  }
}

190 191
bool OpInfo::GetInputArgname(const std::string &value_name,
                             std::string *out) const {
192
  for (auto &item : inputs()) {
193 194 195 196 197 198 199 200 201 202 203
    auto it = std::find(item.second.begin(), item.second.end(), value_name);
    if (it != item.second.end()) {
      *out = item.first;
      return true;
    }
  }
  return false;
}

bool OpInfo::GetOutputArgname(const std::string &value_name,
                              std::string *out) const {
204
  for (auto &item : outputs()) {
205 206 207 208 209 210 211 212 213 214
    auto it = std::find(item.second.begin(), item.second.end(), value_name);
    if (it != item.second.end()) {
      *out = item.first;
      return true;
    }
  }
  return false;
}

bool OpInfo::GetInputIndex(const std::string &input_name, int *out) const {
215
  for (auto &item : inputs()) {
216 217 218 219 220 221 222 223 224 225
    auto it = std::find(item.second.begin(), item.second.end(), input_name);
    if (it != item.second.end()) {
      *out = it - item.second.begin();
      return true;
    }
  }
  return false;
}

bool OpInfo::GetOutputIndex(const std::string &output_name, int *out) const {
226
  for (auto &item : outputs()) {
227 228 229 230 231 232 233 234 235
    auto it = std::find(item.second.begin(), item.second.end(), output_name);
    if (it != item.second.end()) {
      *out = it - item.second.begin();
      return true;
    }
  }
  return false;
}

236 237 238 239
bool OpInfo::HasInputScale(const std::string &name, bool is_scale_name) const {
  bool res = false;
  if (is_scale_name) {
    res = HasAttr(name);
240
  } else {
241 242 243 244 245
    std::string argname;
    int index;
    if (GetInputArgname(name, &argname) && GetInputIndex(name, &index)) {
      res = HasAttr(argname + to_string(index) + "_scale");
    }
246
  }
247
  return res;
248 249
}

250 251 252 253
bool OpInfo::HasOutputScale(const std::string &name, bool is_scale_name) const {
  bool res = false;
  if (is_scale_name) {
    res = HasAttr(name);
254
  } else {
255 256 257 258 259
    std::string argname;
    int index;
    if (GetOutputArgname(name, &argname) && GetOutputIndex(name, &index)) {
      res = HasAttr(argname + to_string(index) + "_scale");
    }
260
  }
261
  return res;
262 263
}

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
void OpInfo::SetInputScale(const std::string &name,
                           const std::vector<float> &scale_value,
                           bool is_scale_name) {
  std::string scale_name;
  if (is_scale_name) {
    scale_name = name;
  } else {
    std::string argname;
    int index;
    CHECK(GetInputArgname(name, &argname));
    CHECK(GetInputIndex(name, &index));
    CHECK(scale_value.size() > 0)
        << "Error in SetInputScale: the scales should not be empty";
    scale_name = argname + to_string(index) + "_scale";
  }
  SetAttr<std::vector<float>>(scale_name, scale_value);
280 281
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
void OpInfo::SetOutputScale(const std::string &name,
                            const std::vector<float> &scale_value,
                            bool is_scale_name) {
  std::string scale_name;
  if (is_scale_name) {
    scale_name = name;
  } else {
    std::string argname;
    int index;
    CHECK(GetOutputArgname(name, &argname));
    CHECK(GetOutputIndex(name, &index));
    CHECK(scale_value.size() > 0)
        << "Error in SetOutputScale: the scales should not be empty";
    scale_name = argname + to_string(index) + "_scale";
  }
  SetAttr<std::vector<float>>(scale_name, scale_value);
298 299
}

300 301 302 303 304 305 306 307 308 309 310 311 312
std::vector<float> OpInfo::GetInputScale(const std::string &name,
                                         bool is_scale_name) const {
  std::string scale_name;
  if (is_scale_name) {
    scale_name = name;
  } else {
    std::string argname;
    int index;
    CHECK(GetInputArgname(name, &argname));
    CHECK(GetInputIndex(name, &index));
    scale_name = argname + to_string(index) + "_scale";
  }
  return GetAttr<std::vector<float>>(scale_name);
313 314
}

315 316 317 318 319 320 321 322 323 324 325 326
std::vector<float> OpInfo::GetOutputScale(const std::string &name,
                                          bool is_scale_name) const {
  std::string scale_name;
  if (is_scale_name) {
    scale_name = name;
  } else {
    std::string argname;
    int index;
    CHECK(GetOutputArgname(name, &argname));
    CHECK(GetOutputIndex(name, &index));
  }
  return GetAttr<std::vector<float>>(scale_name);
327 328
}

Y
Yan Chunwei 已提交
329 330
}  // namespace lite
}  // namespace paddle