用GPU来运行Python代码

2023-05-16

简介


前几天捣鼓了一下Ubuntu,正是想用一下我旧电脑上的N卡,可以用GPU来跑代码,体验一下多核的快乐。

还好我这破电脑也是支持Cuda的:

$ sudo lshw -C display
  *-display                 
       description: 3D controller
       product: GK208M [GeForce GT 740M]
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a1
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list rom
       configuration: driver=nouveau latency=0
       resources: irq:35 memory:f0000000-f0ffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:6000(size=128)

安装相关工具


首先安装一下Cuda的开发工具,命令如下:

$ sudo apt install nvidia-cuda-toolkit

查看一下相关信息:

$ nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Thu_Nov_18_09:45:30_PST_2021
Cuda compilation tools, release 11.5, V11.5.119
Build cuda_11.5.r11.5/compiler.30672275_0

通过Conda安装相关的依赖包:

conda install numba & conda install cudatoolkit

通过pip安装也可以,一样的。

测试与驱动安装


简单测试了一下,发觉报错了:

$ /home/larry/anaconda3/bin/python /home/larry/code/pkslow-samples/python/src/main/python/cuda/test1.py
Traceback (most recent call last):
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 246, in ensure_initialized
    self.cuInit(0)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 319, in safe_cuda_api_call
    self._check_ctypes_error(fname, retcode)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 387, in _check_ctypes_error
    raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: [100] Call to cuInit results in CUDA_ERROR_NO_DEVICE

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/larry/code/pkslow-samples/python/src/main/python/cuda/test1.py", line 15, in <module>
    gpu_print[1, 2]()
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/compiler.py", line 862, in __getitem__
    return self.configure(*args)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/compiler.py", line 857, in configure
    return _KernelConfiguration(self, griddim, blockdim, stream, sharedmem)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/compiler.py", line 718, in __init__
    ctx = get_context()
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/devices.py", line 220, in get_context
    return _runtime.get_or_create_context(devnum)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/devices.py", line 138, in get_or_create_context
    return self._get_or_create_context_uncached(devnum)
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/devices.py", line 153, in _get_or_create_context_uncached
    with driver.get_active_context() as ac:
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 487, in __enter__
    driver.cuCtxGetCurrent(byref(hctx))
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 284, in __getattr__
    self.ensure_initialized()
  File "/home/larry/anaconda3/lib/python3.9/site-packages/numba/cuda/cudadrv/driver.py", line 250, in ensure_initialized
    raise CudaSupportError(f"Error at driver init: {description}")
numba.cuda.cudadrv.error.CudaSupportError: Error at driver init: Call to cuInit results in CUDA_ERROR_NO_DEVICE (100)

网上搜了一下,发现是驱动问题。通过Ubuntu自带的工具安装显卡驱动:

还是失败:

$ nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

最后,通过命令行安装驱动,成功解决这个问题:

$ sudo apt install nvidia-driver-470

检查后发现正常了:

$ nvidia-smi 
Wed Dec  7 22:13:49 2022       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 470.161.03   Driver Version: 470.161.03   CUDA Version: 11.4     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0 N/A |                  N/A |
| N/A   51C    P8    N/A /  N/A |      4MiB /  2004MiB |     N/A      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

测试代码也可以跑了。

测试Python代码


打印ID


准备以下代码:

from numba import cuda
import os

defcpu_print():
    print('cpu print')


@cuda.jitdefgpu_print():
    dataIndex = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x
    print('gpu print ', cuda.threadIdx.x, cuda.blockIdx.x, cuda.blockDim.x, dataIndex)


if __name__ == '__main__':
    gpu_print[4, 4]()
    cuda.synchronize()
    cpu_print()

这个代码主要有两个函数,一个是用CPU执行,一个是用GPU执行,执行打印操作。关键在于@cuda.jit这个注解,让代码在GPU上执行。运行结果如下:

