我的OpenCL代码在GPU上比在CPU上慢

我的OpenCL代码在GPU上比在CPU上慢,opencl,pyopencl,Opencl,Pyopencl,我从OpenCL开始做一些计算机视觉任务。我使用pythonpyopencl模块。我的代码在英特尔cpu上的运行速度比在Nvidia GTX 750Ti上的运行速度快 我有一个将(2000x4000)数组项相乘的示例代码。它在我的cpu上以2ms的速度运行,在我的gpu上以8ms的速度运行。正如您在代码中看到的,所花费的时间只是内核调用 为什么在我的GPU上速度会这么慢 导入时间 将numpy作为np导入 将pyopencl作为cl导入 devices=cl.get_platforms()[1]

我从OpenCL开始做一些计算机视觉任务。我使用python
pyopencl
模块。我的代码在英特尔cpu上的运行速度比在Nvidia GTX 750Ti上的运行速度快

我有一个将(2000x4000)数组项相乘的示例代码。它在我的cpu上以
2ms
的速度运行,在我的gpu上以
8ms的速度运行。正如您在代码中看到的,所花费的时间只是内核调用

为什么在我的GPU上速度会这么慢

导入时间
将numpy作为np导入
将pyopencl作为cl导入
devices=cl.get_platforms()[1]。get_devices()
ctx=cl.Context(设备)
queue=cl.CommandQueue(ctx)
kernel=cl.程序(
ctx“
核子空穴(
全球浮动*a,
全球浮动*b,
全球浮动*
)
{
int行=获取全局id(0);
int col=获取全局id(1);
int cols=获取全局大小(1);
整数索引=列+行*列;
out[index]=a[index]*b[index];
}
“”“).build()
a=np.random.rand(20004000).aType(np.float32)
a_b=cl.Buffer(ctx,cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR,hostbuf=a.flatte())
行,cols=a.shape
out\u b=cl.Buffer(仅ctx,cl.mem\u flags.WRITE\u,size=rows*cols*np.dtype(np.float32).itemsize)
开始=时间。时间()*1000
mult(队列、a.shape、无、a_b、a_b、out_b)
结束=时间。时间()*1000
打印(f“{end-start}ms”)
out=np.empty(a.shape,dtype=np.float32)
cl.enqueue_副本(队列、输出、输出)
#确保结果是正确的
np.testing.assert_数组_equal(a*a,out)
这是
clinfo的输出

> clinfo
Number of platforms                               2
  Platform Name                                   NVIDIA CUDA
  Platform Vendor                                 NVIDIA Corporation
  Platform Version                                OpenCL 1.2 CUDA 9.1.84
  Platform Profile                                FULL_PROFILE
  Platform Extensions                             cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_fp64 cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing cl_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll cl_nv_copy_opts cl_nv_create_buffer
  Platform Extensions function suffix             NV

  Platform Name                                   Intel(R) CPU Runtime for OpenCL(TM) Applications
  Platform Vendor                                 Intel(R) Corporation
  Platform Version                                OpenCL 2.1 LINUX
  Platform Profile                                FULL_PROFILE
  Platform Extensions                             cl_khr_icd cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_byte_addressable_store cl_khr_depth_images cl_khr_3d_image_writes cl_intel_exec_by_local_thread cl_khr_spir cl_khr_fp64 cl_khr_image2d_from_buffer cl_intel_vec_len_hint
  Platform Host timer resolution                  1ns
  Platform Extensions function suffix             INTEL

  Platform Name                                   NVIDIA CUDA
