context.h 9.4 KB
Newer Older
S
superjomn 已提交
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.

#pragma once
S
superjomn 已提交
16

17
#include "paddle/fluid/lite/utils/any.h"
S
superjomn 已提交
18
#ifdef LITE_WITH_CUDA
Y
Yan Chunwei 已提交
19
#include "paddle/fluid/lite/cuda/blas.h"
S
superjomn 已提交
20 21
#include "paddle/fluid/lite/cuda/cuda_utils.h"
#endif
Y
Yan Chunwei 已提交
22 23 24 25
#ifdef LITE_WITH_X86
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/device_context.h"
#endif
C
Chunwei 已提交
26 27 28 29 30
#ifdef LITE_WITH_OPENCL
#include "paddle/fluid/lite/opencl/cl_context.h"
#include "paddle/fluid/lite/opencl/cl_engine.h"
#include "paddle/fluid/lite/opencl/cl_helper.h"
#endif
31
#include <map>
S
superjomn 已提交
32
#include <memory>
S
superjomn 已提交
33
#include <set>
34 35
#include <string>
#include <utility>
S
superjomn 已提交
36
#include <vector>
T
tensor-tang 已提交
37 38
#include "paddle/fluid/lite/core/cpu_info.h"
#include "paddle/fluid/lite/core/lite_tensor.h"
S
superjomn 已提交
39
#include "paddle/fluid/lite/core/target_wrapper.h"
40
#include "paddle/fluid/lite/utils/all.h"
S
superjomn 已提交
41

C
Chunwei 已提交
42 43 44 45
#ifdef LITE_WITH_OPENCL
DECLARE_string(cl_path);
#endif

S
superjomn 已提交
46 47 48
namespace paddle {
namespace lite {

49 50 51 52 53 54 55
template <TargetType Type>
class Context;

using HostContext = Context<TargetType::kHost>;
using X86Context = Context<TargetType::kX86>;
using CUDAContext = Context<TargetType::kCUDA>;
using ARMContext = Context<TargetType::kARM>;
C
Chunwei 已提交
56
using OpenClContext = Context<TargetType::kOpenCL>;
57 58 59 60 61 62 63

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

C
Chunwei 已提交
64
  void CopySharedTo(const HostContext* ctx) {}
65 66 67

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

#ifdef LITE_WITH_ARM
T
tensor-tang 已提交
70

71 72
template <>
class Context<TargetType::kARM> {
T
tensor-tang 已提交
73
 public:
74
  Context() {}
75
  explicit Context(const ARMContext& ctx);
T
tensor-tang 已提交
76

77
  ARMContext& operator=(const ARMContext& ctx) {}
T
tensor-tang 已提交
78

79
  // NOTE: InitOnce should only be used by ContextScheduler
H
hong19860320 已提交
80
  void InitOnce() { DeviceInfo::Init(); }
81

C
Chunwei 已提交
82
  void CopySharedTo(const ARMContext* ctx) {}
83

84 85 86 87 88 89 90
  void SetRunMode(PowerMode mode, int threads) {
    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); }
T
tensor-tang 已提交
91

92 93 94
  PowerMode mode() const { return DeviceInfo::Global().mode(); }
  int threads() const { return DeviceInfo::Global().threads(); }
  ARMArch arch() const { return DeviceInfo::Global().arch(); }
H
hong19860320 已提交
95 96 97
  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(); }
T
tensor-tang 已提交
98 99 100

  template <typename T>
  T* workspace_data() {
101
    return DeviceInfo::Global().workspace_data<T>();
T
tensor-tang 已提交
102 103
  }

104 105 106
  bool ExtendWorkspace(DDimLite dims) {
    return DeviceInfo::Global().ExtendWorkspace(dims);
  }
T
tensor-tang 已提交
107

108
  std::string name() const { return "ARMContext"; }
T
tensor-tang 已提交
109
};
110 111
#endif

