context.h 16.0 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 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.

#pragma once

#include "lite/utils/any.h"
#ifdef LITE_WITH_CUDA
19
#include "lite/backends/cuda/context.h"
Y
Yan Chunwei 已提交
20 21
#endif
#ifdef LITE_WITH_OPENCL
22 23
#include "lite/backends/opencl/cl_context.h"
#include "lite/backends/opencl/cl_runtime.h"
Y
Yan Chunwei 已提交
24
#endif
25 26 27
#ifdef LITE_WITH_MLU
#include <cnml.h>
#include <cnrt.h>
28
#include <mutex>  // NOLINT
29 30
#include "lite/backends/mlu/mlu_utils.h"
#endif
31
#ifdef LITE_WITH_XPU
32
#include <fcntl.h>
33 34
#include "lite/backends/xpu/xpu_header_sitter.h"
#endif
Y
Yan Chunwei 已提交
35 36 37 38 39 40 41

#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
42
#include "lite/core/device_info.h"
43
#include "lite/core/scope.h"
Y
Yan Chunwei 已提交
44 45 46
#include "lite/core/target_wrapper.h"
#include "lite/core/tensor.h"
#include "lite/utils/all.h"
47
#include "lite/utils/env.h"
48
#include "lite/utils/macros.h"
Y
Yan Chunwei 已提交
49 50 51 52 53 54 55 56 57 58 59

namespace paddle {
namespace lite {

template <TargetType Type>
class Context;

using HostContext = Context<TargetType::kHost>;
using X86Context = Context<TargetType::kX86>;
using ARMContext = Context<TargetType::kARM>;
using NPUContext = Context<TargetType::kNPU>;
H
hong19860320 已提交
60
using APUContext = Context<TargetType::kAPU>;
61
using XPUContext = Context<TargetType::kXPU>;
Y
Yan Chunwei 已提交
62 63
using OpenCLContext = Context<TargetType::kOpenCL>;
using FPGAContext = Context<TargetType::kFPGA>;
64
using BMContext = Context<TargetType::kBM>;
65
using MLUContext = Context<TargetType::kMLU>;
66
using RKNPUContext = Context<TargetType::kRKNPU>;
67
using HuaweiAscendNPUContext = Context<TargetType::kHuaweiAscendNPU>;
Y
Yan Chunwei 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

template <>
class Context<TargetType::kHost> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}

  void CopySharedTo(HostContext* ctx) {}

  std::string name() const { return "HostContext"; }
};

#ifdef LITE_WITH_NPU
template <>
class Context<TargetType::kNPU> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}
  void CopySharedTo(NPUContext* ctx) {}

  NPUContext& operator=(const NPUContext& ctx) {}
  std::string name() const { return "NPUContext"; }
90

91 92 93 94 95 96 97
  static void SetSubgraphModelCacheDir(Scope* scope,
                                       std::string subgraph_model_cache_dir) {
    auto var = scope->Var("SUBGRAPH_MODEL_CACHE_DIR");
    CHECK(var);
    auto data = var->GetMutable<std::string>();
    CHECK(data);
    *data = subgraph_model_cache_dir;
98
  }
99 100 101 102
  static std::string SubgraphModelCacheDir(Scope* scope) {
    auto var = scope->FindVar("SUBGRAPH_MODEL_CACHE_DIR");
    if (!var) return "";
    return var->Get<std::string>();
103
  }
Y
Yan Chunwei 已提交
104 105 106
};
#endif

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
#ifdef LITE_WITH_HUAWEI_ASCEND_NPU
template <>
class Context<TargetType::kHuaweiAscendNPU> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}
  void CopySharedTo(HuaweiAscendNPUContext* ctx) {}

  HuaweiAscendNPUContext& operator=(const HuaweiAscendNPUContext& ctx) {
    return *this;
  }
  std::string name() const { return "HuaweiAscendNPUContext"; }

  static void SetSubgraphModelCacheDir(std::string subgraph_model_cache_dir) {
    subgraph_model_cache_dir_ = subgraph_model_cache_dir;
  }
  static std::string SubgraphModelCacheDir() {
    return subgraph_model_cache_dir_;
  }

  static void SetHuaweiAscendDeviceID(int huawei_ascend_device_id) {
    huawei_ascend_device_id_ = huawei_ascend_device_id;
  }
  static int HuaweiAscendDeviceID() { return huawei_ascend_device_id_; }

 private:
133 134
  static LITE_THREAD_LOCAL std::string subgraph_model_cache_dir_;
  static LITE_THREAD_LOCAL int huawei_ascend_device_id_;
135 136 137
};
#endif

H
hong19860320 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150
#ifdef LITE_WITH_APU
template <>
class Context<TargetType::kAPU> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}
  void CopySharedTo(APUContext* ctx) {}

  APUContext& operator=(const APUContext& ctx) {}
  std::string name() const { return "APUContext"; }
};
#endif

151 152 153 154 155
#ifdef LITE_WITH_BM
template <>
class Context<TargetType::kBM> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
156
  void InitOnce() { TargetWrapperBM::SetDevice(TargetWrapperBM::GetDevice()); }
157 158 159 160 161 162 163
  void CopySharedTo(BMContext* ctx) {}
  void* GetHandle() { return TargetWrapperBM::GetHandle(); }

  std::string name() const { return "BMContext"; }
};
#endif

164 165 166 167 168 169 170 171 172 173 174 175 176
#ifdef LITE_WITH_RKNPU
template <>
class Context<TargetType::kRKNPU> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}
  void CopySharedTo(RKNPUContext* ctx) {}

  RKNPUContext& operator=(const RKNPUContext& ctx) {}
  std::string name() const { return "RKNPUContext"; }
};
#endif

177 178 179 180 181 182
#ifdef LITE_WITH_XPU
template <>
class Context<TargetType::kXPU> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}
183

184 185
  void CopySharedTo(XPUContext* ctx) {}

186
  // TODO(miaotianxiang): remove this
187
  static xdnn::Context* GetRawContext() {
188
    return TargetWrapperXPU::GetRawContext();
189 190
  }

191
  std::string name() const { return "XPUContext"; }
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

  inline static int LockXPU() {
    _reentrant = 0;
    int xpu_l3_lock_fd = -1;
    struct flock f_lock;
    f_lock.l_whence = 0;
    f_lock.l_len = 0;

    if (_reentrant == 0) {
      int pd = 0;  // TODO(luohang): need get from lite api
      std::string buf = "/opt/xpu_lock" + std::to_string(pd);
      xpu_l3_lock_fd = open(buf.c_str(), O_RDWR);
      CHECK(xpu_l3_lock_fd > 0) << "open " << buf
                                << " failed: " << xpu_l3_lock_fd;

      // lock
      f_lock.l_type = F_WRLCK;
      fcntl(xpu_l3_lock_fd, F_SETLKW, &f_lock);
    }
    _reentrant++;
    return xpu_l3_lock_fd;
  }

  inline static void ReleaseXPU(int lock_fd) {
    if (lock_fd < 0) return;

    if (_reentrant == 1) {
      struct flock f_lock;
      f_lock.l_whence = 0;
      f_lock.l_len = 0;
      f_lock.l_type = F_UNLCK;
      fcntl(lock_fd, F_SETLKW, &f_lock);
      close(lock_fd);
    }
    _reentrant--;
  }

 private:
  static int _reentrant;
231 232 233
};
#endif

Y
Yan Chunwei 已提交
234 235 236 237 238 239 240 241 242
#ifdef LITE_WITH_ARM
template <>
class Context<TargetType::kARM> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() { DeviceInfo::Init(); }

  void CopySharedTo(ARMContext* ctx) {}

243
  void SetRunMode(lite_api::PowerMode mode, int threads) {
Y
Yan Chunwei 已提交
244 245 246 247 248 249 250
    return DeviceInfo::Global().SetRunMode(mode, threads);
  }
  void SetCache(int l1size, int l2size, int l3size) {
    return DeviceInfo::Global().SetCache(l1size, l2size, l3size);
  }
  void SetArch(ARMArch arch) { return DeviceInfo::Global().SetArch(arch); }

251
  lite_api::PowerMode mode() const { return DeviceInfo::Global().mode(); }