Number of devices                                 1
  Device Name                                     GeForce GTX 750 Ti
  Device Vendor                                   NVIDIA Corporation
  Device Vendor ID                                0x10de
  Device Version                                  OpenCL 1.2 CUDA
  Driver Version                                  390.116
  Device OpenCL C Version                         OpenCL C 1.2
  Device Type                                     GPU
  Device Topology (NV)                            PCI-E, 01:00.0
  Device Profile                                  FULL_PROFILE
  Device Available                                Yes
  Compiler Available                              Yes
  Linker Available                                Yes
  Max compute units                               5
  Max clock frequency                             1084MHz
  Compute Capability (NV)                         5.0
  Device Partition                                (core)
    Max number of sub-devices                     1
    Supported partition types                     None
  Max work item dimensions                        3
  Max work item sizes                             1024x1024x64
  Max work group size                             1024
  Preferred work group size multiple              32
  Warp size (NV)                                  32
  Preferred / native vector sizes
    char                                                 1 / 1
    short                                                1 / 1
    int                                                  1 / 1
    long                                                 1 / 1
    half                                                 0 / 0        (n/a)
    float                                                1 / 1
    double                                               1 / 1        (cl_khr_fp64)
  Half-precision Floating-point support           (n/a)
  Single-precision Floating-point support         (core)
    Denormals                                     Yes
    Infinity and NANs                             Yes
    Round to nearest                              Yes
    Round to zero                                 Yes
    Round to infinity                             Yes
    IEEE754-2008 fused multiply-add               Yes
    Support is emulated in software               No
    Correctly-rounded divide and sqrt operations  Yes
  Double-precision Floating-point support         (cl_khr_fp64)
    Denormals                                     Yes
    Infinity and NANs                             Yes
    Round to nearest                              Yes
    Round to zero                                 Yes
    Round to infinity                             Yes
    IEEE754-2008 fused multiply-add               Yes
    Support is emulated in software               No
  Address bits                                    64, Little-Endian
  Global memory size                              2096300032 (1.952GiB)
  Error Correction support                        No
  Max memory allocation                           524075008 (499.8MiB)
  Unified memory for Host and Device              No
  Integrated memory (NV)                          No
  Minimum alignment for any data type             128 bytes
  Alignment of base address                       4096 bits (512 bytes)
  Global Memory cache type                        Read/Write
  Global Memory cache size                        81920 (80KiB)
  Global Memory cache line size                   128 bytes
  Image support                                   Yes
    Max number of samplers per kernel             32
    Max size for 1D images from buffer            134217728 pixels
    Max 1D or 2D image array size                 2048 images
    Max 2D image size                             16384x16384 pixels
    Max 3D image size                             4096x4096x4096 pixels
    Max number of read image args                 256
    Max number of write image args                16
  Local memory type                               Local
  Local memory size                               49152 (48KiB)
  Registers per block (NV)                        65536
  Max number of constant args                     9
  Max constant buffer size                        65536 (64KiB)
  Max size of kernel argument                     4352 (4.25KiB)
  Queue properties
    Out-of-order execution                        Yes
    Profiling                                     Yes
  Prefer user sync for interop                    No
  Profiling timer resolution                      1000ns
  Execution capabilities
    Run OpenCL kernels                            Yes
    Run native kernels                            No
    Kernel execution timeout (NV)                 Yes
  Concurrent copy and kernel execution (NV)       Yes
    Number of async copy engines                  1
  printf() buffer size                            1048576 (1024KiB)
  Built-in kernels
  Device Extensions                               cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_fp64 cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing cl_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll cl_nv_copy_opts cl_nv_create_buffer

  Platform Name                                   Intel(R) CPU Runtime for OpenCL(TM) Applications
Number of devices                                 1
  Device Name                                     Intel(R) Core(TM) i5-2400 CPU @ 3.10GHz
  Device Vendor                                   Intel(R) Corporation
  Device Vendor ID                                0x8086
  Device Version                                  OpenCL 2.1 (Build 0)
  Driver Version                                  18.1.0.0920
  Device OpenCL C Version                         OpenCL C 2.0
  Device Type                                     CPU
  Device Profile                                  FULL_PROFILE
  Device Available                                Yes
  Compiler Available                              Yes
  Linker Available                                Yes
  Max compute units                               4
  Max clock frequency                             3100MHz
  Device Partition                                (core)
    Max number of sub-devices                     4
    Supported partition types                     by counts, equally, by names (Intel)
  Max work item dimensions                        3
  Max work item sizes                             8192x8192x8192
  Max work group size                             8192
  Preferred work group size multiple              128
  Max sub-groups per work group                   1
  Preferred / native vector sizes
    char                                                 1 / 16
    short                                                1 / 8
    int                                                  1 / 4
    long                                                 1 / 2
    half                                                 0 / 0        (n/a)
    float                                                1 / 8
    double                                               1 / 4        (cl_khr_fp64)
  Half-precision Floating-point support           (n/a)
  Single-precision Floating-point support         (core)
    Denormals                                     Yes
    Infinity and NANs                             Yes
    Round to nearest                              Yes
    Round to zero                                 No
    Round to infinity                             No
    IEEE754-2008 fused multiply-add               No
    Support is emulated in software               No
    Correctly-rounded divide and sqrt operations  No
  Double-precision Floating-point support         (cl_khr_fp64)
    Denormals                                     Yes
    Infinity and NANs                             Yes
    Round to nearest                              Yes
    Round to zero                                 Yes
    Round to infinity                             Yes
    IEEE754-2008 fused multiply-add               Yes
    Support is emulated in software               No
  Address bits                                    64, Little-Endian
  Global memory size                              8308092928 (7.738GiB)
  Error Correction support                        No
  Max memory allocation                           2077023232 (1.934GiB)
  Unified memory for Host and Device              Yes
  Shared Virtual Memory (SVM) capabilities        (core)
    Coarse-grained buffer sharing                 Yes
    Fine-grained buffer sharing                   Yes
    Fine-grained system sharing                   Yes
    Atomics                                       Yes
  Minimum alignment for any data type             128 bytes
  Alignment of base address                       1024 bits (128 bytes)
  Preferred alignment for atomics
    SVM                                           64 bytes
    Global                                        64 bytes
    Local                                         0 bytes
  Max size for global variable                    65536 (64KiB)
  Preferred total size of global vars             65536 (64KiB)
  Global Memory cache type                        Read/Write
  Global Memory cache size                        262144 (256KiB)
  Global Memory cache line size                   64 bytes
  Image support                                   Yes
    Max number of samplers per kernel             480
    Max size for 1D images from buffer            129813952 pixels
    Max 1D or 2D image array size                 2048 images
    Base address alignment for 2D image buffers   64 bytes
    Pitch alignment for 2D image buffers          64 pixels
    Max 2D image size                             16384x16384 pixels
    Max 3D image size                             2048x2048x2048 pixels
    Max number of read image args                 480
    Max number of write image args                480
    Max number of read/write image args           480
  Max number of pipe args                         16
  Max active pipe reservations                    65535
  Max pipe packet size                            1024
  Local memory type                               Global
  Local memory size                               32768 (32KiB)
  Max number of constant args                     480
  Max constant buffer size                        131072 (128KiB)
  Max size of kernel argument                     3840 (3.75KiB)
  Queue properties (on host)
    Out-of-order execution                        Yes
    Profiling                                     Yes
    Local thread execution (Intel)                Yes
  Queue properties (on device)
    Out-of-order execution                        Yes
    Profiling                                     Yes
    Preferred size                                4294967295 (4GiB)
    Max size                                      4294967295 (4GiB)
  Max queues on device                            4294967295
  Max events on device                            4294967295
  Prefer user sync for interop                    No
  Profiling timer resolution                      1ns
  Execution capabilities
    Run OpenCL kernels                            Yes
    Run native kernels                            Yes
    Sub-group independent forward progress        No
    IL version                                    SPIR-V_1.0
    SPIR versions                                 1.2
  printf() buffer size                            1048576 (1024KiB)
  Built-in kernels
  Device Extensions                               cl_khr_icd cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_byte_addressable_store cl_khr_depth_images cl_khr_3d_image_writes cl_intel_exec_by_local_thread cl_khr_spir cl_khr_fp64 cl_khr_image2d_from_buffer cl_intel_vec_len_hint