$ /home/larry/anaconda3/bin/python /home/larry/code/pkslow-samples/python/src/main/python/cuda/print_test.py
gpu print  0 3 4 12
gpu print  1 3 4 13
gpu print  2 3 4 14
gpu print  3 3 4 15
gpu print  0 2 4 8
gpu print  1 2 4 9
gpu print  2 2 4 10
gpu print  3 2 4 11
gpu print  0 1 4 4
gpu print  1 1 4 5
gpu print  2 1 4 6
gpu print  3 1 4 7
gpu print  0 0 4 0
gpu print  1 0 4 1
gpu print  2 0 4 2
gpu print  3 0 4 3
cpu print

可以看到GPU总共打印了16次,使用了不同的Thread来执行。这次每次打印的结果都可能不同,因为提交GPU是异步执行的,无法确保哪个单元先执行。同时也需要调用同步函数cuda.synchronize(),确保GPU执行完再继续往下跑。

查看时间


我们通过这个函数来看GPU并行的力量:

from numba import jit, cuda
import numpy as np
# to measure exec time
from timeit import default_timer as timer


# normal function to run on cpu
def func(a):
    for i in range(10000000):
        a[i] += 1


# function optimized to run on gpu
@jit(target_backend='cuda')
def func2(a):
    for i in range(10000000):
        a[i] += 1


if __name__ == "__main__":
    n = 10000000
    a = np.ones(n, dtype=np.float64)

    start = timer()
    func(a)
    print("without GPU:", timer() - start)

    start = timer()
    func2(a)
    print("with GPU:", timer() - start)

结果如下:

$ /home/larry/anaconda3/bin/python /home/larry/code/pkslow-samples/python/src/main/python/cuda/time_test.py
without GPU: 3.7136273959999926
with GPU: 0.4040513340000871

可以看到使用CPU需要3.7秒,而GPU则只要0.4秒,还是能快不少的。当然这里不是说GPU一定比CPU快,具体要看任务的类型。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用GPU来运行Python代码 的相关文章