S
superjomn 已提交
112 113
#ifdef LITE_WITH_CUDA
// Only works with CUDA kernels.
114 115 116 117 118 119 120 121
template <>
class Context<TargetType::kCUDA> {
 public:
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {
    cublas_fp32_ = std::make_shared<lite::cuda::Blas<float>>();
  }

C
Chunwei 已提交
122
  void CopySharedTo(const CUDAContext* ctx) {
123 124 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
    CHECK(ctx);
    CHECK(cublas_fp32_) << "cublas_fp32 should be set first";
    ctx->cublas_fp32_ = cublas_fp32_;
  }

  const cudaStream_t exec_stream() { return exec_stream_; }
  void SetExecStream(cudaStream_t stream) { exec_stream_ = stream; }

  const cudaStream_t io_stream() { return io_stream_; }
  void SetIoStream(cudaStream_t stream) { io_stream_ = stream; }

  std::shared_ptr<cuda::Blas<float>> cublas_fp32() { return cublas_fp32_; }
  void SetCuBlasFP32(std::shared_ptr<cuda::Blas<float>> cublas_fp32) {
    cublas_fp32_ = cublas_fp32;
  }

  const std::vector<cudaEvent_t>& input_events() { return input_events_; }
  void SetInputEvents(const std::vector<cudaEvent_t>& input_events) {
    input_events_.clear();
    input_events_.assign(input_events.begin(), input_events.end());
  }

  const std::vector<cudaEvent_t>& output_events() { return output_events_; }
  void SetOutputEvents(const std::vector<cudaEvent_t>& output_events) {
    output_events_.clear();
    output_events_.assign(output_events.begin(), output_events.end());
  }

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

 private:
S
superjomn 已提交
154
  // overall information
155 156
  cudaStream_t exec_stream_;
  cudaStream_t io_stream_;
S
superjomn 已提交
157 158

  // not thread-safe, should allocate for each thread.
159
  std::shared_ptr<cuda::Blas<float>> cublas_fp32_;
S
superjomn 已提交
160 161

  // kernel information
162 163
  std::vector<cudaEvent_t> input_events_;
  std::vector<cudaEvent_t> output_events_;
S
superjomn 已提交
164 165 166 167
};
#endif

#ifdef LITE_WITH_X86
168 169 170 171 172 173 174 175 176 177 178 179
template <>
class Context<TargetType::kX86> {
 public:
  using device_ctx_t = ::paddle::platform::CPUDeviceContext;
  using execution_ctx_t = ::paddle::framework::ExecutionContext;

  Context() {
    x86_device_context_.reset(new ::paddle::platform::CPUDeviceContext);
    x86_execution_context_.reset(
        new ::paddle::framework::ExecutionContext(*x86_device_context_));
  }

180 181 182 183 184
  Context(Context&& ctx) {
    x86_device_context_ = std::move(ctx.x86_device_context_);
    x86_execution_context_ = std::move(ctx.x86_execution_context_);
  }

185 186 187
  // NOTE: InitOnce should only be used by ContextScheduler
  void InitOnce() {}

C
Chunwei 已提交
188
  void CopySharedTo(const X86Context* ctx) {}
189 190 191 192 193 194 195 196 197 198 199

  const device_ctx_t* x86_device_context() { return x86_device_context_.get(); }
  void SetX86DeviceContext(std::unique_ptr<device_ctx_t>&& ctx) {
    x86_device_context_ = std::move(ctx);
  }

  const execution_ctx_t* x86_execution_context() {
    return x86_execution_context_.get();
  }
  void SetX86ExecutionContext(std::unique_ptr<execution_ctx_t>&& ctx) {
    x86_execution_context_ = std::move(ctx);
200
  }
201 202 203 204 205 206

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

 private:
  // overall information
  //
S
superjomn 已提交
207
  // kernel information
Y
Yan Chunwei 已提交
208 209