NULL platform behavior
  clGetPlatformInfo(NULL, CL_PLATFORM_NAME, ...)  No platform
  clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, ...)   No platform
  clCreateContext(NULL, ...) [default]            No platform
  clCreateContext(NULL, ...) [other]              Success [NV]
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_DEFAULT)  No platform
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_CPU)  No platform
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_GPU)  No platform
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_ACCELERATOR)  No platform
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_CUSTOM)  No platform
  clCreateContextFromType(NULL, CL_DEVICE_TYPE_ALL)  No platform

我对pyOpenCL了解不多,但我对OpenCL有点了解

GTX 750 TI有5个计算单元和640个CUDA内核,这意味着您的最佳本地工作大小是
640/5=128
。使用较小/较大的值只会浪费资源。我不知道当您通过'None'时库会做什么,但这是获得性能的一个关键方面。我强烈建议您看看使用了哪些值

一般来说,直接读写全局内存是“慢”的。每个计算单元都有一定数量的本地内存,可以(也应该)加以利用。我不确定这是否适合像您这样简单的内核,但我会尝试将结果存储在本地内存中,然后再传输回主内存。您也可以转换为更大的数据类型,以提高本地和全局内存之间的吞吐量


最后,将数据从GPU传输到GPU比进行实际计算花费更多的时间也就不足为奇了。

我对pyOpenCL不太了解,但我对OpenCL有点了解

GTX 750 TI有5个计算单元和640个CUDA内核,这意味着您的最佳本地工作大小是
640/5=128
。使用较小/较大的值只会浪费资源。我不知道当您通过'None'时库会做什么,但这是获得性能的一个关键方面。我强烈建议您看看使用了哪些值

一般来说,直接读写全局内存是“慢”的。每个计算单元都有一定数量的本地内存,可以(也应该)加以利用。我不确定这是否适合像您这样简单的内核,但我会尝试将结果存储在本地内存中,然后再传输回主内存。您也可以转换为更大的数据类型,以提高本地和全局内存之间的吞吐量


最后,将数据从GPU传输到GPU比执行实际计算花费更多的时间也就不足为奇了。

从CPU到GPU再通过PCIe进行内存传输通常有10µs的延迟,这与传输的数据量无关。这意味着大数据传输效率更高,对于小数据集,延迟可能比CPU上的执行时间长


您的矩阵乘法内核可以优化为运行速度快10倍左右。这里的关键词是使用本地内存进行缓存平铺。其思想是通过一次合并传输将数据块从全局内存加载到本地内存,然后从本地内存一次访问一个元素。这大大减少了全局内存访问延迟,并将大大加快内核速度。

从CPU到GPU以及通过PCIe来回传输的内存延迟通常为10µs左右,与传输的数据量无关。这意味着大数据传输效率更高,对于小数据集,延迟可能比CPU上的执行时间长

您的矩阵乘法内核可以优化为运行速度快10倍左右。这里的关键词是使用本地内存进行缓存平铺。其思想是通过一次合并传输将数据块从全局内存加载到本地内存,然后从本地内存一次访问一个元素。这大大减少了全局内存访问延迟,并将大大加快内核速度