Y
Yan Chunwei 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  int threads() const { return DeviceInfo::Global().threads(); }
  ARMArch arch() const { return DeviceInfo::Global().arch(); }
  int l1_cache_size() const { return DeviceInfo::Global().l1_cache_size(); }
  int l2_cache_size() const { return DeviceInfo::Global().l2_cache_size(); }
  int l3_cache_size() const { return DeviceInfo::Global().l3_cache_size(); }
  int llc_size() const { return DeviceInfo::Global().llc_size(); }
  bool has_dot() const { return DeviceInfo::Global().has_dot(); }
  bool has_fp16() const { return DeviceInfo::Global().has_fp16(); }

  template <typename T>
  T* workspace_data() {
    return DeviceInfo::Global().workspace_data<T>();
  }

  bool ExtendWorkspace(size_t size) {
    return DeviceInfo::Global().ExtendWorkspace(size);
  }

  std::string name() const { return "ARMContext"; }
};
#endif

#ifdef LITE_WITH_FPGA
// TODO(tianxiaogang): add needed implementation to context
template <>
class Context<TargetType::kFPGA> {
 public:
  void InitOnce() {}

  FPGAContext& operator=(const FPGAContext& ctx) {}

  void CopySharedTo(FPGAContext* ctx) {}

  std::string name() const { return "FPGAContext"; }
};
#endif

289 290 291 292 293 294 295 296 297
#ifdef LITE_WITH_MLU
template <>
class Context<TargetType::kMLU> {
 public:
  typename Env<TargetType::kMLU>::Devs& devs = Env<TargetType::kMLU>::Global();

  void InitOnce() {}

  MLUContext& operator=(const MLUContext& ctx) {
298
    this->Init(ctx.device_id_, ctx.exec_queue_id_);
299 300 301
    return *this;
  }

302
  void Init(int dev_id, int exec_queue_id = 0) {
303 304 305 306 307 308 309 310 311 312
    CHECK_GT(devs.size(), 0UL)
        << "Env is not initialized or current target is not exit!";
    if (dev_id >= static_cast<int>(devs.size())) {
      LOG(WARNING) << "device index exceeds the number of devices, set to "
                      "default device(0)!";
      device_id_ = 0;
    } else {
      device_id_ = dev_id;
    }
    SetMluDevice(device_id_);
313 314 315 316 317 318

    // get queue id from map
    std::unique_lock<std::mutex> lk(map_mutex_);
    if (queue_id_map_.find(exec_queue_id) == queue_id_map_.end()) {
      queue_id_map_[exec_queue_id] =
          next_queue_id_++ % devs[dev_id].max_queue();
319
    }
320 321 322
    exec_queue_id_ = queue_id_map_[exec_queue_id];
    VLOG(4) << "pick mlu queue id: " << exec_queue_id_;
    lk.unlock();
323

324 325
    io_queue_ = devs[dev_id].io_queues()[exec_queue_id_];
    exec_queue_ = devs[dev_id].exec_queues()[exec_queue_id_];
326 327 328 329 330 331 332 333 334 335 336
  }

  void CopySharedTo(MLUContext* ctx) { ctx->forward_param_ = forward_param_; }

  const cnrtQueue_t& exec_queue() const { return exec_queue_; }
  void SetExecQueue(cnrtQueue_t queue) { exec_queue_ = queue; }

  const cnrtQueue_t& io_queue() const { return io_queue_; }
  void SetIoQueue(cnrtQueue_t queue) { io_queue_ = queue; }

  cnmlCoreVersion_t MLUCoreVersion() {
337
    return paddle::lite::TargetWrapperMlu::MLUCoreVersion();
338 339
  }

340 341 342
  int MLUCoreNumber() {
    return paddle::lite::TargetWrapperMlu::MLUCoreNumber();
  }
343 344 345 346 347 348 349 350 351 352

  u32_t affinity() { return affinity_; }

  cnrtInvokeFuncParam_t forward_param() { return forward_param_; }

  int device_id() { return device_id_; }

  std::string name() const { return "MLUContext"; }

 private:
353 354 355
  static int next_queue_id_;
  static std::map<int, int> queue_id_map_;
  static std::mutex map_mutex_;
356 357 358 359 360 361 362 363 364 365 366 367 368 369
  int device_id_;
  // overall information
  int exec_queue_id_;
  cnrtQueue_t io_queue_;
  cnrtQueue_t exec_queue_;

  std::vector<cnrtNotifier_t> input_notifiers_;
  std::vector<cnrtNotifier_t> output_notifiers_;