  // legacy info.
210 211
  std::unique_ptr<device_ctx_t> x86_device_context_;
  std::unique_ptr<execution_ctx_t> x86_execution_context_;
S
superjomn 已提交
212 213 214
};
#endif

C
Chunwei 已提交
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
#ifdef LITE_WITH_OPENCL
template <>
class Context<TargetType::kOpenCL> {
  mutable std::shared_ptr<CLContext> cl_context_;
  mutable std::shared_ptr<CLHelper> cl_helper_;

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

  void InitOnce() {
    // Init cl engine.
    CHECK(CLEngine::Global()->IsInitSuccess()) << "OpenCL engine init failed";
    CLEngine::Global()->set_cl_path(FLAGS_cl_path);

    cl_context_ = std::make_shared<CLContext>();
    cl_helper_ = std::make_shared<CLHelper>();
    cl_helper_->set_context(cl_context_.get());

    PrepareKernels();
  }

  void CopySharedTo(const OpenClContext* ctx) {
    ctx->cl_context_ = cl_context_;
  }

 private:
  void PrepareKernels() {
    cl_helper_->AddKernel("elementwise_add", "elementwise_add_kernel.cl");
    cl_helper_->AddKernel("pool_max", "pool_kernel.cl");
  }
};
#endif

S
superjomn 已提交
249 250 251 252
// Context for running a kernel.
// Holds the necessary resource and information.
class KernelContext {
 public:
253 254 255 256
  template <typename ContextT>
  ContextT& As() {
    if (!ctx_.valid()) {
      ctx_.set<ContextT>();
257
    }
258
    return *ctx_.get_mutable<ContextT>();
259 260 261
  }

 private:
262
  Any ctx_;
S
superjomn 已提交
263 264
};

265 266 267 268 269 270 271 272 273 274 275 276
// The ContextScheduler helps to assign different context for each kernel.
class ContextScheduler {
 public:
  static ContextScheduler& Global() {
    static auto* x = new ContextScheduler;
    return *x;
  }

  std::unique_ptr<KernelContext> NewContext(TargetType target) {
    std::unique_ptr<KernelContext> ctx(new KernelContext);
    switch (target) {
      case TARGET(kHost):
C
Chunwei 已提交
277
        kernel_contexts_[TargetType::kHost].As<HostContext>().CopySharedTo(
278 279 280 281
            &ctx->As<HostContext>());
        break;
#ifdef LITE_WITH_X86
      case TARGET(kX86):
C
Chunwei 已提交
282
        kernel_contexts_[TargetType::kX86].As<X86Context>().CopySharedTo(
283 284 285 286 287
            &ctx->As<X86Context>());
        break;
#endif
#ifdef LITE_WITH_CUDA
      case TARGET(kCUDA):
C
Chunwei 已提交
288
        kernel_contexts_[TargetType::kCUDA].As<CUDAContext>().CopySharedTo(
289 290 291 292 293
            &ctx->As<CUDAContext>());
        break;
#endif
#ifdef LITE_WITH_ARM
      case TARGET(kARM):
C
Chunwei 已提交
294
        kernel_contexts_[TargetType::kARM].As<ARMContext>().CopySharedTo(
295 296
            &ctx->As<ARMContext>());
        break;
C
Chunwei 已提交
297 298 299 300 301 302
#endif
#ifdef LITE_WITH_OPENCL
      case TARGET(kOpenCL):
        kernel_contexts_[TargetType::kOpenCL].As<OpenClContext>().CopySharedTo(
            &ctx->As<OpenClContext>());
        break;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
#endif
      default:
        LOG(FATAL) << "unsupported target " << TargetToStr(target);
    }
    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>();
C
Chunwei 已提交
326 327 328
#endif
#ifdef LITE_WITH_OPENCL
    InitContext<TargetType::kOpenCL, OpenClContext>();
329 330 331 332 333 334 335
#endif
  }

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

S
superjomn 已提交
336 337
}  // namespace lite
}  // namespace paddle