随机推荐

  • 互连网络的定义

    原文 xff1a http julong com cn Service FAQview asp FAQID 61 15 互联网络是一通过中间网络设备连接多个独立网络的集合 xff0c 其功能是形成一个覆盖范围更广的网络 网络互联技术意指工业
  • Win11本地安装Ubuntu 22.04 双系统简易教程

    1 制作启动U盘 首先找到一个硬盘容量不小于4G的空U盘 xff0c 需要对其进行格式化 然后下载Ubuntu 22 04的iso文件到本地 Ubuntu 22 04 1 LTS 中国地区下载链接 下载 UltraISO并制作启动U盘 Ul
  • 图文详解VMWare Workstation安装Ubuntu20.04虚拟机

    图文详解VMWare Workstation安装Ubuntu20 04虚拟机 0 准备工作1 新建虚拟机并进行初始配置2 安装虚拟机系统 0 准备工作 在使用VMWare Workstation进行Ubuntu20 04虚拟机安装前 xff
  • 理解数据库中的undo日志、redo日志、检查点

    数据库存放数据的文件 xff0c 本文称其为data file 数据库的内容在内存里是有缓存的 xff0c 这里命名为db buffer 某次操作 xff0c 我们取了数据库某表格中的数据 xff0c 这个数据会在内存中缓存一些时间 对这个
  • Token原理

    Q xff1a 分布式场景下如何生成token以及使用token的流程 xff1a 在分布式场景下 xff0c 可以采用以下方式生成 token 和进行权限认证 xff1a 1 生成 token xff1a 使用JWT xff08 JSON
  • 红外遥控其实so easy-第2季第2部分-朱有鹏-专题视频课程

    红外遥控其实so easy 第2季第2部分 1521人已学习 课程介绍 本课程是 朱有鹏老师单片机完全学习系列课程 第2季第2个课程 xff0c 主要讲解如何用单片机进行红外遥控解码 红外遥控是家电产品常用的控制方法 xff0c 通过本课程
  • idea ctrl+左键找到方法引用,选择 All Places的方法

    有时候在idea里点击某个方法想找到该方法在所有地方的引用 xff0c 但是有时候会发现idea默认是在项目文件里搜索 xff0c 这样就搜索不到jar包里的引用 xff0c 如果没有搜到项目里的引用 xff0c 弹窗就会一闪而过 xff0
  • 优雅地解决NullPointException

    null的困扰 通过上面代码示例 xff0c 我们可以发现使用null可能会带来的一系列困扰 xff1a 空指针异常 xff0c 导致代码运行时变得不可靠 xff0c 稍不留神可能就崩了使代码膨胀 xff0c 导致代码中充斥大量的null检
  • springboot 如何配置tomcat信息

    前言 前两天面试的时候 xff0c 面试官问我 xff1a 一个ip发请求过来 xff0c 是一个ip对应一个线程吗 xff1f 我突然愣住了 xff0c 对于SpringBoot如何处理请求好像从来没仔细思考过 xff0c 所以面试结束后
  • Visio2013里面的大括号

    打开Visio2013 xff0c 在左侧的 形状 里面 xff0c 选择 更多形状 gt 其他 Visio 方案 gt 标注 xff0c 然后就会在下面看到大括号了 xff0c 这个括号可以调整方向的 xff0c 把括号拉进 Visio
  • CNN几种经典模型比较

    LeNet5 LeNet5 诞生于 1994 年 xff0c 是最早的卷积神经网络之一 xff0c 并且推动了深度学习领域的发展 自从 1988 年开始 xff0c 在许多次成功的迭代后 xff0c 这项由 Yann LeCun 完成的开拓
  • matlab用mkdir在指定的文件夹下创建新的文件夹,并把图像保存在该文件夹内

    for i 61 1 size query image index 2 mkdir 39 指定的文件夹 39 num2str query image index i 在指定的文件路径下以变量名为名字创建新的文件夹 C 61 imgNamLi
  • MySQL安装之后如何启动

    安装好MySQL之后 xff0c 在MySQL的安装目录下找到MySQL server 的目录 xff08 默认安装目录在 xff1a C Program Files MySQL MySQL Server 5 7 xff09 xff0c 如
  • mysql 密码输入正确,登陆失败的原因

    从命令行输入密码登录mysql 的时候 xff0c 当密码输入正确 xff0c 而且出现如下提示的时候 xff1a 可能是因为你的mysql没有启动的原因造成的 xff0c 解决方法 xff1a 鼠标右键 我的电脑 xff08 或者是计算机
  • vo和dto的区别

    下面转自百度知道里的内容 xff0c 感觉是把dto和vo说反了 xff0c 但是也不排除确实有项目这么做的情况 xff0c 欢迎大家发表自己的意见 xff0c 我个人认为两者说反了 xff0c 不过说的还是通俗易懂的 按照标准来说 xff
  • java日期去掉时分秒,只保留年月日

    public class Test public static void main String args SimpleDateFormat sdf 61 new SimpleDateFormat 34 yyyy MM dd 34 Cale
  • 51单片机也能玩TFT彩屏-第2季第3部分-朱有鹏-专题视频课程

    51单片机也能玩TFT彩屏 第2季第3部分 2125人已学习 课程介绍 本课程是 朱有鹏老师单片机完全学习系列课程 第2季第3个课程 xff0c 主要讲解TFT液晶显示器的原理和编程显示线条 文字 图片等 本课程的学习目标是对较复杂的TFT
  • 大数据hadoop hdfs 读写流程

    1 HDFS读流程 1 首先调用FileSystem对象的open 方法 xff0c 其实获取的是一个DistributedFileSystem的实例 2 DistributedFileSystem用RPC调用元数据节点 xff0c 得到文
  • C#初学者教程系列19:Winform应用程序

    本文是C 初学者简单教程 xff0c 这是第19篇 感谢观看 xff0c 记得关注我 xff0c 后续还有更多教程文章 xff0c 谢谢 本文环境为Visual Studio 2019 一 Winform应用程序 Windows窗体应用程序
  • 用GPU来运行Python代码

    简介 前几天捣鼓了一下Ubuntu xff0c 正是想用一下我旧电脑上的N卡 xff0c 可以用GPU来跑代码 xff0c 体验一下多核的快乐 还好我这破电脑也是支持Cuda的 xff1a sudo lshw C display displ