  cnrtInvokeFuncParam_t forward_param_;
  u32_t affinity_ = 0x01;
};
#endif  // LITE_WITH_MLU

Y
Yan Chunwei 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
#ifdef LITE_WITH_X86
template <>
class Context<TargetType::kX86> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}

  void CopySharedTo(X86Context* ctx) {}

  std::string name() const { return "X86Context"; }

 private:
  // overall information
  //
  // kernel information
};
#endif

#ifdef LITE_WITH_OPENCL
template <>
class Context<TargetType::kOpenCL> {
391
  std::shared_ptr<CLContext> cl_context_{nullptr};
Y
Yan Chunwei 已提交
392 393 394 395 396

 public:
  CLContext* cl_context() { return cl_context_.get(); }

  void InitOnce() {
397 398 399
    if (CLRuntime::Global()->IsInitSuccess() == false) {
      LOG(ERROR) << "OpenCL runtime init failed";
    }
Y
Yan Chunwei 已提交
400 401 402
    cl_context_ = std::make_shared<CLContext>();
  }

403 404 405 406 407
  void CopySharedTo(OpenCLContext* ctx) {
    if (ctx && cl_context_) {
      ctx->cl_context_ = cl_context_;
    }
  }
Y
Yan Chunwei 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
};
#endif

// Context for running a kernel.
// Holds the necessary resource and information.
class KernelContext {
 public:
  template <typename ContextT>
  ContextT& As() {
    if (!ctx_.valid()) {
      ctx_.set<ContextT>();
    }
    return *ctx_.get_mutable<ContextT>();
  }

 private:
  Any ctx_;
};

// The ContextScheduler helps to assign different context for each kernel.
class ContextScheduler {
 public:
  static ContextScheduler& Global() {
    static auto* x = new ContextScheduler;
    return *x;
  }

435 436 437
  std::unique_ptr<KernelContext> NewContext(
      TargetType target,
      /*only used for cuda context*/ int exec_stream_id = 0) {
Y
Yan Chunwei 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450
    std::unique_ptr<KernelContext> ctx(new KernelContext);
    switch (target) {
      case TARGET(kHost):
        kernel_contexts_[TargetType::kHost].As<HostContext>().CopySharedTo(
            &ctx->As<HostContext>());
        break;
#ifdef LITE_WITH_X86
      case TARGET(kX86):
        kernel_contexts_[TargetType::kX86].As<X86Context>().CopySharedTo(
            &ctx->As<X86Context>());
        break;
#endif
#ifdef LITE_WITH_CUDA
451 452 453
      case TARGET(kCUDA): {
        int dev_id = TargetWrapper<TargetType::kCUDA>::GetCurDevice();
        auto& context = ctx->As<CUDAContext>();
454
        context.Init(dev_id, exec_stream_id);
Y
Yan Chunwei 已提交
455
        kernel_contexts_[TargetType::kCUDA].As<CUDAContext>().CopySharedTo(
456 457
            &context);
      } break;
Y
Yan Chunwei 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470
#endif
#ifdef LITE_WITH_ARM
      case TARGET(kARM):
        kernel_contexts_[TargetType::kARM].As<ARMContext>().CopySharedTo(
            &ctx->As<ARMContext>());
        break;
#endif
#ifdef LITE_WITH_NPU
      case TARGET(kNPU):
        kernel_contexts_[TargetType::kNPU].As<NPUContext>().CopySharedTo(
            &ctx->As<NPUContext>());
        break;
#endif
471 472 473 474 475 476 477
#ifdef LITE_WITH_HUAWEI_ASCEND_NPU
      case TARGET(kHuaweiAscendNPU):
        kernel_contexts_[TargetType::kHuaweiAscendNPU]
            .As<HuaweiAscendNPUContext>()
            .CopySharedTo(&ctx->As<HuaweiAscendNPUContext>());
        break;
#endif
H
hong19860320 已提交
478 479 480 481 482 483
#ifdef LITE_WITH_APU
      case TARGET(kAPU):
        kernel_contexts_[TargetType::kAPU].As<APUContext>().CopySharedTo(
            &ctx->As<APUContext>());
        break;
#endif
484 485 486 487 488 489
#ifdef LITE_WITH_RKNPU
      case TARGET(kRKNPU):
        kernel_contexts_[TargetType::kRKNPU].As<RKNPUContext>().CopySharedTo(
            &ctx->As<RKNPUContext>());
        break;
#endif
490 491 492 493 494 495
#ifdef LITE_WITH_XPU
      case TARGET(kXPU):
        kernel_contexts_[TargetType::kXPU].As<XPUContext>().CopySharedTo(
            &ctx->As<XPUContext>());
        break;
#endif
Y
Yan Chunwei 已提交
496 497 498 499 500 501 502 503 504 505 506
#ifdef LITE_WITH_OPENCL
      case TARGET(kOpenCL):
        kernel_contexts_[TargetType::kOpenCL].As<OpenCLContext>().CopySharedTo(
            &ctx->As<OpenCLContext>());
        break;
#endif
#ifdef LITE_WITH_FPGA
      case TARGET(kFPGA):
        kernel_contexts_[TargetType::kFPGA].As<FPGAContext>().CopySharedTo(
            &ctx->As<FPGAContext>());
        break;
507 508 509 510 511 512
#endif
#ifdef LITE_WITH_BM
      case TARGET(kBM):
        kernel_contexts_[TargetType::kBM].As<BMContext>().CopySharedTo(
            &ctx->As<BMContext>());
        break;
513 514 515 516 517
#endif
#ifdef LITE_WITH_MLU
      case TARGET(kMLU): {
        int dev_id = TargetWrapper<TargetType::kMLU>::GetCurDevice();
        auto& context = ctx->As<MLUContext>();
518
        context.Init(dev_id, exec_stream_id);
519 520 521 522
        kernel_contexts_[TargetType::kMLU].As<MLUContext>().CopySharedTo(
            &context);
        LOG(INFO) << "New Context for MLU";
      } break;
Y
Yan Chunwei 已提交
523 524
#endif
      default:
525
#if (!defined LITE_ON_MODEL_OPTIMIZE_TOOL) && (!defined LITE_WITH_PYTHON)
Y
Yan Chunwei 已提交
526
        LOG(FATAL) << "unsupported target " << TargetToStr(target);
527 528
#endif
        break;
Y
Yan Chunwei 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    }
    return ctx;
  }

 private:
  template <TargetType Type, typename ContextT>
  void InitContext() {
    kernel_contexts_[Type].As<ContextT>().InitOnce();
  }

  ContextScheduler() {
    InitContext<TargetType::kHost, HostContext>();
#ifdef LITE_WITH_X86
    InitContext<TargetType::kX86, X86Context>();
#endif
#ifdef LITE_WITH_CUDA
    InitContext<TargetType::kCUDA, CUDAContext>();
#endif
#ifdef LITE_WITH_ARM
    InitContext<TargetType::kARM, ARMContext>();
#endif
#ifdef LITE_WITH_OPENCL
    InitContext<TargetType::kOpenCL, OpenCLContext>();
#endif
#ifdef LITE_WITH_FPGA
    InitContext<TargetType::kFPGA, FPGAContext>();
#endif
#ifdef LITE_WITH_NPU
    InitContext<TargetType::kNPU, NPUContext>();
558
#endif
559 560 561
#ifdef LITE_WITH_HUAWEI_ASCEND_NPU
    InitContext<TargetType::kHuaweiAscendNPU, HuaweiAscendNPUContext>();
#endif
H
hong19860320 已提交
562 563 564
#ifdef LITE_WITH_APU
    InitContext<TargetType::kAPU, APUContext>();
#endif
565 566 567
#ifdef LITE_WITH_RKNPU
    InitContext<TargetType::kRKNPU, RKNPUContext>();
#endif
568 569
#ifdef LITE_WITH_XPU
    InitContext<TargetType::kXPU, XPUContext>();
570 571 572
#endif
#ifdef LITE_WITH_BM
    InitContext<TargetType::kBM, BMContext>();
573 574 575
#endif
#ifdef LITE_WITH_MLU
    InitContext<TargetType::kMLU, MLUContext>();
Y
Yan Chunwei 已提交
576 577 578 579 580 581 582 583 584
#endif
  }

 private:
  std::map<TargetType, KernelContext> kernel_contexts_;
};

}  // namespace lite
}  // namespace paddle