文字稿 · CC BY 4.0

面向 Python 程序员的 CUDA 入门——Jeremy Howard

本页标题、字幕、摘要和阅读笔记为已保存的 AI 译文,可能有误。时间戳与来源一致,可展开查看原始字幕,并对照原视频核对。

Jeremy Howard 面向 Python 开发者介绍 CUDA 中的 NVIDIA GPU 编程,讲解并行内核、C++ 张量集成和调试工作流程。

Jeremy Howard · 发布于 · 1 小时 18 分钟 · 英语 · 许可:CC BY 4.0 · 来源:在 YouTube 上观看

文字稿来源:创作者上传至 YouTube 的字幕。AI 标点由 Vidleaf 添加;原始措辞和时间戳锚点均保留。原始文字稿见下方。

AI 生成的摘要

Answer.AI 的 Jeremy Howard 带来“CUDA 入门”演讲,他认为只要掌握一些技巧,CUDA 并没有那么难;相关工作在 notebook 中通过 PyTorch 完成,CUDA mode GitHub 仓库中还有一个 Colab 版本,无需 GPU 即可免费运行,但运行时需要设置为 T4 GPU。无需预先学习任何课程,示例遵循《Programming Massively Parallel Processes》的部分内容。本次课程首先大量使用旧版 PyTorch 来建立概念,然后将其转换为 CUDA,从第 2 章的 RGB 转灰度任务开始,使用亮度公式:0.21 红、0.72 绿和 0.07 蓝;将像素展平为向量,并在 i 处索引红色、在 i 加 n 处索引绿色、在 i 加 2n 处索引蓝色,速度极慢,耗时近两秒。之所以需要 CUDA,是因为 RTX 3090 拥有 82 个 SM,每个 SM 有 128 个 CUDA 核心,因此移除内层循环并将其编写为内核;Python 的 run_kernel 模拟可复现完全相同的语义,但没有并行加速,而 CUDA 将范围划分为大小为 256 的块,内核运行器是一对嵌套循环,其中当前索引等于块索引乘以块维度再加上线程索引,线程数始终为 256,并且有一个保护检查确保索引不超过像素数量。块之所以重要,是因为线程块中的线程共享共享内存、可以同步,并在同一个流式多处理器上执行。设置过程安装构建工具和 WorldLitza,并使用 torch.utils.cpp 扩展中 PyTorch 的 LoadInline,通过名为 LoadCuda 的封装进行简化,将 CUDA 代码字符串编译为 Python 模块;推荐的方法是将 Python 内核粘贴到 ChatGPT 中,并要求它转换为等效的 C 代码,结果基本完美,尽管它假设使用浮点数。在 1.7 百万像素上,运行时间从约一秒半降至一毫秒。接着在 MNIST 数据上用纯 Python 实现矩阵乘法,然后作为 CUDA 风格的 2D 内核实现,将每个输出单元分配给一个线程,每个块 16 乘 16 个线程;在整个 MNIST 数据集上,CUDA 耗时 6 毫秒,而优化的 CPU 方法耗时 1.3 秒,PyTorch 的 matmul 耗时 2 毫秒,其速度更快尤其得益于使用共享内存。演讲者鼓励 Python 程序员和数据科学家尝试 CUDA,指出它可以在 notebook 中完成,并且对于 flash attention、量化、GPTQ、AWQ 和 bits and bytes 等事物越来越重要。第二部分解释如何使用 Conda 设置 CUDA 环境,将其理解为 Docker 的替代品而非 PIP 或 poetry 的替代品:Conda 允许并行运行多个版本的 Python、CUDA 和 C++ 编译系统并在它们之间切换,避免令人困惑的 .run 文件和 Ubuntu 软件包。一个小型安装脚本检测所需的 MiniConda 和你的 shell,下载并安装它,之后重启终端;然后检查 PyTorch 需要哪个 CUDA 版本,用该版本替换运行一个 shell 命令来安装 NVIDIA 的分析、调试和构建工具套件,并安装去掉 -nightly 标志的 PyTorch。Conda 过去由于较旧的求解器而速度较慢,但现代默认求解器应使其运行非常快。该设置可在 Windows 上的 WSL 以及 Ubuntu、Fedora 和 Debian 上运行,不过 CUDA 在 Mac 上无法工作。

根据文字稿生成。请对照原始视频核查所链接的段落。

带时间戳的章节摘要

CUDA 入门

CUDA 的声誉与基于 notebook 的方法

  • [0:01] 来自 Answer.AI 的 Jeremy Howard 带来“CUDA 入门”,用于对 NVIDIA GPU 进行编程,以获得速度和最大灵活性。
  • [0:17] CUDA 素有难以上手的名声,但 Howard 表示,一旦掌握一些技巧,其实并没有那么糟。
  • [0:38] 得益于 PyTorch 提供的魔力,所有工作都在 notebook 中完成,而不是编译器和终端。

通过 CUDA mode 仓库和 Colab 跟随学习

  • [0:55] Howard 强烈建议在你自己的电脑上跟随操作。
  • [1:03] 在 GitHub 上的 CUDA mode 组织中,Lecture 2 仓库包含一个 Lecture 3 文件夹;这是 CUDA mode 系列的第 3 讲,跟随学习不需要之前的讲座。
  • [1:25] readme 的 Lecture 3 部分链接到一个 Colab 版本,即使没有可用的 GPU 也能免费运行。

配套书籍与讲座顺序

  • [1:39] 这些示例遵循《Programming Massively Parallel Processes》一书的部分内容,Howard 推荐通过它深入学习。
  • [1:57] 完成今天的课程后,你应该能够很好地开始阅读这本书,它更详细地涵盖了这些内容。
  • [2:16] Lecture 2 深入讲解了该书的第 1 到 3 章,所以为了了解更多细节,你可能会困惑地想要在本 Lecture 3 之后学习 Lecture 2。

从 PyTorch 到 CUDA:环境设置与第一个练习

工作流程:先 PyTorch,再转换为 CUDA

  • [2:35] 课程首先大量使用旧版 PyTorch 来建立概念,然后尝试将每一项转换为 CUDA。

使用 T4 GPU 设置 Colab

  • [2:56] 工作在 Colab 中完成,运行时环境应设置为 T4 GPU,它可以免费大量使用,并且足以轻松运行今天涵盖的所有内容。
  • [3:18] 运行时启动后,就可以导入所需的库并开始第一个练习。

来自第 2 章的第一个练习

  • [3:23] 第一个练习来自该书的第 2 章,它教你如何继续。

使用 CUDA 内核进行 RGB 到灰度转换

亮度公式与图像加载

  • [3:31] 任务是使用推荐的亮度公式将 RGB 彩色图像转换为灰度图:红色占 0.21、绿色占 0.72、蓝色占 0.07,然后求和。
  • [3:55] 这种标准的 RGB 转灰度方法将实现为 CUDA 内核。
  • [4:07] 从 URL 下载一张小狗图片,并使用 torchvision.io 加载,该库已包含在 Colab 中。
  • [4:35] 加载的图像形状为 3 乘 1066 乘 1600,讲者假设听众具备基础 PyTorch 知识,否则推荐学习 course.fast.ai。

张量布局与图像显示

  • [5:31] 该图像是一个秩为 3 的张量,包含三个通道、1066 行(高度)和 1600 列(宽度),以无符号 8 位整数存储。
  • [6:12] show_image 函数会创建 matplotlib 绘图、移除坐标轴,并对彩色图像使用置换 1 2 0 将轴顺序从通道-高度-宽度重排为高度-宽度-通道。
  • [6:46] 在切换到 CUDA 之前,先将图像缩放使其最小维度为 150,得到 150 乘 225 的形状,共 33,750 个像素,每个像素都有 R、G、B 值。

通过展平遍历像素

  • [7:24] 灰度转换会遍历每个像素、应用公式,并将结果存入输出。
  • [7:55] 像素数量按高度乘以宽度计算,遍历所有像素的一种简便方法是将其展平为一个向量。
  • [8:24] 在内存中,数据按一个通道面接一个通道面排列,每个面内先按行再按列。
  • [9:37] 对于高度 2、宽度 3、3 通道的示例,展平会生成一个向量,其中各通道块连续排列。
  • [10:09] 尽管图像被视为通道,但计算机内存是线性排列的,因此展平会将通道-高度-宽度变为一个大向量。

展平后的 RGB 转灰度转换

索引展平后的通道值

  • [10:59] 结果初始化为长度为 n 的空向量,循环遍历从 0 到 n 减 1 的所有 n 个值。
  • [11:06] 每个输出值由约 0.29 倍的输入值 x i(红色分量)加上 0.59 倍的 x i 加 n(绿色分量)组合而成。
  • [11:32] 这里 n 是 1、2、3、4、5、6 个像素的距离,因此访问绿色需要跳到 i 加 n,访问蓝色需要跳到 i 加 2n。
  • [12:04] 图像被展平并直接索引,然后将灰度结果重塑为高度乘宽度。

展平方法的性能

  • [12:26] 展平后的图像是一个单一向量,所有通道值都按所述方式展平。
  • [12:35] 这种方法极其缓慢,处理图像需要将近两秒。

RTX 3090 上的 CUDA 并行计算

CUDA 为何能加速像素处理

  • [12:44] 仅输入 34,000 个像素,就需要 CUDA 来加速处理。
  • [12:55] CUDA 之所以能加速,是因为它的设置方式与普通 CPU 截然不同。

RTX 3090 硬件:SM 与 CUDA 核心

  • [13:16] RTX 3090 被描述为一款出色的 GPU,二手购买性价比相当高,因此是特别适合爱好者的绝佳选择。
  • [13:31] 一块 3090 拥有 82 个 SM,其中 SM 是流式多处理器,可以将其视为计算机中几乎独立的 CPU。
  • [13:50] 每个 SM 拥有 128 个 CUDA 核心,核心与多处理器都可以同时运行。
  • [14:06] 128 乘以 82 总共得到 10,500 个 CUDA 核心,它们可以同时工作,远超任何常见的 CPU。
  • [14:26] 3090 并非顶级型号;它是一款非常好的 GPU,但有些 GPU 拥有更多的 CUDA 核心。

将内层循环提取为内核

  • [14:32] 要利用所有核心,代码必须设置成能让一段代码同时运行在许多不同的数据和内存上。
  • [15:02] CUDA 将内层循环提取出来,这部分可以同时运行 10,000 次,且各次迭代互不影响。
  • [15:13] 这些迭代只是将内容写入输出内存,无法从 CUDA 内核返回值。
  • [15:25] 内核只能以执行顺序未知的方式修改内存,因为有些可能比其他稍早运行。

编写并启动内核

  • [15:34] CUDA 要求你编写一个函数,其中包含需要按需调用数十、数百、数千甚至数百万次的代码行。
  • [15:56] CUDA 会尽可能并行运行它,在 3090 上最多同时处理 10,000 项任务,速度尽可能快。
  • [16:10] 除了编写代码行,你还必须说明调用多少次。
  • [16:21] 内核会以请求的参数为你调用:输入数组张量、输出张量,以及每个通道中的像素数量。

在 Python 中模拟 CUDA 内核执行

Python run_kernel 循环模拟

  • [16:42] 可以用单个 for 循环在 Python 中模拟 CUDA 内核,它不会并行运行,因此不会加速,但产生的语义与 CUDA 完全相同。
  • [16:56] run_kernel 函数接收一个函数、运行次数和参数,每次调用该函数时传入索引、时间和请求的参数。
  • [17:23] 初始化部分获取通道数、高度和宽度,计算像素数,将其展平,并创建结果张量。
  • [17:35] 代码没有直接调用循环,而是调用 run_kernel,传入函数名 f、作为循环次数的像素数以及参数 out、x 和 n。

最小依赖与概念等价性

  • [18:00] 该实现完全不使用外部库,仅使用纯 Python 和少量 PyTorch,刚好足以创建张量并对张量进行索引。
  • [18:26] 从概念上讲,它所做的与 CUDA 内核几乎相同,而了解这些迭代是独立运行的,就能看出工作可以如何并行化,这正是 CUDA 所做的。

CUDA 块与单个循环

  • [18:55] CUDA 并不像 Python 中的 range n 那样简单地创建一个单一的数字列表并依次将每个数字传入内核;它将范围拆分成块。
  • [19:19] 例如,要处理约 1,000 个像素时,CUDA 将它们按每次 256 个分组为块。
  • [19:39] 实际上,CUDA 内核运行器并不是循环 n 次的单个 for 循环,而是一对嵌套的 for 循环。

块、线程与索引计算

  • [19:49] 你传入的不是单个像素数,而是两个数字:块数和线程数,它们可以是任意数字。
  • [20:07] 如果这两个数字相乘等于所需的 n,嵌套循环所做的就完全相同,传入外层循环索引、内层循环索引以及内层循环遍历的次数。
  • [20:28] 在内核内部,当前索引通过将块索引乘以块维度(线程数)再加上内层循环索引 j 得到。

CUDA 线程索引与边界保护

CUDA 中的全局索引公式

  • [20:51] 在内核内部,作为 i 和 j 线程传入的值分别称为块索引、线程索引和块维度。
  • [21:03] CUDA 书籍将索引定义为块索引乘以块维度再加上线程索引,其中带有一个 .x 分量,目前可以忽略。
  • [21:19] 实际上,CUDA 的块是有编号的,每个块包含线程,块只是携带诸如 0、1 等编号。

选择 256 个线程和块数

  • [21:40] 在实践中,线程数总是设为 256,这被认为是一个几乎总是安全的良好默认值。
  • [22:05] 使用 256 个线程时,内核运行器中的内层循环会被调用 256 次,因此块数等于像素数除以 256 后向上取整。
  • [22:41] 对块数向上取整可确保内核被调用足够多次。

防止越界访问

  • [22:49] 由于所需的调用次数(此前等于像素数)可能不是 256 的倍数,内核可能会越界。
  • [23:02] 一个 if 语句会检查当前索引是否超过像素数;这几乎出现在每个 CUDA 内核中,被称为保护或保护块。
  • [23:22] 该内核保留与之前相同的代码行,并加入索引计算和保护,构成了任何 CUDA 内核相当标准的前几行。

CUDA 为何使用块和线程

块级共享内存与同步

  • [24:08] CUDA 让同一线程块中的每个线程都能访问共享内存并有机会进行同步。
  • [24:29] 同步意味着一个块中的所有线程都必须到达某个给定点,执行才能继续。
  • [24:35] 一个块中的所有线程都在同一个流式多处理器上执行。
  • [24:44] 巧妙地使用块可以让代码运行得更快,这是后续讲座将涉及的主题,但不由本讲者讲授。

共享内存与 CPU 缓存

  • [25:01] 共享内存是 GPU 内存中一小块极快的区域,由块中的所有线程共享。
  • [25:08] 在 3090 上,共享内存只有 128K,大致相当于一个 CPU 缓存。
  • [25:19] 与自动管理的 CPU 缓存不同,在 GPU 上,程序员要手动决定什么内容放入共享内存。

为初学者推迟的优化

  • [25:35] 现在编写的 CUDA 代码中并未使用共享内存缓存,因为课程才刚刚开始。
  • [25:45] 要跑得快,就需要使用该缓存和寄存器文件,后者容纳的内存甚至比共享内存更多。
  • [25:55] 这些优化是以后才需要考虑的事情,入门阶段并不需要。

CUDA 环境配置与 PyTorch 内联编译

开发环境配置代码块与错误处理

  • [26:15] 一个配置代码块会设置一个环境变量,使程序在出错时立即停止执行,这会拖慢速度,但有利于开发,不适合生产环境或追求速度的场景。
  • [26:43] 安装了两个模块:一个是 PyTorch 编译 C++ CUDA 代码所需的构建工具,另一个是 WorldLitza。

WorldLitza 用于在 notebook 中打印 CUDA 的输出

  • [27:02] WorldLitza 仅在加载扩展的那一行使用,没有它,从 CUDA 或 C++ 代码打印的任何内容都不会显示在 notebook 中。
  • [27:12] 在 notebook 中加载 WorldLitza 后,就可以使用 print 语句来调试 CUDA 代码。

LoadInline 与 LoadCuda 封装

  • [27:27] PyTorch 的 LoadInline 位于 torch.utils.cpp extension 中,让你可以在 Python 中使用 CUDA 代码。
  • [27:58] LoadInline 接收一个 CUDA 代码字符串列表、纯 C++ 字符串以及要暴露的 C++ 函数,然后将它们编译成一个可立即使用的 Python 模块。
  • [28:19] 一个名为 LoadCuda 的小型封装简化了这一过程,它在底层只是调用 LoadInline。

共享的 C++ 头文件、宏与向上取整除法

  • [28:32] 一段 C++ 代码字符串被包含在所有 CUDA 文件中,其中包括用于 PyTorch 张量访问、I.O. 使用和异常检查的头文件。
  • [29:08] 定义了三个宏:一个检查张量是否为 CUDA 张量,一个检查其在内存中是否连续,而 check input 会同时检查两者,因为非 CUDA 或非连续的张量无法以展平形式使用。
  • [29:45] 定义了向上取整除法,同时也展示了另一种实现方式,并调用它来计算需要多少个块。

从 Python 编写并启动 CUDA 内核

用 ChatGPT 将 Python 内核转换为 C

  • [30:19] 推荐的做法是将 Python 内核粘贴到 ChatGPT 中,让它尽可能使用相同的名称和格式将代码转换为等效的 C 代码。
  • [30:42] 如果你熟悉 C,自己编写 C 代码也没问题,但复用现有的 Python 代码可以避免从头开始。
  • [30:48] 转换结果基本上相当完美,不过它假定这些值是浮点数,而实际上并非如此,因此不得不修改几个数据类型。
  • [31:09] 对于现在主要使用 Python 编程的人来说,这是编写所需代码中 95% 部分的好方法。

Python 与 C 之间的语法差异

  • [31:18] 与之前的图片不同,这里的内置变量写成了 blockIdx.x、blockDim.x 和 threadIdx.x,因此需要加上 .x。
  • [31:37] 这两段代码看起来几乎一模一样;改动之处在于添加了数据类型、分号、花括号,并去掉了冒号。
  • [32:02] 对于这种计算密集型的工作,C 语言并没有太大区别,所以 C 语言经验少并不是什么大问题。
  • [32:18] unsigned char 就是 C 语言中 uint8 的写法,数据类型的拼写可以用 ChatGPT 或 Google 查一下。

指针、数组与内核限定符

  • [32:37] 星号基本上表示这个变量是一个数组;它实际上是指针,但 C 语言把指针当作数组来处理,所以可以把它看作数组。
  • [33:05] 这里 C 语言只处理一维数组,这就是为什么张量必须始终展平,多维张量实际上无法直接在这些 CUDA 内核中使用。
  • [33:32] void 表示函数不返回任何值,而 __global__ 是 CUDA 特有的扩展,用来说明代码应该如何编译。
  • [33:47] __device__ 会将其编译为只能在 GPU 上调用,__global__ 表示可以从 CPU 或 GPU 调用并在 GPU 上运行,而 __host__ 表示在 CPU 侧运行的普通 C 或 C++ 程序。
  • [34:15] 要从 CPU 侧调用某个东西在 GPU 上运行——这基本上几乎总是内核的情况——你就写 __global__。

用三尖括号启动内核

  • [34:36] 使用 CUDA 时不需要像之前的块内核函数那样使用特殊函数;内核内置的特殊语法就能完成这件事。
  • [35:01] 三尖括号是 C++ 的 CUDA 特殊扩展,表示这是一个要在 GPU 上调用的内核。
  • [35:19] 至少必须在这对三尖括号之间传入两个值:块的数量,按像素数除以线程数向上取整计算;以及线程数,它始终被设为 256。
  • [35:45] 输入张量、输出张量和像素数作为参数传入,每个张量都使用特殊的 .data_ptr() 方法将其转换为 C 指针。

数据类型与 C++ 方法语法

  • [36:13] 你还必须告诉它把指针当作什么数据类型来处理,使用一个 C++ 模板参数来说明将其视为 uint8。
  • [36:31] 在 C++ 中,点表示调用对象的方法,而双冒号基本上类似于在 Python 中调用类的方法,因此创建输出时要写 torch::empty 而不是 torch.empty。

PyTorch C++ 扩展:张量创建与内核错误检查

使用 C++ 列表初始化器创建 2 维张量

  • [37:04] 可以通过传入一个包含高度和宽度(用花括号括起)的 C++ 列表初始化器来创建二维张量,这样就无需在末尾使用点视图。
  • [37:25] 使用点视图的方法同样可行,讲者指出保持一致性可能更好,但当时写的就是这样。

使用 input.options() 和 auto 来指定数据类型与设备

  • [37:36] 传入 input.options() 可使输出使用与输入张量相同的数据类型和相同的 CUDA 设备,讲者认为 Python 中并不存在这种便捷方式。
  • [37:55] 用 auto 代替 torch::tensor 可让编译器推断类型,这是 C++ 的另一项便捷特性。

使用 PyTorch 宏检查内核错误

  • [38:14] 如果内核出错,不一定会被告知,因此必须在调用内核之后写入 PyTorch 提供的宏来检查错误。
  • [38:25] 宏的细节并不重要;应始终在内核调用之后调用它以确保其正常工作。
  • [38:31] 检查之后,可以返回你分配、以指针传入并填充好的张量。

与 CUDA 源码并列的 C++ 源码

  • [38:40] 除了 CUDA 源码之外,还需要一份 C++ 源码。

使用 PyTorch 编译 CUDA 扩展

声明要暴露给 Python 的函数

  • [38:52] 一份要暴露给外部(此处为 Python)的函数详情列表,实际上就充当了头文件。
  • [39:06] 可以从函数定义中复制粘贴整行,并在末尾加上分号。
  • [39:20] 调用 load CUDA 函数时需传入 CUDA 源码、C++ 源码以及要提供给 Python 的函数名列表。
  • [39:31] 只传入了一个函数,即 RGB 转灰度函数,这就足够了。

自动构建与模块加载

  • [39:38] 该过程会在后台自动编译,生成 main.cpp 并将其编译为 main.o,然后将所有内容链接成一个模块。
  • [40:05] 返回的模块存储在名为 module 的变量中,并在编译完成后加载。
  • [40:18] 除了常规自动生成的 Python 内容之外,该模块还包含 RGB 转灰度函数,使 CUDA 函数可从 Python 调用。
  • [40:37] 构建位置包含 main.cpp、编译后的 main.o、可加载库、CUDA 文件以及构建脚本,全部由 PyTorch 处理。

准备输入张量

  • [41:17] 要将张量传递给函数,必须检查它是连续的并且在 CUDA 上。
  • [41:24] 创建一个 imageC 变量,作为连续并放置在 CUDA 设备上的图像,允许函数在全尺寸图像上运行。

Python CUDA 内核性能和工作流程

相对于最小化图像的分辨率和速度提升

  • [41:41] 新图像有 1.7 百万像素,而之前大约有 34,000–35,000 百万像素。
  • [41:57] 运行时间从大约一秒半下降到一毫秒,因为代码被编译并在 GPU 上运行,所以速度大幅提升。

计时包括和不包括的内容

  • [42:16] 将数据移动到 GPU 上不计时,这可能是合理的,因为通常你只做一次,然后运行许多 CUDA 操作。
  • [42:29] 将数据从 GPU 移回 CPU 的时间包含在计时中。
  • [42:36] 如果没有这一步,Python 代码可能在 CUDA 代码仍在运行时继续执行,使得显示的时间大大减少,因为同步尚未完成。
  • [42:48] 包含传输会强制 CUDA 运行完成并将数据放回 CPU;同步也可以通过打印值或手动触发。

验证输出和 Python 优先的工作流程

  • [43:13] 同步后,结果应该完全相同的灰度小狗,确认了第一个真正工作的 Python CUDA 内核代码。
  • [43:40] 用 Python 编写并转换为 CUDA 并不特别常见,但演讲者除了教学之外还使用它,因为 Python 更容易调试和查看发生了什么。
  • [44:08] 避免编译有帮助,因为即使简单的例子也需要大约 45 或 50 秒来编译,而 Python 可以立即运行。
  • [44:19] 一旦工作,转换为 C 可以 largely 由 chat GPT 完成,这使得即使你对 CUDA 内核变得有些熟悉,这也是编写它们的好方法。
  • [44:33] 许多人避免 CUDA,因为过程如此痛苦,这种方法通过允许更快的调试和开发使其不那么痛苦。

实现矩阵乘法

定义及其在深度学习中的作用

  • [44:54] 矩阵乘法被描述为最基本的线性代数运算,并且对深度学习至关重要。
  • [45:58] 该操作概念上简单,但在深度学习中多次执行,每个神经网络都将其作为最基本的操作。

按行与列的点积过程

  • [45:11] 该操作接收输入矩阵 M 和第二个输入矩阵 N,遍历 M 的每一行和 N 的每一列。
  • [45:36] 在每个点上,取 M 的该行与 N 的该列的点积,这就是矩阵乘法。

库与自定义实现

  • [46:06] 矩阵乘法无需从头实现,因为库已经提供了它。
  • [46:16] 工作中常常涉及将某种矩阵乘法作为片段融合进来。

用纯 Python 实现矩阵乘法

MNIST 设置与线性模型维度

  • [46:56] fast AI 课程的第二部分第 11 课花了一两个小时讲解使用 MNIST 数据集的矩阵乘法,这里也使用了该数据集。
  • [47:04] MNIST 手写数字为 28 乘 28,展平后每张图像有 784 个值。
  • [47:23] 不带激活函数的单个神经网络层,就是将展平后的图像与一个具有 784 行、任意列数的权重矩阵进行矩阵乘法。
  • [47:42] 直接得到输出就形成了一个具有 10 层的线性模型,每个数字一层;这里不进行任何学习,只是一个示例。

点积的维度规则

  • [48:10] 由于 Python 速度慢,矩阵一被缩减为五行,因此一个五乘 784 的矩阵与一个 784 乘 10 的矩阵相乘。
  • [48:32] 内部维度必须匹配:A 的列数必须等于 B 的行数,输出为 A 的行数乘 B 的列数,这里是五乘 10。

纯 Python 矩阵乘法实现

  • [48:53] 创建一个行数乘列数的零输出张量,然后遍历 A 的每一行和 B 的每一列来计算点积。
  • [49:11] 点积遍历最内层的全部 784 个项,将 M1 和 M2 中对应的元素相乘并求和到输出张量中。
  • [49:43] 讲者在 Python 中逐行构建代码,检查每一步,然后合并单元格并添加函数头以形成 matmul。
  • [50:08] 对 39,200 次最内层操作调用 matmul 大约花了一秒,这被描述为相当慢。

纯 PyTorch 中 CUDA 风格的 2D 内核执行

将点积变为逐单元内核

  • [50:54] 输出张量的每个单元格分配给一个执行点积的 CUDA 线程,这便成为矩阵乘法块内核。
  • [51:26] 内核主体与上面复制的代码完全相同,因此需要一种单独的机制来运行它。

2维和3维块与线程索引

  • [51:53] 在 CUDA 中,块和线程不必是1维向量;它们可以是2维甚至3维张量。
  • [52:38] 每个块都有一个元组索引,如 (0,0)、(1,3) 或 (3,4),而不是单个整数块索引。
  • [53:28] 线程索引也有两个元素,给出块内的行和列,因此位置由块坐标和线程坐标共同定义。
  • [54:32] 使用2维网格只是一种便利,CUDA 最多允许三个维度。

内核运行器中的四个嵌套循环

  • [54:41] 内核运行器将两个嵌套循环替换为四个:y 上的块、x 上的块、y 上的线程和 x 上的线程。
  • [55:27] 这种笛卡尔积意味着对每个块、每个线程,简单的命名空间对象提供 y 和 x 坐标。
  • [56:13] 内核以块和线程对象调用,最终覆盖所有可能的块以及每个块内的所有线程。
  • [56:27] 运行器还必须被告知每个块的高度和宽度,作为带有 x 和 y 的简单命名空间传递。

纯 PyTorch 执行与边界保护

  • [56:49] 一切都是纯 PyTorch,除了少量用于索引和张量创建的 PyTorch 外,不调用 CUDA 或其他库,因此可以在调试器中单步执行。
  • [57:16] 保护检查当前行不高于、当前列不宽于张量。
  • [57:33] 列的计算方式与之前相同,这就是 CUDA 使用 blockIdx.x 作为三维结构一部分的原因。
  • [57:55] 行由 y 轴上已遍历的块和线程数量确定;如果位置越界则停止,否则将点积结果写入输出张量。

2维矩阵乘法的块配置

推导2维线程和块维度

  • [58:27] 内核使用两个输入矩阵的高度和宽度,内部维度 k 和 k2 必须匹配。
  • [58:41] 每块线程数变为一对 x 和 y 值,选择使它们相乘为256,从而很好地展开二维输入。
  • [59:05] 每块线程数不能超过1024,因此256是安全的;这里16乘以16得到每块线程数。

块限制与共享内存原理

  • [59:30] 方块的最大数量为:维度 0 为 2 到 31,维度 1 和 2 为 2 到 16,可能还要减去 1。
  • [59:43] 每个对称多处理器在同一设备上运行所有块,它们共享对共享内存的访问,这就是每个块使用少量线程的原因。

启动 2D 内核并验证结果

  • [59:53] x 和 y 的块数通过向上取整除法计算,使用了从前面示例复制的代码。
  • [1:00:11] 调用 2D 块内核运行器时,传入内核、块数、每块线程数、展平的输入矩阵、展平的输出矩阵以及所需维度,并返回结果。
  • [1:00:35] 使用 2D 块调用 mapMole 产生的结果与原始手动循环接近,因为它运行相同的代码。

CUDA 矩阵乘法与 CPU 基准比较

CUDA 版本使用完整矩阵

  • [1:00:51] CUDA 版本预计会快得多,因此不再需要精简的矩阵,可以使用整个矩阵。

基于广播的 CPU 参考实现

  • [1:01:08] 需要一种快速的基于 CPU 的方法来检查正确性,因为之前的方法对于 39,000 个元素花费了大约一秒。
  • [1:01:17] 快速的 CPU 方法使用广播,正如快速 AI 课程中所教,用单个纯 Python 循环替换了三个嵌套循环。
  • [1:01:34] 广播方法对于裁剪后的张量给出相同的答案,但运行时间仅四毫秒。

在完整输入矩阵上运行

  • [1:01:47] 因为它足够快,广播方法现在可以在整个输入矩阵上运行,大约需要 1.3 秒。
  • [1:02:06] 广播优化版本在实际上是三个循环的中间执行了 392 百万次加法,但使用了广播。
  • [1:02:19] 这种 CPU 方法的主要目的是将结果存储为参考,以便比较。

将 Python matmul 函数转换为 CUDA

用 ChatGPT 将 Python 函数重写为 C

  • [1:02:35] 演讲者拿过 Python 函数,让 ChatGPT 用 C 重写,第一次尝试就得到了可用的代码。
  • [1:02:48] C 版本使用浮点指针而不是无符号字符指针,但除此之外与 Python 代码非常相似,并做了与之前相同的更改。

内核启动设置与断言

  • [1:03:02] 代码使用 .y 和 .x 访问器以及 DunderGlobal 注解,指示当从 CPU 调用时内核应在 GPU 上运行。
  • [1:03:21] matmul 包装器接收两个张量,检查它们是否连续且位于 CUDA 设备上,并提取高度、宽度和内部维度,验证内部维度匹配。
  • [1:03:41] PyTorch CUDA 代码中的断言使用 torch check 以及条件和错误消息,演讲者建议将它们散布在整个 CUDA 代码中。

使用 dim3 的线程和块配置

  • [1:04:08] 代码没有使用简单的线程数 256,而是创建了一个名为 tpb 的 dim3,设置为 16 乘 16,未指定的第三个元素被视为一。
  • [1:04:37] 块的数量在 X 维度上是 W 除以 X,在 Y 维度上是 H 除以 Y,均使用向上取整除法。
  • [1:04:55] 内核像普通函数一样调用,但使用三尖括号指定块和线程,它们现在是 dim3 结构而不是整数。
  • [1:05:18] 在之前的灰度示例中,传递 256 实际上产生了一个 dim3 结构,其点 X、点 Y 和点 Z 值自动设置为一。

在完整 MNIST 上启动、编译和验证

  • [1:05:49] 张量被转换为特定数据类型的指针,并连同内核需要的任何其他信息一起传递给内核。
  • [1:06:10] load CUDA 将代码编译成模块,检查连续性和 CUDA 设备放置,并调用模块的 mapmul 方法,然后将结果移到 CPU 并确认它们都接近。
  • [1:06:36] 计算现在在整个 MNIST 数据集上运行,而不仅仅是前五行。

CUDA 矩阵乘法性能

CPU 与 CUDA 与 PyTorch 计时对比

  • [1:06:41] 使用优化的 CPU 方法运行整个 MNIST 数据集耗时 1.3 秒,而 CUDA 耗时 6 毫秒。
  • [1:07:05] PyTorch 通过 at 进行矩阵乘法得到相同答案,耗时 2 毫秒,快三倍,在许多情况下会快远不止三倍。

共享内存作为 PyTorch 的速度技巧

  • [1:07:40] PyTorch 特别快是因为利用了共享内存,这是块内线程共享的小内存空间,比全局内存快得多。
  • [1:08:03] 在矩阵乘法中,每个块在同一个 SM 上运行,并反复重用相同的 16 乘 16 块、相同的 16 行和列,访问相同的共享内存。
  • [1:08:22] 这样可以缓存大量所需信息并重复使用,而不必反复回到较慢的内存,这就是达到该阶段后可以优化的一个例子。

2D 块是可选的

  • [1:08:43] 2D 块的想法完全是可选的;一切都可以用 1D 块完成。

1D 与 2D 块用于 RGB 转灰度

1D 与 2D 实现得到等价结果

  • [1:08:54] 末尾的示例使用 2D 块将 RGB 转换为灰度,其结果与之前的 1D 块版本完全相同。

代码复杂度比较

  • [1:09:26] 尽管要操作像素,1D 线程与块版本仍比 2D 版本短不少。
  • [1:09:45] 尽管人们预期 2D 方法在处理像素时会更简洁,但在这一特定情况下并非如此;分别处理列和行增加了复杂度。
  • [1:09:51] 2D 版本的守卫条件稍复杂一些,因为必须确定当前索引,而 1D 内核只有两行代码。
  • [1:10:07] 与 1D 方法相比,使用每块线程数设置调用内核也稍复杂一些。

何时选择 2D 或 3D 结构

  • [1:10:17] 两段代码做的事情完全相同,因此如果你不想用 2D 或 3D 的块/线程结构,就不必使用。
  • [1:10:32] 2D 选项只是为了方便你而存在;你不应觉得自己必须使用它。

面向数据科学家用 Python 编写 CUDA

数据科学家从 Python 到 CUDA 的可及性

  • [1:10:48] 即使对 Python 程序员和数据科学家来说,编写 CUDA 也并未远离他们的舒适区。
  • [1:11:06] CUDA 代码几乎可以自动转换,即使换一种语言,看起来也相当熟悉。
  • [1:11:16] 一切都可以在 notebook 中完成,边测试边进行,并从内核中打印内容。
  • [1:11:35] 讲者鼓励大家放手去做,因为这可能没有想象中那么超出自己的能力范围。

手写 CUDA 的需求日益增长

  • [1:11:42] 能够编写 CUDA 代码对于 flash attention、量化、GPTQ、AWQ 和 bits and bytes 等无法用 PyTorch 编写的内容越来越重要。
  • [1:11:58] 随着模型变得越来越复杂,PyTorch 对我们想要做什么的假设变得越来越不准确。
  • [1:12:12] 现在越来越多的工作必须由开发者自己在 CUDA 中完成。

使用 Conda 搭建本地 GPU 开发环境

将 Conda 视为类似 Docker 的环境管理器

  • [1:13:15] 环境搭建使用 Conda,它更适合被理解为 Docker 的替代品,而不是 PIP 或 poetry 的替代品。
  • [1:13:34] Conda 让你可以并行运行多个版本的 Python、CUDA 和 C++ 编译系统,并在它们之间切换。
  • [1:13:55] 使用 Conda 可以避免令人困惑的 .run 文件和 Ubuntu 软件包,因此一切都可以仅通过 Conda 完成。

安装 Conda 并使 CUDA 与 PyTorch 匹配

  • [1:14:01] 一个小型安装脚本会自动检测所需的 MiniConda 和你的 shell,下载并安装它,之后你重启终端即可。
  • [1:14:23] 第二步是检查 PyTorch 需要哪个 CUDA 版本;当时,Linux 上的 Conda 构建使用 CUDA 12.1。
  • [1:14:46] 第三步运行一条替换了当前 CUDA 版本的 shell 命令,从 NVIDIA 安装完整的 NVIDIA 性能分析、调试和构建工具套件,并带有正确的版本。
  • [1:15:18] 最后,使用所示的命令安装 PyTorch,去掉 -nightly 标志,以便最新稳定版使用刚刚安装的 NVIDIA CUDA 设置。

速度、平台支持和存储效率

  • [1:15:29] Conda 过去由于较旧的求解器而速度较慢,但最近几个月默认启用的现代求解器应该能让它运行得非常快。
  • [1:15:47] 该设置可在 Windows 上的 WSL 以及 Ubuntu、Fedora 和 Debian 上运行,不过 CUDA 在 Mac 上无法工作。
  • [1:16:23] 在多个环境之间共享的库会被硬链接,因此重复安装不会占用额外的硬盘空间。

CUDA 学习的后续步骤

建议的项目和代码研读

  • [1:16:56] 鼓励观众继续观看其他 CUDA 模式讲座,演讲者会提供链接。
  • [1:17:05] 演讲者建议尝试个人项目,例如实现 4 位量化或 Flash Attention。
  • [1:17:24] 大型项目可以拆分成更小的部分,一步一步地构建起来。
  • [1:17:28] 阅读他人的代码,例如 Flash Attention、bits and bytes 和 GPTQ 的实现,投入的时间越多越有益。

阅读带时间戳的可用字幕,或转录播客、讲座和本地音频/视频。免费YouTube转录提取器。

需要提取其他公开视频的 SRT、TXT 或 Markdown 字幕?前往 YouTube 字幕提取工具。

前 3 段双语对照预览 · 免消耗额度

以下展示前 3 段已保存中文译文与英文原版字幕的逐段对照(零额度消耗):

[0:01]

大家好,我是来自 Answer.AI 的 Jeremy Howard,欢迎来到《CUDA 入门》。CUDA 当然是我们用来为 NVIDIA GPU 编程的工具,如果我们想让它们运行得超快,并且想要最大的灵活性。它一直有着非常难以上手的名声。事实是,它其实并没有那么糟。你只需要知道一些技巧。而在这期视频中,我将向你展示其中一些技巧。那么让我们切换到屏幕来看一看。今天我将全部在 notebook 中完成所有工作。这可能会让你感到惊讶。你可能认为要用 CUDA 工作,我们必须得跟编译器和终端之类的东西打交道。而事实是,多亏了 PyTorch 提供的一些魔法,我们其实真的不需要。你可以跟着完成所有这些步骤,我强烈建议你在自己的电脑上这样做。你可以

Hi there, I'm Jeremy Howard from Answer.AI, and this is Getting Started with CUDA. CUDA is of course what we use to program NVIDIA GPUs, if we want them to go super fast, and we want maximum flexibility. And it has a reputation of being very hard to get started with. The truth is, it's actually not so bad. You just have to know some tricks. And. so in this video I'm going to show. you some of those tricks. So let's switch to the screen and take a look. So I'm going to be doing all of the work today in notebooks. This might surprise you. You might be thinking that to do. work with CUDA we have to do stuff with compilers and terminals and things like that. And the truth。 is actually it turns out we really don't, thanks to some magic that is provided by PyTorch. You can follow along in all of these steps and I strongly suggest you do so in your own computer. You can

[1:03]

前往 GitHub 上的 CUDA mode 组织,在那里找到 Lecture 2 仓库,你会看到一个 Lecture 3 文件夹。这是 CUDA mode 系列的第 3 讲。不过你不需要看过之前的任何一讲就能跟上。在 readme 中你会看到一个 Lecture 3 部分,底部有一个点击前往 Colab 版本的链接。没错,你可以在 Colab 中免费运行所有这些内容。你甚至不需要有可用的 GPU 就能运行整个内容。

go to the CUDA mode organization in GitHub, find the Lecture 2 repo there, and you'll see there is a Lecture 3 folder. This is Lecture 3 of the CUDA mode series. You don't need to have seen any of. the previous ones, however, to follow along. In the readme there you'll see there's a Lecture 3. section and at the bottom there is a click to go to the Colab version. Yep, you can run all. of this in Colab for free. You don't even have to have a GPU available to run the whole thing.

[1:39]

我们将跟随《Programming Massively Parallel Processes》这本书中的一些示例。Programming Massively Parallel Processes 是一本非常值得一读的好书,一旦你完成了今天的课程,你应该能够很好地开始阅读这本书。它会更详细地讲解我们将要相当快速地涉及的一些内容。如果你没有这本书也没关系,但如果你想深入下去,我强烈建议你买一本。事实上,你会在仓库中看到,本系列中的 Lecture 2 实际上是对那本书第 1 到 3 章的深入探讨。所以,说来有点绕,你可能会想在这讲之后再看 Lecture 2、Lecture 3,以了解更多我们正在讨论的内容的细节。好了,让我们深入 notebook 吧。那么我们今天要做的是,我们要做一大堆事情

We're going to be following along with some of the examples from this book Programming Massively Parallel Processes. Programming Massively Parallel Processes is a really great book to read, and once you've completed today's lesson, you should be able to make a great start on this book. It goes into a lot more details about some of the things that we're going to cover on fairly quickly. It's okay。 if you don't have the book, but if you want to go deeper I strongly suggest you get it. In fact, you'll see in the repo that Lecture 2 in this series actually was a deep dive into chapters 1 to 3 of that book. So. actually you might want to do Lecture 2, confusingly enough, after this one, Lecture 3, to get more details about some of what we're talking about. Okay, so let's dive into the. notebook. So what we're going to be doing today, is we're going to be doing a whole lot of stuff

[0:01] 大家好,我是来自 Answer.AI 的 Jeremy Howard,欢迎来到《CUDA 入门》。CUDA 当然是我们用来为 NVIDIA GPU 编程的工具,如果我们想让它们运行得超快,并且想要最大的灵活性。它一直有着非常难以上手的名声。事实是,它其实并没有那么糟。你只需要知道一些技巧。而在这期视频中,我将向你展示其中一些技巧。那么让我们切换到屏幕来看一看。今天我将全部在 notebook 中完成所有工作。这可能会让你感到惊讶。你可能认为要用 CUDA 工作,我们必须得跟编译器和终端之类的东西打交道。而事实是,多亏了 PyTorch 提供的一些魔法,我们其实真的不需要。你可以跟着完成所有这些步骤,我强烈建议你在自己的电脑上这样做。你可以

[1:03] 前往 GitHub 上的 CUDA mode 组织,在那里找到 Lecture 2 仓库,你会看到一个 Lecture 3 文件夹。这是 CUDA mode 系列的第 3 讲。不过你不需要看过之前的任何一讲就能跟上。在 readme 中你会看到一个 Lecture 3 部分,底部有一个点击前往 Colab 版本的链接。没错,你可以在 Colab 中免费运行所有这些内容。你甚至不需要有可用的 GPU 就能运行整个内容。

[1:39] 我们将跟随《Programming Massively Parallel Processes》这本书中的一些示例。Programming Massively Parallel Processes 是一本非常值得一读的好书,一旦你完成了今天的课程,你应该能够很好地开始阅读这本书。它会更详细地讲解我们将要相当快速地涉及的一些内容。如果你没有这本书也没关系,但如果你想深入下去,我强烈建议你买一本。事实上,你会在仓库中看到,本系列中的 Lecture 2 实际上是对那本书第 1 到 3 章的深入探讨。所以,说来有点绕,你可能会想在这讲之后再看 Lecture 2、Lecture 3,以了解更多我们正在讨论的内容的细节。好了,让我们深入 notebook 吧。那么我们今天要做的是,我们要做一大堆事情

[2:41],先用旧版 PyTorch 来做,确保我们把所有思路都理清楚,然后再尝试把每一部分转换成 CUDA。那么,为了做到这一点,我们先导入一堆东西。其实我们就在 Colab 里做所有这些吧。现在我们就在 Colab 里,你应该确保在 Colab 中把运行时设置为 T4 GPU。这个你可以免费大量使用,而且它完全足以运行我们今天要做的所有事情。等你把它跑起来之后,我们就可以导入需要的库,然后开始第一个练习。第一个练习其实来自书的第 2 章和第 2 章,它教的是如何解决这个问题,也就是把 RGB 彩色图片转换成灰度图片。结果发现,推荐的公式是取红色像素的 0.21、绿色像素的 0.72、

[3:44] 0.07 的蓝色像素,然后把它们加在一起,这样就得到了亮度值,也就是我们在这里看到的结果。这是一种常见的方式,是从 RGB 转到灰度的标准做法。所以我们要做这个,我们要写一个 CUDA 内核来完成它。那么我们首先需要的是一个图片,而每当你需要图片时,我建议找一张小狗的图片。这里我们有一个小狗图片的 URL。我们直接把它下载下来,然后用 torchvision.io 来加载它。这已经是 Colab 的一部分了。如果你有兴趣在自己的机器或云服务器上运行这些东西,我会在讲座最后展示如何设置。那我们来读取图像,如果看一下它的形状,它显示是 3 乘 1066 乘 1600。所以我假设你了解基础

[4:44] 的 PyTorch 基础。如果你不了解 PyTorch 基础,我可能有点偏心,但我强烈推荐我的课程,它正好涵盖这些内容。你可以访问 course.fast.ai,你还能顺便看到一些非常可爱的小兔子,而且除了这些可爱的小兔子之外,它基本上会带你掌握成为现代深度学习高效实践者所需的一切。

[5:14] 所以如果你想直接进入那些细节,就完成第一部分,但即使你只做前两到三课,那也会给你足够多的知识来理解这类代码和这类输出。所以我已经完成了所有这些。你会看到这里我们有一个秩为 3 的张量。有三个通道,所以它们就像立方体的面。每个面上有 1066 行,那就是高度,然后每行有 16 列,那就是宽度。所以如果我们看前几个通道、前三行和前四列,你可以看到这些是无符号 8 位整数。所以它们是字节,就在这里。这就是图像的样子。希望你已经知道这些了。那么让我们看看我们的图像。为此,我只需创建一个简单的小函数 show image,它会创建一个 matplotlib 图。移除坐标轴。如果它是彩色的,也就是这个

[6:23] 它会将坐标轴的顺序从通道×高度×宽度(这是 PyTorch 使用的)改为高度×宽度×通道(这是 matplotlib 所期望的)。所以我们将坐标轴的顺序改为 1 2 0,然后我们就可以显示边缘。如有必要,将其放到 CPU 上。现在我们要在 Python 中处理这张图像,一开始将只使用纯 Python,然后再切换到 CUDA。它会非常慢,所以我们会调整它的大小,使最短的边长、最小的维度为 150。所以在这种情况下就是高度。所以我们最终得到一个 150×225 的形状,这是一个矩形,即 3 3 750 个像素,每个像素都有 R、G 和 B 值,这就是我们的小狗。所以你看,把这张图做成小狗可不是个好主意。好吧

[7:24] 那么我们如何将其转换为灰度呢?书里已经告诉我们要使用的公式。遍历每个像素并对其执行该操作。好的,这就是我们要做的循环,遍历每个像素并对其执行该操作,然后将其放入输出中。这就是基本思路。那么细节是什么呢?这里我们有通道×行×列。那么我们如何遍历每个像素呢?

[7:55] 首先我们需要知道有多少个像素。所以我们可以说通道数乘以高度乘以宽度就是形状。现在我们已经定义了这三个变量。所以像素的数量就是高度乘以宽度。那么,要遍历所有这些像素,一个简单的方法是把它们全部展平成一个向量。那么,当把它们全部展平成一个向量时会发生什么呢?正如我们所见,它们目前以这种格式存储。我们有一个面,然后是另一个面。然后还有一个——我们这里没有打印出来——但还有第三个面。在每个面内部,有一行。我们只展示了前几行。然后是下一行,再下一行。然后在每一行中,你有列、列、列。那么假设我们有一个小图像,实际上我们可以这样做。我们可以说这是我们的红色。所以我们有 0、1、2 的像素,

[9:05] 3、4、5。那么假设这是一个高度为 2、宽度为 3、3 通道的图像。那么就会有 6、7、8、9、10、11、RGB、12、13、14、15、16。那么假设这些就是像素。所以当它们被展平时,就会变成像这样的一个单一向量。6、7、8、12、13、14。所以,实际上当我们谈论图像时,我们最初把它看作一堆像素。我们可以把它看作具有

[10:09] 3 个通道。但在实际中,在我们计算机里,内存都是线性排列的。所有东西都只是内存中的一个地址。它就是一整块。你可以把它想象成你计算机的内存就是一个巨大的向量。所以当我们说,当我们说展平的时候,它实际做的是把我们这个通道乘高度乘宽度变成一个像这样的大向量。好,现在我们已经这么做了,我们可以说,好吧,我们要把它放进的地方,结果,我们会从一个长度为 n 的空向量开始。我们会遍历从 0 到 n 减 1 的所有 n 个值。然后我们会把输出值放进去,大约 0.29 次。

[11:17] 输入值 x i。所以,这将在红色部分这里。然后 0.59 乘以 x i 加 n。所以,这里的 n 是这个距离。它是像素的数量,1、2、3、4、5、6。所以,这就是为什么要到绿色我们必须跳到 i 加 n。然后要到蓝色我们必须跳到 i 加 2n。所以这就是它的工作原理。我们已经把所有东西展平了,我们直接索引到这个展平的东西中。所以在最后我们将完成我们的灰度处理。那么我们可以把它重塑为高度乘以宽度。然后,就是这样。这就是我们的灰度小狗。然后你

[12:26] 可以看到,展平后的图像只是一个单独的向量,所有那些通道值都按我们描述的方式展平了。好,现在这慢得离谱。仅仅处理 34,000 个像素就要花将近两秒。所以为了加速,我们要用 CUDA。为什么 CUDA 能加速?CUDA 能加速的原因在于它的组织方式与普通 CPU 的组织方式非常不同。我们其实可以通过查看 RTX 3090 显卡的一些信息看到这一点。RTX 3090 显卡是一款很棒的 GPU。你可以买到二手的,性价比相当不错。所以是个非常好的选择,尤其适合

[13:31] 爱好者。3090 里面有什么?它有 82 个 SM。什么是 SM?SM 是流式多处理器。你可以把它几乎看作你电脑里一个独立的 CPU。所以有 82 个这样的东西。这已经比你电脑里的 CPU 多很多了。但除此之外,每一个还有 128 个 CUDA 核心。这些 CUDA 核心都能同时运行。这些多处理器也都能同时运行。所以这给了我们 128 乘以 82。总共 10,500 个 CUDA 核心可以同时工作。这比我们熟悉的任何 CPU 能做的都多得多。

[14:26] 而且 3090 甚至还不是最高端的。它确实是一款非常好的 GPU,但还有一些拥有更多 CUDA 核心的。那么我们如何把它们全都用起来呢?我们需要能够以这样一种方式组织代码:我们可以说这里有一段代码,你可以在许多不同的数据、许多不同的内存上同时运行它,这样你就能同时做 10,000 件事。CUDA 以一种非常简单且相当优雅的方式做到这一点,它基本上就是说,好,把那种内层循环拿出来。这就是我们的内层循环。就是那些你可以同时运行 10,000 个的部分。它们完全不会互相影响。你看,这些完全不会互相影响。它们所做的只是把某个东西写进某个输出内存。所以它甚至不返回东西。你不能从这些所谓的 CUDA 内核中返回东西。你所能做的只是以某种方式修改内存,而你不知道什么

[15:30]它们将要运行的顺序。它们可以全部同时运行。有些可能比另一个稍早一点运行,等等。所以 CUDA 的做法是,好,写一个函数。在你的函数里写一行代码,我会根据需要调用它几十次、几百次、几千次、几百万次,来完成所有需要的工作。我会尽可能为你并行执行。在 3090 上运行时,最多 10,000 次,最多 10,000 个任务同时进行。我会尽可能快地完成。所以你基本上只需要写下你想要被多次调用的那行代码。然后第二件事是说明要调用这段代码多少次。接下来会发生的是,这段被称为 kernel 的代码会为你被调用。它会传入你要求传入的任何参数,在这个例子中就是输入数组张量、输出张量和大小

[16:35]每个通道有多少像素。它会告诉你,好,这是我第 i 次调用它。现在我们可以在 Python 中非常简单地用一个 for 循环来模拟。这不会并行执行,所以不会加速,但结果的语义将与 CUDA 完全相同。所以这里有一个我们称为 run kernel 的函数。我们要传入一个函数。我们要说明运行该函数多少次以及用什么参数调用该函数。因此每次它都会调用该函数,传入索引、第几次调用以及我们请求的参数。好,现在我们可以创建一些东西来调用它。所以让我们像之前一样,获取通道数、高度和宽度、像素数,将其展平,创建结果张量。我们要把结果放进去。所以这次,我们不是直接调用循环,而是调用 run kernel。我们将传入……的名称。

[17:42]要作为 f 调用的函数。我们将传入次数,即循环的像素数。我们还将传入 kernel 内部所需的参数。所以我们需要 out,需要 x,需要 n。你可以看到这里我们完全没有使用任何外部库。我们只有纯 Python 和一点点 PyTorch,刚好够创建张量、对张量进行索引。这就是全部所用到的。从概念上讲,它做的事情几乎和 CUDA kernel 一样。我们马上就会谈到这个“几乎”。但从概念上讲,你可以看到,你现在有可能写出一些东西,如果你知道这是在完全独立地运行一堆东西,从概念上讲,

[18:48] 你现在可以真正轻松地实现并行化了。而这就是 CUDA 所做的事情。不过,事情并没有那么简单。它并不像 Python 中的 range n 那样简单地创建一个数字列表,然后依次把每个数字传进你的内核。相反,它实际上会把数字范围拆分成所谓的块。所以在这个例子中,也许我们有 1,000 个像素想要处理。它会将它们按每次 256 个分组。所以在 Python 中,它看起来是这样的。在实践中,CUDA 内核运行器并不是一个循环 n 次的单一 for 循环。相反,

[19:49] 它是一对嵌套的 for 循环。所以你不只是传入一个数字并说这就是像素数量,而是传入两个数字:块的数量和线程的数量。我们稍后会详细讨论这一点。但这些只是数字。你可以在这里放任何你喜欢的数字。如果你选择两个数字,它们的乘积等于我们想要的结果,也就是我们想要调用它的次数 n,那么这就能做完全相同的事情,因为我们现在会传入外层循环当前进行到哪个索引、内层循环当前进行到哪个索引、内层循环中要遍历多少个元素,因此在内核内部,我们可以通过将块索引乘以块维度来算出当前进行到哪个索引。也就是说,用 i 乘以线程数,再加上内层循环索引 j。所以这就是

[20:51] 我们通过 i、j 线程传入的内容。但在内核内部,我们称之为块索引、线程索引和块维度。所以如果你查看 CUDA 的书,你会看到这里正是他们所做的事情。他们说索引等于块索引乘以块维度再加上线程索引。这里有一个 .x 的东西,我们暂时可以忽略。我们稍后会看它。但在实践中,这实际上就是 CUDA 的工作方式。所以它有所有这些块,里面是线程,你可以把它们就当作数字来看。你可以看到这些块,它们只是有编号,零、一、点、点、点、点,等等。不过,这确实意味着有一点棘手的地方,那就是,我首先要说的是,我们如何选择这些数字,即块的数量和线程的数量?目前在实践中,我们总是会说线程数是 256。作为一个默认值,这是一个完全没问题的数字。无论如何,你也不会错得太离谱,

[21:58] 总是选择 256,几乎总是如此。所以现在不用太担心这个。优化那个。数字。所以如果我们说,好吧,我们想要 256 个线程,记住那是内层循环,或者如果我们看看这里的 kernel runner 内部,那就是我们的内层循环。所以我们会调用每个,这个会被调用 256 次。那么你需要调用它多少次?嗯,你需要调用它 n 次,即像素数除以 256 次。现在这可能不是整数,所以你需要向上取整。这就是我们计算块数的方法。我们需要确保我们的 kernel 被调用足够多次。但现在我们有一个问题,就是我们原本希望调用的次数,之前等于像素数,可能不是 256 的倍数。所以我们可能最终会走得太

[23:02] 远。这就是为什么我们现在在 kernel 中还需要这个 if 语句。所以这是为了确保我们当前的索引不会超过我们拥有的像素数。这出现在基本上你会看到的每个 CUDA kernel 中,它被称为 guard,或 guard block。所以,这是我们的 guard,确保我们不会越界。所以。这和我们之前有的代码是同一行。现在我们只是添加了这个东西来计算索引,并且我们添加了 guard。

[23:34] 这就像是任何 CUDA kernel 中非常标准的前几行。所以我们现在可以运行这些,它们会做和之前完全相同的事情。那么显而易见的问题是,为什么?为什么 CUDA kernel 以这种奇怪的块和线程方式工作?为什么我们不直接告诉它运行次数?为什么我们必须按块和线程来做?原因是由于我们这里的一些细节,即 CUDA 为我们设置好了,使得同一个块中的所有内容,或者更完整地说线程块,即同一个块,它们都会被分配一些共享内存。它们也都会有机会进行同步,这基本上是说,好吧,这个块中的所有内容都必须到达这个点,然后你

[24:35] 才能继续。一个块中的所有线程将在同一个流式多处理器上执行。所以我们会在后面的课程中看到,但不会由我来讲授,通过巧妙地使用块,你可以让你的代码运行得更快。而共享内存尤其重要。所以共享内存是 GPU 中的一小块内存,一个块中的所有线程共享它,而且它很快。

[25:08] 它非常、非常、非常快。当我们说容量不大时,大概是在 3090 上,也就是 128K。所以非常小。这基本上和 CPU 中的缓存一样。不过区别在于,在 CPU 上,你不会手动决定缓存里放什么。但在 GPU 上,你要自己决定。完全由你掌控。所以目前,当我们创建 CUDA 代码时,这个缓存不会被用到,因为我们才刚开始。因此我们暂时不担心那个优化。但要想跑得快,你就得用那个缓存。另外,你还要用寄存器文件。很多人没有意识到的是,实际上寄存器内存相当多,甚至比共享内存还多。总之,这些都是以后才需要操心的事,入门阶段用不到。那么,我们该如何使用 CUDA 呢?基本上有一个标准的

[26:15] 设置代码块,我会加上,我们这就加上。这个设置代码块里要做的是设置一个环境变量。你在生产环境或追求速度时不会用这个。但它基本上是说,如果遇到错误,就立刻停下。所以先看看情况如何。这样一来,你就能准确告诉我们错误何时发生、在哪里发生。所以这会拖慢速度,但对开发很有好处。我们还要安装两个模块。一个是构建工具,PyTorch 编译你的 C++ CUDA 代码时需要它。第二个是个非常方便的小东西,叫做 WorldLitza。你唯一会看到它被使用的地方就是这一行,我们在这里加载这个名为 WorldLitza 的扩展。没有它,你从 CUDA 代码里打印的任何内容,实际上从 C++ 代码里打印的任何内容,都不会出现在 notebook 中。所以你在做 CUDA 相关工作的

[27:19] notebook 里时,总要这样做,这样你就能用 print 语句来调试。好。那么如果你有一些 CUDA 代码,如何从 Python 中使用它呢?答案是 PyTorch 自带一个非常方便的东西,叫做 LoadInline,它在 torch.utils.cpp extension 里面。LoadInline 是个很棒的函数,你只需传入一个列表,包含你想编译的任何 CUDA 代码字符串、你想编译的任何纯 C++ 字符串、你想让 PyTorch 可用的 C++ 中的任何函数。它就会去编译全部内容,把它变成一个 Python 模块,并立即让它可用,这相当了不起。我刚刚创建了一个小小的包装器,

[28:26],名为 LoadCuda,只是为了稍微简化一下。在幕后,它只是调用 LoadInline。我做的另一件事是创建了一个包含一些 C++ 代码的字符串。我认为这些都是 C 代码,但它是作为 C++ 代码编译的。我们称之为 C++ 代码。我们希望将 C++ 代码包含在我们所有的 CUDA 文件中。我们需要包含这个头文件,以确保我们可以访问 PyTorch 张量相关的东西。我们希望能够使用 I.O.,并且希望能够检查异常。然后我还定义了三个宏。第一个宏只是检查张量是否在 CUDA 上。第二个检查它在内存中是否连续,因为有时 PyTorch 实际上可以将东西拆分到不同的内存块上。然后如果我们尝试在这个

[29:29] 展平的形式中访问它,它就不会工作。然后我们实际使用它的方式,检查输入,我们只会检查这两件事。所以如果某个东西不在 CUDA 上并且不连续,我们就无法使用它。所以我们总是有这个。然后我们在这里做的第三件事是定义向上取整除法。向上取整除法就是这个。虽然你可以用不同的方式实现它,像这样。所以这会做向上取整除法。这就是我们将要,这就是我们将要调用的,以弄清楚我们需要多少个块。所以这只是,你不必太担心它的细节。这只是我们将要使用的标准设置。好的,现在我们需要编写我们的 CUDA 内核。那么,你如何编写 CUDA 内核?

[30:19] 好吧,我所做的,我建议你也这样做,就是把你的 Python 内核粘贴到 chat GPT 中,并说将其转换为等效的 C 代码,使用相同的名称、格式等。在可能的情况下,粘贴进去,chat GPT 会为你完成。除非你对 C 非常熟悉,那就自己写也行。但这样,既然你已经有了 Python,为什么不直接这样做呢?我发现它基本上相当完美。尽管它确实假设这些是浮点数,它们实际上不是浮点数。我们不得不更改几个数据类型,但基本上我几乎可以按原样使用它。所以特别是,你知道,对于现在像我这样更多是 Python 程序员的人来说,这是编写你需要的 95% 代码的好方法。我们还需要更改什么?好吧,正如我们之前在图中所看到的,它不叫 block。

[31:28] IDX,它叫做 block IDX.x、block dim.x、thread IDX.x。所以,我们得在那里加上 .x。除此之外,如果我们比较一下。所以如你所见,这两段代码看起来几乎一模一样。我们得给它们加上数据类型。我们得加上分号。我们得去掉冒号。我们得加上花括号。大概就这些。所以其实差别并不大。所以如果你没怎么写过 C 语言,别太担心,因为说实话,对于这种计算密集型的工作,它其实并没有那么不同。有一点我们应该讲一下。就是这个。unsigned cast R 是什么?这就是在 C 里写 Uint 8 的方式。你只要,如果你不太确定

[32:32] 确定如何在 PyTorch 的写法和 C 的写法之间转换数据类型,你可以问 ChatGPT 或者谷歌一下。但这就是写 byte 的方式。那个星号实际上基本上就是在说这是一个数组。所以这表示 X 是一个 byte 数组。它实际上意味着它是一个指针,但正如你在这里看到的,指针被 C 当作数组来处理。所以你其实不用太担心它是指针这件事,对我们来说它只意味着它是一个数组。但在 C 里,它唯一知道怎么处理的数组是一维数组。这就是为什么我们总是得把东西展平。我们没法在这种 CUDA kernel 里以这种方式直接使用多维张量。所以我们最终会得到这些一维的 C 数组。除此之外,它看起来会完全一样,事实上,我的意思是,甚至因为我们把 Python 写得像

[33:32] 那样,它看起来会一模一样。这里的 void 只是表示它不返回任何东西。然后这里的双下划线 global 是 CUDA 添加的一个特殊东西。可以出现三种情况。它只是说明,我应该把这个编译成做什么?所以你可以写双下划线 device,那意味着把它编译成只能在 GPU 上调用。你可以写双下划线 global,那表示,好,你可以从 CPU 或 GPU 调用它,它会在 GPU 上运行。或者你可以写双下划线 host,这个你不一定要写。它只是表示这是一个普通的 C 或 C++ 程序,在 CPU 侧运行。所以每当我们想从 CPU 侧调用某个东西来在 GPU 上运行,这基本上在我们写 kernel 时几乎总是如此,你就写双下划线 global。所以这里我们有双下划线 global,我们有我们的 kernel,就这样。那么接下来我们需要

[34:36] 用来调用该内核的东西。所以之前调用内核时,我们调用这个块内核函数,传入内核并传入块和线程。而使用 CUDA 的参数时,我们不必使用特殊函数。内核中内置了一种奇怪的特殊语法来为我们完成这件事。要使用这种奇怪的特殊语法,你说,好,内核是什么,我想调用的函数是什么?然后你使用这些奇怪的三重尖括号。所以。三重尖括号是 C++ 语言的一种特殊 CUDA 扩展。它的意思是这是一个内核,请在 GPU 上调用它。

[35:19] 而在三重尖括号之间,你可以传入若干内容,但至少必须传入前两项,即多少个块、多少个线程。所以多少个块,向上取整除法,像素数除以线程数。以及多少个线程,正如我们之前所说,我们就一直选 256,不用操心。所以这表示将此函数作为 GPU 内核调用,然后传入这些参数。我们必须传入输入张量、输出张量以及像素数。你会看到,对于每个张量,我们必须使用一个特殊方法 dot data pointer。这会把张量转换为 C 指针。所以这就是为什么当它到达我们的内核时,它是一个 C 指针。你还必须告诉它你希望将其视为哪种数据类型。这表示将其视为 Untates。所以这就是这个

[36:23] 在这里是 C++ 模板参数。而这是一个方法。你还需要知道的另一件事是,在 C++ 中,点表示调用对象的方法,或者双冒号基本上就像在 C 中、在 Python 中调用类的方法。所以你不会说 torch 点 empty,而是说 torch 双冒号 empty 来创建我们的输出。或者回到我们用 Python 做的时候,我们说 torch 点 empty。

[36:55] 在 Python 中也是如此。哦,好的。所以在 Python 中,这是对的。我们只是创建了一个长度和向量,然后做了一个点视图。我们怎么做其实并不重要。但在这种情况下,我们实际上是通过传入……我们在这里的花括号中传入了这个东西,从而创建了一个二维张量。这叫做 C++ 列表初始化器。它基本上就是一个包含高度、逗号、宽度的小列表。所以这告诉它创建一个二维矩阵,这就是为什么我们最后不需要点视图。我们也可以用点视图的方式来做。保持一致性可能更好。但这是我当时写的。创建输出时另一个有趣的地方是,如果你传入 input 点 options。所以这是我们的输入张量,它只是说,哦,使用相同的数据类型和相同的设备,即与我们的输入相同的 CUDA 设备。这是一个非常好、非常方便的方式,我甚至觉得我们在 Python 中都没有,用来确保这是相同的数据类型和相同的设备。如果你在这里写 auto,这非常方便。你不必指定是什么类型。

[38:01] 这是。我们本可以写 torch 冒号冒号 tensor。但通过写 auto,它只是说你自己去弄清楚。这是另一个方便的小 C++ 特性。在我们调用内核之后,如果其中有错误,我们不一定会被告知。所以要让它检查错误,你必须写这个。这是一个同样由 PyTorch 提供的宏。细节并不重要。你应该总是在调用内核之后调用它,以确保它能正常工作。然后你可以返回你分配的张量,然后你作为指针传入,然后你填充了它。好的。现在,除了 CUDA 源代码,你还需要 C++ 源代码。而 C++ 源代码只是说,这里是我想要提供给外部世界(在这种情况下是 Python)的所有函数细节的列表。所以这基本上就是你的头文件,

[39:06] 即可生效。所以你完全可以直接从函数定义里把整行复制粘贴过来,然后在末尾加上一个分号。这是你随时都可以做的。接着我们调用之前看过的 load CUDA 函数,传入 CUDA 源代码、C++ 源代码,以及一个列表,列出其中已定义、你希望暴露给 Python 的函数名。这里我们只有一个,就是 RGB 转灰度函数。信不信由你,你要做的就这么多。它会自动——你现在可以看到它在后台运行,用一大堆文件在编译,它为我们生成了一个 main.cpp,然后会把它编译成 main.o,把所有东西编译好、链接到一起,并创建一个模块。你可以看到,我们随后把返回的那个模块放进一个……

[40:10] 名为 module 的变量里。等它完成后,就会加载那个模块。如果我们看看刚创建的模块内部,你会发现除了 Python 自动生成的常规内容之外,里面还有一个函数,RGB 转灰度。好,这太棒了。我们现在有了一个从 Python 可用的 CUDA 函数。如果需要,我们甚至可以看看它把这一切放在哪里。我们可以看一下。它就在那里。你可以看到它创建了 main.cpp,把它编译成了 main.o,创建了一个我们可以加载的库,创建了一个 CUDA 文件,还创建了一个构建脚本。如果需要,我们也可以看看那个构建脚本。

[41:04] 它就在那里。这些都不太重要,知道 PyTorch 在替我们做这些事就挺好。我们不用操心它。这挺酷的。那么为了把张量传进去,我们会检查它是连续的并且在 CUDA 上。所以我们最好确保它确实如此。我们要创建一个 imageC 变量,也就是把图像变成连续的并放到 CUDA 设备上。现在我们可以真正在完整尺寸的图像上运行它了,而不是之前创建的那个极小的缩小图像。这个图像的像素多得多,有 1.7 百万像素,而之前我记得是 35,000、34,000。而且耗时从一秒半降到了一毫秒。这太惊人了。速度快得多了,

[42:07],既因为它现在运行在编译后的代码中,也因为它运行在 GPU 上。将数据放到 GPU 上的步骤不在我们计时的范围内。这大概也合理,因为通常你只做一次,然后在其上运行大量 CUDA 操作。不过,我们把将数据从 GPU 移出并放回 CPU 的步骤也纳入了计时。一个关键原因是,如果不这样做,它实际上可以在 CUDA 代码仍在运行时执行我们的 Python 代码。因此,显示的时间可能会大幅减少,因为它尚未完成同步。所以加上这一步,会强制它完成 CUDA 运行并将数据放回 CPU。这种同步也可以通过打印其中的一个值来触发,或者你可以手动同步。所以在我们完成这些之后,我们就可以

[43:13] 看一下,我们应该得到完全相同的灰度小狗。好的。我们成功地从 Python CUDA 内核创建了第一个真正可工作的代码。这种用 Python 编写再转换为 CUDA 的方法并不特别常见。但我这样做不只是作为教学练习。这就是我喜欢编写 CUDA 内核的方式,至少尽可能多地这样做,因为在 Python 中调试要容易得多。更容易看清到底发生了什么。这样我就不必担心编译问题。即使是我们的简单示例,编译也需要大约 45 或 50 秒

[44:13] 示例。我可以直接运行它。一旦它工作,就将其转换为 C,正如我提到的,你知道,ChatGPT 可以为我们完成大部分工作。所以,我认为这实际上是一种编写 CUDA 内核的绝佳方式,即使当你开始对它们有些熟悉时也是如此。因为它让你能够更快地调试和开发。很多人避免编写 CUDA 只是因为那个过程太痛苦。所以这里有一种方法可以让那个过程不那么痛苦。让我们再做一次。这次我们要实现一些非常重要的东西,即矩阵乘法。矩阵乘法,你可能知道,对深度学习至关重要。它就像我们拥有的最基本的线性代数运算。它的工作方式是你有一个输入矩阵 M 和第二个输入矩阵 N。而

[45:23] 我们遍历 M 的每一行。所以我们遍历 M 的每一行,直到到达这里,我们到了这一行,以及 N 的每一列。这里我们到了这一列。然后我们对那一行和那一列在每个点取点积。这里就是这两个东西的点积。这就是矩阵乘法。所以从概念上讲,这是一个非常简单的操作。而且这是我们在深度学习中会做很多很多很多次的操作。基本上每个深度学习、每个神经网络都把它作为最基本的操作。当然,我们实际上不需要从头实现矩阵乘法,因为库已经替我们做了。但我们经常会遇到需要把某种矩阵乘法融合进去的情况。

[46:24] 所以,你知道,当然,这也只是一个很好的练习。那么我们先来看看如何在纯 Python 中做矩阵乘法。实际上,在我提到的 fast AI 课程中,第二部分第 11 课对矩阵乘法有非常完整深入的讲解,我们在那里花了一两个小时只讲矩阵乘法。这里的细节。

[46:56] 但我们在那里做的是使用 MNIST 数据集来完成这件事。所以我们在这里也要做同样的事情。我们要获取手写数字的 MNIST 数据集。它们是 28 乘 28 的数字。它们看起来像这样。28 乘 28 是 784。所以要做,你知道,基本上做神经网络的一层,或者不带激活函数,我们会做一个矩阵乘法,把图像展平后乘以一个权重矩阵,这个矩阵有 784 行和我们想要的任意多列。如果我们要直接到输出,我会需要这个。所以这会是一个线性函数,一个线性模型。我们会有 10 层,每个数字一层。所以这就是我们的权重。我们实际上不会在这里做任何学习。这既不是深度学习也不是逻辑回归的学习。这只是一个例子。好,所以我们有了权重,也有了输入。

[48:01] 数据。X train 和 X valid。所以我们要先在 Python 中实现这个。再说一次,Python 真的很慢,所以我们把它变小一点。所以矩阵一只有五行。矩阵二将是所有权重。所以那将是一个五乘 784 的矩阵乘以一个 784 乘 10 的矩阵。现在这两个必须匹配。当然它们必须匹配,否则这个点积就无法进行。这两个必须匹配,行对列。好,所以我们把它提取成 A 行、A 列、B 行、B 列。显然 A 列和 B 行是必须匹配的。然后输出将是 A 行乘 B 列。

[48:53] 所以是五乘 10。那么让我们创建一个全零的输出,其中包含行和列。现在我们可以继续遍历 A 的每一行、B 的每一列,并做点积,这涉及遍历最内层的每一个元素,也就是 784 个元素,将 M1 和 M2 中对应的元素相乘,并把它们累加到我们创建的输出张量中。所以正如我们所说,这会给我们一个五乘 10 的输出。五乘 10 的输出。这就是结果。好,这就是我在 Python 中创建东西的方式。我基本上几乎不需要调试。我的代码中几乎从来不会有错误、意外的错误,因为我在 Python 中一行一行地写好了每一行

[49:57] 代码,一步一步来。我在写的过程中逐一检查了它们。然后我把所有单元格复制下来并合并在一起,像这样加上一个函数头。于是这就是 matmul。所以这和我们之前看到的代码完全一样。我们可以调用它。我们会看到,对于 39,200 次最内层操作,我们花了大约一秒。所以这相当慢。好,既然我们已经完成了这些,你听到接下来我们需要把最内层循环作为内核调用来执行,并且要能够并行运行,可能就不会感到意外了。现在,在这个例子中,最内层循环并不是这行代码。实际上是这行代码。我的意思是,我们可以选择让它成为任何我们想要的东西。但在这个例子中,我们就是这样做的。我们要说,对于每个像素,我们不是要对每个

[50:58] 像素,而是对于输出张量中的每个单元格,就像这里的这个,将对应一个 CUDA 线程。所以一个 CUDA 线程将执行点积。这就是执行点积的部分。所以这将是我们的内核。我们可以这样写:matmul 块内核将包含这部分。好,这和我们刚才从上面复制的内容完全一样。现在我们需要一些东西来运行这个内核。你可能不会感到意外,在 CUDA 中,我们将使用块和线程来调用它。但 CUDA 中相当方便的一点是,块和线程不必只是一个 1 维向量。它们可以是一个 2 维甚至 3 维张量。所以在这个例子中,

[52:01] 你可以看到我们有一、二,有点难看清它们到底在哪里结束,二、三、四个块。然后对于每个块,这大致是在一个维度上,然后在另一个维度上也有一、二、三、四、五个块。所以这些块中的每一个都有一个索引。所以这里的这个将是零、零,有点难看清。这里的这个将是一、三,依此类推。而这里的这个将是三、四。所以与其

[53:02] 现在不再只是一个整数块索引,而是会有一个元组块索引。然后在一个块内,要选取比如说这里的这个确切位置,刚才没做好,会有一个线程索引。同样,线程索引不会是一个向量中的单个索引,而是两个元素。所以在这种情况下,它会是向下 0、1、2、3、4、5、6 行。而横向是 1、2、3、4、5、6、7、8、9、10,那是 11、12 吗?我数不清了。也许是横向 12 个。所以这里实际上将由两样东西来定义。一个是块。所以块是 3、4。而线程是 6、12。所以

[54:18] 这就是 CUDA 让我们使用块和线程对二维网格进行索引的方式。我们并非必须这样做。如果我们愿意,这只是一个便利。事实上,我们最多可以使用三个维度。所以现在要创建我们的内核运行器,不再只是为块和线程使用两个嵌套循环,而是必须有两组两个嵌套循环。分别对应我们的 x 和 y、块和线程,或者我们的行和列、块和线程。所以最终看起来有点乱。因为我们现在有四个嵌套的 for 循环。所以我们会先遍历 y 轴上的块,然后遍历

[55:21] x 轴上的块,然后遍历 y 轴上的线程,再遍历 x 轴上的线程。所以这意味着,你可以把这个笛卡尔积看作是对每个块、对每个线程。现在要获取点 y 和点 x,我们会使用这个方便的 Python 标准库小工具,叫做 simple namespace。我用得非常多,所以直接给它起名叫 NS,因为我在快速草稿代码里总是用命名空间。所以我们遍历这四个。然后调用我们的内核,并传入一个包含 y 和 x 坐标的对象。那将是我们的块。我们还传入我们的线程,它是一个包含线程 y 和 x 坐标的对象。它最终会为每个块执行所有可能的块和所有可能的线程编号。我们还需要告诉它每个块有多大,

[56:27] 有多高、有多宽。所以这就是它的含义。如你所见,这将是一个简单的命名空间,一个带有 x 和 y 的对象。所以我们需要知道它们有多大。就像之前一样,我们必须知道块维度。这就是我们传入线程数的原因。所以请记住,这完全是纯 PyTorch。我们实际上并没有调用任何 CUDA。除了用一点点 PyTorch 来做索引和张量创建之外,我们没有调用任何其他库。所以你可以手动运行所有这些。确保你理解了。你可以把它放进调试器里。你可以单步执行。所以它会调用我们的函数。这就是我们的矩阵乘法函数。正如我们所说,它是一个内核,包含我们之前写的点积。所以现在守卫必须检查我们当前所在的行号没有超出我们的高度,并且我们当前所在的列号没有超出我们的宽度。我们还需要知道我们当前处于哪个行号

[57:27] 了。这完全一样。实际上,我应该说列和我们之前看到的完全一样。事实上,你可能记得在 CUDA 中我们有 block IDX.x。这就是原因,对吧?因为在 CUDA 中,它总是给你这些三维的 dim three 结构。所以你必须加上这个 .x。这样我们就能用这种方式求出列。然后我们可以通过查看我们已经经过了多少个块、每个块在 y 轴上有多大,以及我们在 y 轴上已经经过了多少个线程,来求出所在的行。所以我们当前处于哪个行号?我们当前处于哪个列号?它是否在我们的张量边界之内?如果不在,那就停下来,否则就执行我们的点积并把它放入我们的输出张量。所以这全是纯 Python。现在我们可以通过获取第一个输入的高度和宽度、以及……的高度和宽度来调用它。

[58:35] 我们的第二个输入。然后 k 和 k2,内部维度应当匹配。然后我们可以创建我们的输出。所以现在每个块的线程数不再只是一个数字 256,而是一对数字。它是一个 x 和一个 y。我们选择了两个相乘得到 256 的数字。所以再说一次,如果你有二维输入,这是一个合理的选择,可以很好地分散开来。这里需要注意的一点是,你的每个块的线程数不能大于 1024。所以我们使用 256,这是安全的。注意你必须把这些相乘。16 乘以 16 就是每个块的线程数。所以这些是可以安全使用的数字。不过你不会用完块。

[59:30] 2 到 31 是维度 0 的最大块数,然后是 2 到 16 用于维度 1 和 2。我认为实际上是减 1,但不用担心这个。所以不要有太多线程,但可以有大量块。但当然,每个对称模型处理器都会在同一设备上运行所有这些,并且它们也能访问共享内存。所以这就是为什么每个块使用少量线程。所以我们的块,x,我们将使用向上取整除法。y,我们将使用相同的向上取整除法。如果这些中有任何不熟悉的,请回到我们之前的示例,因为代码都是从那里复制的。现在我们可以调用我们的 2D 块内核运行器,传入内核。块数、每个块的线程数、我们展平的输入矩阵、我们展平的输出矩阵,以及它需要的维度,因为它们在这里都会被用到,并返回结果。所以如果我们用……调用那个 mapMole

[1:00:35] 2D 块,我们可以检查它们是否接近我们在原始手动循环中得到的结果。当然它们是,因为运行的是相同的代码。现在我们已经完成了这些,我们可以做 CUDA 版本了。现在 CUDA 版本会快得多,我们不再需要使用这个精简的矩阵了。我们可以使用整个矩阵。所以为了检查它是否正确,我想要一个快速的基于 CPU 的方法,以便我可以进行比较。之前处理 39,000 个元素大约需要一秒。所以我不打算解释这是如何工作的,但我将使用广播方法来实现一个快速的基于 CPU 的方法。如果你查看 fast AI 课程,我们会教你如何做这种广播方法。但这是一个纯 Python 方法,它设法在单个循环中完成所有工作,而不是三个嵌套循环。对于缩减后的张量,它给出了相同的答案。

[1:01:47] 但快得多,只需四毫秒。所以它足够快,我们现在可以在整个输入矩阵上运行它。大约需要 1.3 秒。所以这个广播优化版本,如你所见,要快得多。现在我们在三个循环中间有 392 百万次加法,实际上是三个循环,但我们在对它们进行广播。所以这要快得多。

[1:02:19] 但我这么做的真正原因是,这样我们就能把这个结果存下来做对比。这样就能确保我们的 CUDA 版本是正确的。好,那我们怎么把它转换成 CUDA 呢?你可能不会感到意外,我做的就是把这个函数拿过来,交给 ChatGPT,然后说:请用 C 重写它。它给我的东西基本上第一次就能直接用。就是这个。这次我没有 unsigned 指针转换,而是 float 指针。除此之外,它看起来几乎和我们之前的 Python 一模一样,改动也和我们之前看到的一模一样。我们现在有了 .y 和 .x 版本。同样,我们有 DunderGlobal,它表示当我们从 CPU 调用它时,请在 GPU 上运行。所以这个 kernel,我觉得没什么好讲的。然后调用 kernel 的那个东西,matmul,将会是

[1:03:21] 传入两个张量。我们要检查它们都是连续的,并检查它们在 CUDA 设备上。我们会取第一个和第二个张量的高度和宽度。我们要取内维。我们会像之前一样确保两个矩阵的内维匹配。这就是在 PyTorch CUDA 代码里做断言的方法。你调用 torch check,传入要检查的东西,传入出问题时弹出的消息。这些东西非常适合散布在你的 CUDA 代码各处,以确保一切都如你所想。和之前一样,我们创建一个输出。所以现在当我们创建线程数时,我们不说 threads 是 256。我们而是说,这是 CUDA 为我们提供的一个特殊东西,dim3。

[1:04:17] 所以这基本上是一个包含三个元素的元组。所以我们要创建一个名为 tpb 的 dim3。它将是 16 乘 16。现在我说它有三个元素。第三个在哪?没关系。它只是把第三个当作一。所以我们可以忽略它。这就是每个块的线程数。那么会有多少个块呢?嗯,在 X 维度上,将是 W 除以 X,向上取整除法。在 Y 维度上,将是 H 除以 Y,向上取整除法。这就是我们拥有的块数。所以和之前一样,我们调用 kernel,就像调用普通函数一样。但然后我们加上这个奇怪的三尖括号,告诉它有多少个块和多少个线程。所以这些不再是 int 了。这些现在是 dim3 结构。这就是我们使用的,

[1:05:18]这些 dim3 结构。而事实上,甚至在此之前,当我们做灰度处理时,幕后实际发生的情况是,尽管我们传入了 256,例如,我们最终得到的是一个 dim3 结构,在这种情况下,索引一和二,或者点 X、点 Y 和点 Z 的值会被自动设置为一。所以我们其实已经在不知不觉中使用了 dim3 结构。然后就像之前一样,传入我们想要的所有张量,将它们转换为指针,也许不只是转换,而是通过某种特定的数据类型将它们转换为指针,并传入我们的函数、那个内核所需的任何其他信息。好的,然后我们再次调用 load CUDA,这会把其编译成一个模块,使

[1:06:21]确保它们都是连续的并且位于 CUDA 设备上。然后,在我们调用 module 点 mapmul 并传入这些之后,将它们放到 CPU 上并检查它们是否都接近,结果显示是的,它们确实如此。现在这不仅仅是在前五行上运行,而是在整个 MNIST 数据集上运行。在整个 MNIST 数据集上,使用优化的 CPU 方法,耗时 1.3 秒。使用 CUDA,耗时 6 毫秒。所以这是相当大的提升。酷。当然,我还要提到的另一件事是,PyTorch 只需使用 at 就能为我们做矩阵乘法。需要多长时间,而且显然给出相同的答案,运行需要多长时间?那需要 2 毫秒。所以快了三倍。而在许多情况下,它会远不止快三倍

[1:07:26]更快。那么,为什么相比 PyTorch 我们仍然相当慢呢?我的意思是,在 6 毫秒内完成 392 百万次这样的计算并不算差。但如果 PyTorch 能快这么多,它们在做什么呢?嗯,诀窍在于它们特别利用了这种共享内存。所以,共享内存是一个很小的内存空间,在一个块中的线程之间共享,它比全局内存快得多。在我们的矩阵乘法中,当我们有其中一个块时,而且,所以它会一次处理一个块,全部在同一个 SM 中,它会重复使用相同的 16 乘 16 块。它会一次又一次地使用相同的 16 行和列,每次都访问相同的共享内存。所以你可以看到,你确实有可能缓存信息,很多你需要的信息,并重复使用它们,而不是

[1:08:28] 一次又一次地回到较慢的内存。所以这是一个例子,说明一旦你达到那个阶段,你可以优化的事情类型。我在这里想提到的唯一另一件事是,这个 2D 块的想法完全是可选的。你可以用 1D 块、2D 块或 3D 块和线程来完成所有事情。为了展示这一点,我在最后实际上有一个例子,使用 2D 块将 RGB 转换为灰度。因为记住之前我们做这个时,是用 1D 块。它给出了完全相同的结果。如果我们比较代码,所以如果我们比较代码,实际上用 1D 线程和块完成的版本,相当

[1:09:33] 比使用 2D 线程和块的版本短一点。所以在这种情况下,即使我们在操作像素,你可能会认为使用 2D 方法会更整洁、更方便,但在这种特定情况下,它并不是真的。我们仍然需要相当简单地分别处理列和行 x.y。守卫稍微复杂一些。我们必须找出我们实际到达的索引。而在其他地方,这个内核要直接得多,只有两行代码。然后调用内核,同样,使用每块线程数的方式比这个稍微复杂一些。我想指出的关键点是,这两段代码做的事情完全相同。所以不要觉得如果你不想使用 2D 或 3D 块线程结构,你就必须使用。你可以只使用 1D 的。

[1:10:32] 2D 的东西只有在它对你方便并且你想使用时才存在。不要觉得你必须使用它。所以是的,我想这基本上就是我今天想向大家展示的所有关键内容。我希望你从中得到的主要收获是,即使对于 Python 程序员、数据科学家来说,这也不完全超出我们的舒适区。我们可以用 Python 写这些东西,我们可以几乎自动地转换它们,最终得到的代码看起来,你知道,看起来相当熟悉,即使它现在是用不同的语言。我们可以在笔记本内完成所有事情,我们可以边做边测试所有东西,我们可以从内核中打印东西。所以,你知道,希望感觉上比我们以前可能认为的要稍微不那么超出我们的能力范围

[1:11:35] 想象一下。所以我会说,对,你知道,放手去做吧。我认为如今能够编写 CUDA 代码也越来越重要,因为像 flash attention 或者量化、GPTQ、AWQ、bits and bytes 这些东西,都是你无法用 PyTorch 编写的。你知道,我们的模型正变得越来越复杂。像 PyTorch 这样的库对我们想做的事情所做的那些假设,你知道,正变得越来越不准确。

[1:12:12] 所以如今我们不得不用 CUDA 自己来做越来越多这类事情。因此我认为这是一项非常有价值的能力。另外,我提到的一点是,今天我们都是在 Colab 里完成的,但如果你有 GPU,或者用云机器,我们也可以在自己的机器上做。为此进行环境搭建,同样,它比你想象的要简单得多。事实上,我可以给你演示,基本上就是四行代码,或者三四行 bash 脚本就能全部搭好。它可以在 Windows 或 WSL 下运行,当然也可以在 Linux 上运行。Mac 上的东西当然不太行……CUDA 相关的东西在 Mac 上不太能跑。它们不在 Mac 上。实际上,我会把这个链接放到视频说明里。但现在,我先跳转到一条 Twitter 推文串,我在那里把这一切都写了下来,给你们展示

[1:13:15] 这些步骤。所以做法是使用一个叫 Conda 的东西。Conda 是极少数人真正理解的东西。很多人以为它像是 PIP 或 poetry 之类的替代品。并不是。最好把它看作 Docker 的替代品。你完全可以在自己的机器上同时并行拥有多个不同版本的 Python、多个不同版本的 CUDA、多个不同的 C++ 编译系统,并在它们之间切换。你只能用 Conda 做到这一点。而且一切都能正常工作。所以你不必担心 .run 文件或 Ubuntu 软件包之类那些令人困惑的东西。你可以只用 Conda 完成一切。你需要安装 Conda。我实际上有一个脚本,你只要运行这个脚本就行。如你所见,它是一个很小的脚本。如果你直接运行这个脚本,它会自动判断你需要哪个 mini Conda。它会自动判断你用的是哪个 shell,

[1:14:18],它就会直接为你下载并安装好。好,运行那个脚本,重启你的终端。现在你就有了 Conda。第二步是查明 PyTorch 需要哪个版本的 CUDA。所以如果我点击 Linux、Conda,CUDA 12.1 是最新的。那么第三步就是运行这个 shell 命令,把 12.1 替换成当前 PyTorch 的版本。对我来说目前其实还是 12.1。这样就会安装所有东西。你进行性能分析、调试、构建等所需的所有东西。你需要的所有 NVIDIA 工具,完整套件,都会安装好,而且它直接来自 NVIDIA,所以你会得到正确的版本。正如我所说,你可以在不同环境中同时安装多个版本。完全没问题。最后,

[1:15:18] 安装 PyTorch。这里的这个命令会安装 PyTorch。不知为何我在这里写了 nightly。你不需要 nightly。只要去掉 dash nightly 就行。这样就会安装最新版本的 PyTorch,使用你刚刚安装的 NVIDIA CUDA 相关内容。如果你以前用过 Conda,而且它真的很慢,那是因为它过去使用了一个不同的求解器,比现代的求解器慢成千上万倍。它只是在过去几个月里才被加入并设为默认。所以如今这一切应该都会运行得非常快。正如我所说,它会在 Windows 上的 WSL 下运行。它会在 Ubuntu 上运行。它会在 Fedora 上运行。它会在 Debian 上运行。一切都会正常工作。所以这就是我强烈推荐的本地开发环境搭建方式。你不需要担心使用 Docker。正如我所说,你可以在不同的 CUDA 版本、不同的 Python 版本、不同的编译器等等之间切换,而无需担心任何

[1:16:23] Docker 相关的内容。而且它足够高效,如果你在多个环境中安装了相同的库等,它会用硬链接。所以甚至不会占用额外的硬盘空间。因此它也非常高效。很好。这就是如何在你自己机器上或云端开始的方法。或者随便什么地方。所以希望你觉得这也有帮助。好。非常感谢观看。希望你觉得这有用,我期待听到你用 CUDA 创造的东西。至于下一步,去看看其他 CUDA 模式的讲座。我会链接到它们。我也建议尝试一些你自己的项目。所以,例如,你可以尝试实现像 4 位量化或 Flash Attention 或。

[1:17:24] 之类的东西。这些项目都相当大,但你可以尝试把它们拆分成更小的部分,一步一步地构建起来。当然,也要看看别人的代码。看看 Flash Attention 的实现,看看 bits and bytes 的实现,看看 GPTQ 等等的实现。你花在阅读别人代码上的时间越多越好。好了,希望你觉得这期内容有用,非常感谢你的观看。

查看英文原始字幕

[0:01] Hi there, I'm Jeremy Howard from Answer.AI and this is Getting Started with CUDA. CUDA is of course what we use to program NVIDIA GPUs if we want them to go super fast and we want maximum flexibility. And it has a reputation of being very hard to get started with. The truth is, it's actually not so bad. You just have to know some tricks. And so in this video I'm going to show you some of those tricks. So let's switch to the screen and take a look. So I'm going to be doing all of the work today in notebooks. This might surprise you. You might be thinking that to do work with CUDA we have to do stuff with compilers and terminals and things like that. And the truth is actually it turns out we really don't, thanks to some magic that is provided by PyTorch. You can follow along in all of these steps and I strongly suggest you do so in your own computer. You can

[1:03] go to the CUDA mode organization in GitHub, find the Lecture 2 repo there and you'll see there is a Lecture 3 folder. This is Lecture 3 of the CUDA mode series. You don't need to have seen any of the previous ones, however, to follow along. In the readme there you'll see there's a Lecture 3 section and at the bottom there is a click to go to the Colab version. Yep, you can run all of this in Colab for free. You don't even have to have a GPU available to run the whole thing.

[1:39] We're going to be following along with some of the examples from this book Programming Massively Parallel Processes. Programming Massively Parallel Processes is a really great book to read and once you've completed today's lesson you should be able to make a great start on this book. It goes into a lot more details about some of the things that we're going to cover on fairly quickly. It's okay if you don't have the book, but if you want to go deeper I strongly suggest you get it. In fact you'll see in the repo that Lecture 2 in this series actually was a deep dive into chapters 1 to 3 of that book. So actually you might want to do Lecture 2, confusingly enough, after this one, Lecture 3, to get more details about some of what we're talking about. Okay, so let's dive into the notebook. So what we're going to be doing today is we're going to be doing a whole lot of stuff

[2:41] with old PyTorch first to make sure that we get all the ideas and then we will try to convert each of these things into CUDA. So in order to do this we're going to start by importing a bunch of stuff. In fact let's do all of this in Colab. So here we are in Colab and you should make sure that you set in Colab your runtime to the T4 GPU. This one you can use plenty of for free and it's easily good enough to run everything we're doing today. And once you've got that running we can import the libraries we're going to need and we can start on our first exercise. So the first exercise actually comes from Chapter 2 of the book and Chapter 2 of the book teaches how to do this problem which is converting an RGB color picture into a grayscale picture. And it turns out that the recommended formula for this is to take 0.21 of the red pixel, 0.72 of the green pixel,

[3:44] 0.07 of the blue pixel and add them up together and that creates the luminance value which is what we're seeing here. That's a common way, the kind of the standard way to go from RGB to grayscale. So we're going to do this, we're going to make a CUDA kernel to do this. So the first thing we're going to need is a picture and anytime you need a picture I recommend going for a picture of a puppy. So we've got here a URL to a picture of a puppy. So we'll just go ahead and download it and then we can use torchvision.io to load that. So this is already part of Colab. If you're interested in running stuff on your own machine or a server in the cloud I'll show you how to set that up at the end of this lecture. So let's read in the image and if we have a look at the shape of it it says it's 3 by 1066 by 1600. So I'm going to assume that you know the basics

[4:44] of PyTorch here. If you don't know the basics of PyTorch I am a bit biased but I highly recommend my course which covers exactly that. You can go to course.fast.ai and you get the benefit also of having seen some very cute bunnies and along with the very cute bunnies it basically takes you through all of everything you need to be an effective practitioner of modern deep learning.

[5:14] So finish part one if you want to go right into those details but even if you just do the first two or three lessons that will give you more than enough you need to know to understand this kind of code and these kinds of outputs. So I have a sigma you've done all that. So you'll see here we've got a rank 3 tensor. There are three channels so they're like the faces of a cube if you like. There are 1066 rows on each face so that's the height and then there are 16 columns in each row so that's the width. So if we then look at the first couple of channels and the first three rows and the first four columns you can see here that these are unsigned 8-bit integers. So they're bytes and so here they are. So that's what an image looks like. Hopefully you know all that already. So let's take a look at our image. To do that I'm just going to create a simple little function show image that will create a mat lip plot. Remove the axes. If it's color which this

[6:23] one is it will change the order of the axes from channel by height by width which is what PyTorch uses to height by width by channel which is what mat plot lip I'm having trouble today expects. So we change the order of the axes to be 1 2 0 and then we can show the edge. Putting it on the CPU if necessary. Now we're going to be working with this image in Python which is going to be just pure Python to start with before we switch to CUDA. It's going to be really slow so we'll resize it to have the smallest length smallest dimension be 150. So that's the height in this case. So we end up with a 150 by 225 shape which is a rectangle which is 3 3 750 pixels each one with R, G and B values and there is our puppy. So you see it wasn't a good idea to make this a puppy. Okay

[7:24] so how do we convert that to grayscale? Well the book has told us the formula to use. Go through every pixel and do that to it. Alright so here is the loop we're going to go through every pixel and do that to it and stick that in the output. So that's the basic idea. So what are the details of this? Well here we've got channel by row by column. So how do we loop through every pixel?

[7:55] Well the first thing we need to know is how many pixels are there. So we can say channel by height by width is the shape. So now we've defined those three variables. So the number of pixels is the height times the width. And so to loop through all those pixels an easy way to do them is to flatten them all out into a vector. Now what happens when you flatten them all out into a vector? Well as we saw they're currently stored in this format where we've got one face and then another face and then there's a we haven't got it printed here but there's a third face. Within each face then there is one row. We're just showing the first few and then the next row and then the next row and then with each row you've got column, column, column. So let's say we had a small image in which in fact we can do it like this. We could say here's our red so we've got the pixels of 0, 1, 2,

[9:05] 3, 4, 5. So let's say this was a height 2, width 3, 3 channel image. So then there'll be 6, 7, 8, 9, 10, 11, RGB, 12, 13, 14, 15, 16. So let's say these are the pixels. So when these are flattened out it's going to turn into a single vector just like so. 6, 7, 8, 12, 13, 14. So actually when we talk about an image we initially see it as a bunch of pixels. We can think of it as having

[10:09] 3 channels but in practice in our computer the memory is all laid out linearly. Everything has just an address in memory. It's just a whole bunch. You can think of it as your computer's memory is one giant vector. And so when we say, when we say flatten then what that's actually doing is it's turning our channel by height by width into a big vector like this. Okay, so now that we've done that we can say, alright, the place we're going to be putting this into, the result, we're going to start out with just an empty vector of length n. We'll go through all of the n values from 0 to n minus 1 and we're going to put in the output value 0.29-ish times

[11:17] the input value at x i. So this will be here in the red bit. And then 0.59 times x i plus n. So n here, n here is this distance. It's the number of pixels, 1, 2, 3, 4, 5, 6. So that's why to get to green we have to jump up to i plus n. And then to get to blue we have to jump to i plus 2n. And so that's how this works. We've flattened everything out and we're indexing into this flattened out thing directly. And so at the end of that we're going to have our grayscale is all done. So we can then just reshape that into height by width. And there it is. There's our grayscale puppy. And you

[12:26] can see here the flattened image is just a single vector with all those channel values flattened out as we described. Okay now that is incredibly slow. It's nearly two seconds to do something with only 34,000 pixels in. So to speed it up we are going to want to use CUDA. How come CUDA is able to speed things up? Well the reason CUDA is able to speed things up is because it is set up in a very different way to how a normal CPU is set up. And we can actually see that if we look at some of this information about what is in an RTX 3090 card for example. Now an RTX 3090 card is a fantastic GPU. You can get them secondhand, pretty good value. So a really good choice particularly for

[13:31] hobbyists. What is inside a 3090? It has 82 SMs. What's an SM? An SM is a streaming multiprocessor. So you can think of this as almost like a separate CPU in your computer. And so there's 82 of these. So that's already a lot more than you have CPUs in your computer. But then each one of these has 128 CUDA cores. So these CUDA cores are all able to operate at the same time. These multiprocessors are all able to operate at the same time. So that gives us 128 times 82. 10,500 CUDA cores in total that can all work at the same time. So that's a lot more than any CPU we're familiar with can do.

[14:26] And the 3090 isn't even at the very top end. It's really a very good GPU but there are some with even more CUDA cores. So how do we use them all? Well we need to be able to set up our code in such a way that we can say here is a piece of code that you can run on lots of different pieces of data, lots of different pieces of memory at the same time so that you can do 10,000 things at the same time. And so CUDA does this in a really simple and pretty elegant way which is it basically says okay take out the kind of the inner loop. So here's our inner loop. The stuff where you can run 10,000 of these at the same time. They're not going to influence each other at all. So you see these do not influence each other at all. All they do is they stick something into some output memory. So it doesn't even return something. You can't return something from these CUDA kernels as they're going to be called. All you can do is you can modify memory in such a way that you don't know what

[15:30] order they're going to run in. They could all run at the same time. Some could run a little bit before another one and so forth. So the way that CUDA does this is it says okay write a function. And in your function write a line of code which I'm going to call as many dozens, hundreds, thousands, millions of times as necessary to do all the work that's needed. And I'm going to do this in parallel for you as much as I can. In the case of running on a 3090, up to 10,000 times, up to 10,000 things all at once. And I will get this done as fast as possible. So all you have to do is basically write the line of code you want to be called lots of times. And then the second thing you have to do is say how many times to call that code. And so what will happen is that piece of code called the kernel will be called for you. It'll be passed in whatever arguments you ask to be passed in, which in this case will be the input array tensor, the output tensor, and the size of

[16:35] how many pixels are in each channel. And it'll tell you, okay this is the ith time I've called it. Now we can simulate that in Python, very, very simply, a single for loop. Now this doesn't happen in parallel, so it's not going to speed it up, but the kind of results, the semantics, are going to be identical to CUDA. So here is a function we've called run kernel. We're going to pass it in a function. We're going to say how many times to run the function and what arguments to call the function with. And so each time it will call the function passing in the index, what time, and the arguments that we've requested. Okay, so we can now create something to call that. So let's get the, just like before, get the number of channels, height and width, the number of pixels, flatten it out, create the result tensor that we're going to put things in. So this time, rather than calling the loop directly, we will call run kernel. We will pass in the name of the

[17:42] function to be called as f. We will pass in the number of times, which is the number of pixels for the loop. And we'll pass in the arguments that are going to be required inside our kernel. So we're going to need out, we're going to need x, and we're going to need n. So you can see here we're using no external libraries at all. We have just plain Python and a tiny bit of PyTorch, just enough to create a tensor index into tensors. And that's all that's being used. Conceptually, it's doing the same thing as a CUDA kernel would do, nearly. And we'll get to the nearly in just a moment. But conceptually, you could see that you could now potentially write something, which if you knew that this was running a bunch of things totally independently of each other, conceptually,

[18:48] you could now truly easily parallelize that. And that's what CUDA does. However, it's not quite that simple. It does not simply create a single list of numbers like range n does in Python and pass each one in turn into your kernel. But instead, it actually splits the range of numbers into what's called blocks. So in this case, maybe there's like 1,000 pixels we wanted to get through. It's going to group them into blocks of 256 at a time. And so in Python, it looks like this. In practice, a CUDA kernel runner is not a single for loop that loops n times. Instead,

[19:49] it is a pair of nested for loops. So you don't just pass in a single number and say this is the number of pixels, but you pass in two numbers, number of blocks and the number of threads. We'll get into that in a moment. But these are just numbers. They're just you can put any numbers you like here. And if you choose two numbers that multiply to get the thing that we want, which is the n times we want to call it, then this can do exactly the same thing because we're now going to pass in which of the what's the index of the outer loop we're up to, what's the index in the inner loop we're up to, how many things do we go through in the inner loop, and therefore inside the kernel, we can find out what index we're up to by multiplying the block index times the block dimension. So that is to say the i by the threads and add the inner loop index, the j. So that's

[20:51] what we pass in with the i, j threads. But inside the kernel, we call it block index, thread index and block dimension. So if you look at the CUDA book, you'll see here this is exactly what they do. They say the index is equal to the block index times the block dimension plus the thread index. There's a dot x thing here that we can ignore for now. We'll look at that in a moment. But in practice, this is actually how CUDA works. So it has all these blocks and inside there are threads and you can just think of them as numbers. You can see these blocks, they just have numbers, o, one, dot, dot, dot, dot, and so forth. Now that does mean something a little bit tricky though, which is, well, the first thing I'll say is how do we pick these numbers, the number of blocks and the number of threads? For now in practice, we're just always going to say the number of threads is 256. And that's a perfectly fine number to use as a default. Anyway, you can't go too far wrong,

[21:58] just always picking 256, nearly always. So don't worry about that too much for now optimizing that number. So if we say, okay, we want to have 256 threads, so remember that's the inner loop, or if we look inside our kernel runner here, that's our inner loop. So we're going to call each of, this is going to be called 256 times. So how many times do you have to call this? Well, you're going to have to call it n, number of pixels, divided by 256 times. Now that might not be an integer, so you'll have to round that up. So that's how we can calculate the number of blocks we need to make sure that our kernel is called enough times. Now we do have a problem though, which is that the number of times we would have liked to have called it, which previously was equal to the number of pixels, might not be a multiple of 256. So we might end up going too

[23:02] far. And so that's why we also need in our kernel now this if statement. And so this is making sure that the index that we're up to does not go past the number of pixels we have. And this appears in basically every CUDA kernel you'll see, and it's called the guard, or the guard block. So this is our guard to make sure we don't go out of bounds. So this is the same line of code we had before. Now we've also just added this thing to calculate the index, and we've added the guard.

[23:34] And this is like the pretty standard first lines from any CUDA kernel. So we can now run those, and they'll do exactly the same thing as before. And so the obvious question is, well, why? Why do CUDA kernels work in this weird block and thread way? Why don't we just tell them the number of times to run it? Why do we have to do it by blocks and threads? And the reason why is because of some of this detail that we've got here, which is that CUDA sets things up for us so that everything in the same block, or to say it more completely thread block, which is the same block, they will all be given some shared memory. And they'll also all be given the opportunity to synchronize, which is to basically say, OK, everything in this block has to get to this point before you

[24:35] can move on. All of the threads in a block will be executed on the same streaming multiprocessor. And so we'll see later in later lectures, but won't be taught by me, that by using blocks smartly, you can make your code run more quickly. And the shared memory is particularly important. So shared memory is a little bit of memory in the GPU that all the threads in a block share and it's fast.

[25:08] It's super, super, super fast. Now when we say not very much, it's like on a 3090, it's 128K. So very small. This is basically the same as a cache in a CPU. The difference, though, is that on a CPU, you're not going to be manually deciding what goes into your cache. But on the GPU, you do. It's all up to you. So at the moment, this cache is not going to be used when we create our CUDA code because we're just getting started. And so we're not going to worry about that optimization. But to go fast, you want to use that cache. And also, you want to use the register file. Something a lot of people don't realize is that there's actually quite a lot of register memory, even more register memory than shared memory. So anyway, those are all things to worry about down the track, not needed for getting started. So how do we go about using CUDA? There is a basically standard

[26:15] setup block that I would add, and we are going to add. And what happens in this setup block is we're going to set an environment variable. You wouldn't use this in production or for going fast. But this says, if you get an error, stop right away, basically. So wait to see how things go. And then that way, you can tell us exactly when an error occurs and where it happens. So that slows things down, but it's good for development. We're also going to install two modules. One is a build tool, which is required by PyTorch to compile your C++ CUDA code. The second is a very handy little thing called WorldLitza. And the only place you're going to see that used is in this line here, where we load this extension called WorldLitza. Without this, anything you print from your CUDA code, in fact, from your C++ code, won't appear in a notebook. So you always want to do this in a

[27:19] notebook where you're doing stuff in CUDA so that you can use print statements to debug things. OK. So if you've got some CUDA code, how do you use it from Python? The answer is that PyTorch comes with a very handy thing called LoadInline, which is inside torch.utils.cpp extension. LoadInline is a marvelous function that you just pass in a list of any of the CUDA code strings that you want to compile, any of the plain C++ strings that you want to compile, any functions in that C++ you want to make available to PyTorch. And it will go and compile it all, turn it into a Python module and make it available right away, which is pretty amazing. I've just created a tiny little wrapper

[28:26] for that called LoadCuda, just to streamline it a tiny bit. Behind the scenes, it's just going to call LoadInline. The other thing I've done is I've created a string that contains some C++ code. This is all C code, I think, but it's compiled as C++ code. We'll call it C++ code. C++ code we want included in all of our CUDA files. We need to include this header file to make sure that we can access PyTorch tensor stuff. We want to be able to use I.O. and we want to be able to check for exceptions. And then I also define three macros. The first macro just checks that a tensor is CUDA. The second one checks that it's contiguous in memory, because sometimes PyTorch can actually split things up over different memory pieces. And then if we try to access that in this

[29:29] flattened out form, it won't work. And then the way we're actually going to use it, check input, we'll just check both of those things. So if something's not on CUDA and it's not contiguous, we aren't going to be able to use it. So we always have this. And then the third thing we do here is we define ceiling division. Ceiling division is just this. Although you can implement it a different way like this. And so this will do ceiling division. And so this is how we're going to, this is what we're going to call in order to figure out how many blocks we need. So this is just, you don't have to worry about the details of this too much. It's just a standard setup we're going to use. OK, so now we need to write our CUDA kernel. Now, how do you write the CUDA kernel?

[30:19] Well, all I did, and I recommend you do, is take your Python kernel and paste it into chat GPT and say convert this to equivalent C code using the same names, formatting, etc. Where possible, paste it in and chat GPT will do it for you. Unless you're very comfortable with C, which goes just write it yourself is fine. But this way, since you've already got the Python, why not just do this? It basically was pretty much perfect. I found, although it did assume that these were floats, they're actually not floats. We had to change a couple of data types, but basically I was able to use it almost as is. And so particularly, you know, for people who are much more Python programmers nowadays like me, this is a nice way to write 95% of the code you need. What else do we have to change? Well, as we saw in our picture earlier, it's not called block

[31:28] IDX, it's called block IDX.x, block dim.x, thread IDX.x. So we have to add the dot X there. Other than that, if we compare. So as you can see, these two pieces of code look nearly identical. We've had to add data types to them. We've had to add semicolons. We had to get rid of the colon. We had to add curly brackets. That's about it. So it's not very different at all. So if you haven't done much C programming, yeah, don't worry about it too much because, you know, the truth is actually it's not that different for this kind of calculation intensive work. One thing we should talk about is this. What's unsigned cast R? This is just how you write Uint 8 in C. You can just if you're not

[32:32] sure how to change change a data type between the Pytorch spelling and the C spelling, you could ask chat GPT or you can Google it. But this is how you write byte. The star in practice, it's basically how you say this is an array. So this says that X is an array of bytes. It actually means it's a pointer, but pointers are treated, as you can see here, as arrays by C. So you don't really have to worry about the fact that the pointer, it just means for us that it's an array. But in C, the only kind of arrays that it knows how to deal with these one dimensional arrays. And that's why we always have to flatten things out. We can't use multidimensional tensors really directly in these CUDA kernels in this way. So we're going to end up with these one dimensional C arrays. Yeah, other than that, it's going to look exactly in fact, I mean, even because we did our Python like

[33:32] that, it's going to look identical. The void here just means it doesn't return anything. And then the Dunder global here is a special thing added by CUDA. There's three things that can appear. And this simply says, what should I compile this to do? And so you can put Dunder device, and that means compile it so that you can only call it on the GPU. You can say Dunder global, and that says, OK, you can call it from the CPU or GPU and it'll run on the GPU. Or you can write Dunder host, which you don't have to. And that just means it's a normal C or C++ program that runs on the CPU side. So any time we want to call something from the CPU side to run something on the GPU, which is basically almost always when we're doing kernels, you write Dunder global. So here we've got Dunder global, we've got our kernel and that's it. So then we need

[34:36] the thing to call that kernel. So earlier to call the kernel, we called this block kernel function passed in the kernel and passed in the blocks and threads. And the arguments with CUDA, we don't have to use a special function. There is a weird special syntax built into kernel to do it for us. To use the weird special syntax, you say, OK, what's the kernel, the function that I want to call? And then you use these weird triple angle brackets. So the triple angle brackets is a special CUDA extension to the C++ language. And it means this is a kernel, please call it on the GPU.

[35:19] And between the triple angle brackets, there's a number of things you can pass, but you have to pass at least the first two things, which is how many blocks, how many threads. So how many blocks, ceiling division, number of pixels divided by threads. And how many threads, as we said before, let's just pick 256 all the time and not worry about it. So that says call this function as a GPU kernel and then passing in these arguments. We have to pass in our input tensor, our output tensor and how many pixels. And you'll see that for each of these tensors, we have to use a special method dot data pointer. And that's going to convert it into a C pointer to the tensor. So that's why by the time it arrives in our kernel, it's a C pointer. You also have to tell it what data type you want it to be treated as. This says treat it as Untates. So that's this

[36:23] is a C++ template parameter here. And this is a method. The other thing you need to know is in C++ dot means call a method of an object, or else colon colon is basically like in C, in Python calling a method of a class. So you don't say torch dot empty, you say torch colon colon empty to create our output. Or else back when we did it in Python, we said torch dot empty.

[36:55] Also in Python. Oh, OK. So in Python, that's right. We just created a length and vector and then did a dot view. It doesn't really matter how we do it. But in this case, we actually created a two dimensional tensor by passing. We pass in this thing in curly brackets here. This is called a C++ list initializer. And it's just basically a little list containing height comma width. So this tells it to create a two dimensional matrix, which is why we don't need dot view at the end. We could have done it the dot view way as well. Probably be better to keep it consistent. But this is what I wrote at the time. The other interesting thing when we create the output is if you pass in input dot options. So this is our input tensor that just says, oh, use the same data type and the same device, CUDA device as our input has. This is a nice, really convenient way, which I don't even think we have in Python to say, make sure that this is the same data type in the same device. If you say auto here, this is quite convenient. You don't have to specify what type

[38:01] this is. We could have written torch colon colon tensor. But by writing auto, it just says figure it out yourself. Which is another convenient little C++ thing. After we call the kernel, if there's an error in it, we won't necessarily get told. So to tell it to check for an error, you have to write this. This is a macro that's again provided by PyTorch. The details don't matter. You should just always call it after you call a kernel to make sure it works. And then you can return the tensor that you allocated and then you passed as a pointer and then that you filled in. OK. Now, as well as the CUDA source, you also need C++ source. And the C++ source is just something that says, here is a list of all of the details of the functions that I want you to make available to the outside world. In this case, Python. And so this is basically your header,

[39:06] effectively. So you can just copy and paste the full line here from your function definition and stick a semicolon on the end. So that's something you can always do. And so then we call our load CUDA function that we looked at earlier, passing in the CUDA source code, the C++ source code, and then a list of the names of the functions that are defined there that you want to make available to Python. So we just have one, which is the RGB to grayscale function. And believe it or not, that's all you have to do. This will automatically, you can see it running in the background now, compiling with a hugely long thing our files from, so it's created a main.cpp for us, and it's going to put it into a main.o for us and compile everything up, link it all together and create a module. And you can see here, we then take that module that's been passed back and put it into a

[40:10] variable called module. And then when it's done, it will load that module. And if we look inside the module that we just created, you'll see now that apart from the normal auto-generated stuff, Python adds, it's got a function in it, RGB to grayscale. Okay, so that's amazing. We now have a CUDA function that's been made available from Python. And we can even see if we want to, this is where it put it all. So we can have a look. And there it is. You can see it's created a main.cpp, it's compiled it into a main.o, it's created a library that we can load up, it's created a CUDA file, it's created a build script. And we could have a look at that build script if we wanted to.

[41:04] And there it is. So none of this matters too much, it's just nice to know that PyTorch is doing all this stuff for us. And we don't have to worry about it. So that's pretty cool. So in order to pass a tensor to this, we're going to be checking that it's contiguous and on CUDA. So we better make sure it is. So we're going to create an imageC variable, which is the image made contiguous and put on through the CUDA device. Now we can actually run this on the full sized image, not on the tiny little minimized image we created before. This has got much more pixels, it's got 1.7 million pixels, whereas before we had I think it was 35,000, 34,000. And it's gone down from one and a half seconds to one millisecond. So that is amazing. So it's dramatically faster,

[42:07] both because it's now running in compiled code and because it's running on the GPU. The step of putting the data onto the GPU is not part of what we timed. And that's probably fair enough because normally you do that once and then you run a whole lot of CUDA things on it. We have though included the step of moving it off the GPU and putting it onto the CPU as part of what we're timing. And one key reason for that is that if we didn't do that, it can actually run our Python code at the same time that the CUDA code is still running. And so the amount of time shown could be dramatically less because it hasn't finished synchronizing. So by adding this, it forces it to complete the CUDA run and to put the data back onto the CPU. That kind of synchronization you can also trigger by printing a value from it or you can synchronize it manually. So after we've done that and we can

[43:13] have a look and we should get exactly the same grayscale puppy. Okay. So we have successfully created our first real working code from Python CUDA kernel. This approach of writing it in Python and then converting it to CUDA is not particularly common. But I'm not just doing it as an educational exercise. That's how I like to write my CUDA kernels, at least as much of it as I can, because it's much easier to debug in Python. It's much easier to see exactly what's going on. And so I don't have to worry about compiling. It takes about 45 or 50 seconds to compile even our simple

[44:13] example here. I can just run it straight away. And once it's working to convert that into C, as I mentioned, you know, chat GPT can do most of it for us. So I think this is actually a fantastically good way of writing CUDA kernels even as you start to get somewhat familiar with them. Because it lets you debug and develop much more quickly. A lot of people avoid writing CUDA just because that process is so painful. And so here's a way that we can make that process less painful. So let's do it again. And this time we're going to do it to implement something very important, which is matrix multiplication. So matrix multiplication, as you probably know, is fundamentally critical for deep learning. It's like the most basic linear algebra operation we have. And the way it works is that you have a input matrix M and a second input matrix N. And

[45:23] we go through every row of M. So we go through every row of M until we get to here we are up to this one and every column of N. And here we are up to this one. And then we take the dot product at each point of that row with that column. And this here is the dot product of those two things. And that is what matrix multiplication is. So it's a very simple operation conceptually. And it's one that we do many, many, many times in deep learning. And basically every deep learning, every neural network has this as its most fundamental operation. Of course, we don't actually need to implement matrix multiplication from scratch because it's done for us in libraries. But we will often do things where we have to kind of fuse in some kind of matrix multiplication like pieces.

[46:24] And so, you know, and of course, it's also just a good exercise. So let's take a look at how to do matrix multiplication first of all in pure Python. So in the, actually in the fast AI course that I mentioned, there's a very complete in-depth dive into matrix multiplication in part two, lesson 11, where we spend like an hour or two talking about nothing but matrix multiplication. detail here.

[46:56] But what we do do in that is we use the MNIST dataset to do this. And so we're going to do the same thing here. We're going to grab the MNIST dataset of handwritten digits. And they are 28 by 28 digits. They look like this. 28 by 28 is 784. So to do a, you know, to basically do a single layer of a neural net or without the activation function, we would do a matrix multiplication of the image flattened out by a weight matrix with 784 rows and however many columns we like. And I'm going to need if we're going to go straight to the output. So this would be a linear function, a linear model. We'd have 10 layers, one for each digit. So here's this is our weights. We're not actually going to do any learning here. This is just not any deep learning or logistic regression learning. This is just for an example. OK, so we've got our weights and we've got our input

[48:01] data. X train and X valid. And so we're going to start off by implementing this in Python. Now, again, Python is really slow, so let's make this smaller. So matrix one will just be five rows. Matrix two will be all the weights. So that's going to be a five by 784 matrix multiplied by a 784 by 10 matrix. Now these two have to match. Of course they have to match because otherwise this dot product won't work. Those two are going to have to match the row by the column. OK, so let's pull that out into A rows, A columns, B rows, B columns. And obviously A columns and B rows are the things that have to match. And then the output will be A rows by B columns.

[48:53] So five by 10. So let's create an output full of zeros with rows by columns in it. And so now we can go ahead and go through every row of A, every column of B, and do the dot product, which involves going through every item in the innermost dimension, or 784 of them, multiplying together the equivalent things from M1 and M2 and summing them up into the output tensor that we created. So that's going to give us, as we said, a five by 10. Five by 10 output. And here it is. OK, so this is how I always create things in Python. I basically almost never have to debug. I almost never have like errors, unexpected errors in my code, because I've written every single line one

[49:57] step at a time in Python. I've checked them all as they go. And then I copy all the cells and merge them together, stick a function header on like so. And so here is matmul. So this is exactly the code we've already seen. And we can call it. And we'll see that for 39,200 innermost operations, we took us about a second. So that's pretty slow. OK, so now that we've done that, you might not be surprised to hear that we now need to do the innermost loop as a kernel call in such a way that it is can be run in parallel. Now, in this case, the innermost loop is not this line of code. It's actually this line of code. I mean, we can choose to be whatever we want it to be. But in this case, this is how we're going to do it. We're going to say for every pixel, we're not going to be every

[50:58] pixel, for every cell in the output tensor like this one here is going to be one CUDA thread. So one CUDA thread is going to do the dot product. So this is the bit that does the dot product. So that'll be our kernel. So we can write that matmul block kernel is going to contain that. OK, so that's exactly the same thing that we just copied from above. And so now we're going to need something to run this kernel. And you might not be surprised to hear that in CUDA, we are going to call this using blocks and threads. But something that's rather handy in CUDA is that the blocks and threads don't have to be just a 1D vector. They can be a 2D or even 3D tensor. So in this case,

[52:01] you can see we've got one, two, it's a little hard to see exactly where they stop, two, three, four blocks. And so then for each block, and that's kind of in one dimension, and then there's also one, two, three, four, five blocks in the other dimension. And so each of these blocks has an index. So this one here is going to be zero, zero, a little bit hard to see. This one here is going to be one, three, and so forth. And this one over here is going to be three, four. So rather than

[53:02] just having a integer block index, we're going to have a tuple block index. And then within a block, there's going to be, to pick, let's say, this exact spot here, didn't do that very well, there's going to be a thread index. And again, the thread index won't be a single index into a vector. It'll be two elements. So in this case, it'll be 0, 1, 2, 3, 4, 5, 6 rows down. And 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, is that 11, 12? I can't count. 12 maybe across. So this here is actually going to be defined by two things. One is by the block. And so the block is 3, 4. And the thread is 6, 12. So

[54:18] that's how CUDA lets us index into two-dimensional grids using blocks and threads. We don't have to. It's just a convenience if we want to. And in fact, we can use up to three dimensions. So to create our kernel runner, now rather than just having two nested loops for blocks and threads, we're going to have to have two lots of two nested loops for both of our x and y blocks and threads, or our rows and columns blocks and threads. So it ends up looking a bit messy because we now have four nested for loops. So we'll go through our blocks on the y-axis and then through our blocks

[55:21] on the x-axis and then through our threads on the y-axis and then through our threads on the x-axis. And so what that means is that for you can think of this Cartesian product as being for each block, for each thread. Now to get the dot y and the dot x, we'll use this handy little Python standard library thing called simple namespace. I use that so much I just give it an NS name because I use namespaces all the time in my quick and dirty code. So we go through all those four. We then call our kernel and we pass in an object containing the y and x coordinates. And that's going to be our block. And we also pass in our thread, which is an object with the y and x coordinates of our thread. And it's going to eventually do all possible blocks and all possible threads numbers for each of those blocks. And we also need to tell it how big is each block,

[56:27] how high and how wide. And so that's what this is. This is going to be a simple namespace, an object with an x and y, as you can see. So we need to know how big they are. Just like earlier on, we had to know the block dimension. That's why we passed in threads. So remember this is all pure PyTorch. We're not actually calling any out to any CUDA. We're not calling out to any libraries other than just a tiny bit of PyTorch for the indexing and tensor creation. So you can run all of this by hand. Make sure you understand. You can put it in the debugger. You can step through it. And so it's going to call our function. So here's our matrix multiplication function. As we said, it's a kernel that contains the dot product that we wrote earlier. So now the guard is going to have to check that the row number we're up to is not taller than we have and the column number we're up to is not wider than we have. And we also need to know what row number we're

[57:27] up to. And this is exactly the same. Actually, I should say the column is exactly the same as we've seen before. And in fact, you might remember in the CUDA we had block IDX.x. This is why, right? Because in CUDA, it's always gives you these three dimensional dim three structures. So you have to put this dot x. So we can find out the column this way. And then we can find out the row by seeing how many blocks have we gone through, how big is each block in the y-axis, and how many threads have we gone through in the y-axis. So what row number are we up to? What column number are we up to? Is that inside the bounds of our tensor? If not, then just stop and then otherwise do our dot product and put it into our output tensor. So that's all pure Python. And so now we can call it by getting the height and width of our first input, the height and width of

[58:35] our second input. And so then k and k2, the inner dimensions ought to match. We can then create our output. And so now threads per block is not just the number 256, but it's a pair of numbers. It's an x and a y. And we've selected two numbers that multiply together to create 256. So again, this is a reasonable choice if you've got two dimensional inputs to spread it out nicely. One thing to be aware of here is that your threads per block can't be bigger than 1024. So we're using 256, which is safe. And notice that you have to multiply these together. 16 times 16 is going to be the number of threads per block. So these are safe numbers to use. You're not going to run out of blocks though.

[59:30] 2 to the 31 is the number of maximum blocks for dimension 0 and then 2 to the 16 for dimensions 1 and 2. I think it's actually minus 1, but don't worry about that. So don't have too many threads, but you can have lots of blocks. But of course, each symmetric model processor is going to run all of these on the same device and they're also going to have access to shared memory. So that's why you use a few threads per block. So our blocks, the x, we're going to use the ceiling division. The y, we're going to use the same ceiling division. So if any of this is unfamiliar, go back to our earlier example because the code's all copied from there. And now we can call our 2D block kernel runner passing in the kernel. The number of blocks, the number of threads per block, our input matrices flattened out, our output matrix flattened out, and the dimensions that it needs because they get all used here and return the result. And so if we call that mapMole with a

[1:00:35] 2D block and we can check that they are close to what we got in our original manual loops. And of course they are because it's running the same code. So now that we've done that, we can do the CUDA version. Now the CUDA version is going to be so much faster, we do not need to use this slimmed down matrix anymore. We can use the whole thing. So to check that it's correct, I want a fast CPU based approach that I can compare to. So previously it took about a second to do 39,000 elements. So I'm not going to explain how this works, but I'm going to use a broadcasting approach to get a fast CPU based approach. If you check the fast AI course, we teach you how to do this broadcasting approach. But it's a pure Python approach, which manages to do it all in a single loop rather than three nested loops. It gives the same answer for the cut down tensors.

[1:01:47] But much faster, only four milliseconds. So it's fast enough that we can now run it on the whole input matrices. And it takes about 1.3 seconds. And so this broadcast optimized version, as you can see, it's much faster. And now we've got 392 million additions going on in the middle of our three loops, effectively three loops, but we're broadcasting them. So this is much faster.

[1:02:19] But the reason I'm really doing this is so that we can store this result to compare to. So that makes sure that our CUDA version is correct. Okay, so how do we convert this to CUDA? You might not be surprised to hear that what I did was I grabbed this function and I passed it over to ChatGPT and said, please rewrite this in C. And it gave me something basically that I could use first time. And here it is. This time I don't have unsigned cast star, I have float star. Other than that, this looks almost exactly like the Python we had with exactly the same changes we saw before. We've now got the .y and .x versions. Once again, we've got DunderGlobal, which says, please run this on the GPU when we call it from the CPU. So the kernel, I don't think there's anything to talk about there. And then the thing that calls the kernel, matmul, is going to be

[1:03:21] passed in two tensors. We're going to check that they're both contiguous and check that they are on the CUDA device. We'll grab the height and width of the first and second tensors. We're going to grab the inner dimension. We'll make sure that the inner dimensions of the two matrices match just like before. And this is how you do an assertion in PyTorch CUDA code. You call torch check, pass in the thing to check, pass in the message to pop up if there's a problem. These are a really good thing to spread around all through your CUDA code to make sure that everything is as you thought it was going to be. Just like before, we create an output. So now when we create a number of threads, we don't say threads is 256. We instead say, this is a special thing provided by CUDA for us, dim3.

[1:04:17] So this is basically a tuple with three elements. So we're going to create a dim3 called tpb. It's going to be 16 by 16. Now I said it has three elements. Where's the third one? That's okay. It just treats the third one as being one. So we can ignore it. So that's the number of threads per block. And then how many blocks will there be? Well, in the X dimension, it'll be W divided by X, ceiling division. In the Y dimension, it will be H divided by Y, ceiling division. And so that's the number of blocks we have. So just like before, we call our kernel just by calling it like a normal function. But then we add this weird triple angle bracket thing telling it how many blocks and how many threads. So these aren't ints anymore. These are now dim3 structures. And that's what we use,

[1:05:18] these dim3 structures. And in fact, even before, what actually happened behind the scenes when we did the grayscale thing is even though we passed in 256, for instance, we actually ended up with a dim3 structure and just in which case the index one and two or the dot X and dot Y and dot Z values would have set to one automatically. So we've actually already used a dim3 structure without quite realizing it. And then just like before, pass in all of the tensors we want, casting them to pointers, maybe they're not just casting, converting them to pointers through some particular data type and passing in any other information that our function will need, that kernel will need. Okay, so then we call load CUDA again, that'll compile this into a module, make

[1:06:21] sure that they're both contiguous and on the CUDA device. And then after we call module dot mapmul, passing those in, putting on the CPU and checking that they're all close, and it says yes, they are. This is now running not on just the first five rows, but on the entire MNIST data set. And on the entire MNIST data set, using a optimized CPU approach, it took 1.3 seconds. Using CUDA, it takes 6 milliseconds. So that is quite a big improvement. Cool. The other thing I will mention, of course, is PyTorch can do a matrix multiplication for us just by using at. How long does, and obviously gives the same answer, how long does that take to run? That takes 2 milliseconds. So three times faster. And in many situations, it'll be much more than three times

[1:07:26] faster. So why are we still pretty slow compared to PyTorch? I mean, this isn't bad to do 392 million of these calculations in 6 milliseconds. But if PyTorch can do it so much faster, what are they doing? Well, the trick is that they are taking advantage in particular of this shared memory. So shared memory is a small memory space that is shared amongst the threads in a block, and it is much faster than global memory. In our matrix multiplication, when we have one of these blocks, and so it's going to do one block at a time all in the same SM, it's going to be reusing the same 16 by 16 block. It's going to be using the same 16 rows and columns again and again and again, each time with access to the same shared memory. So you can see how you could really potentially cache the information, a lot of the information you need, and reuse it rather than

[1:08:28] going back to the slower memory again and again. So this is an example of the kinds of things that you could optimize potentially once you get to that point. The only other thing that I wanted to mention here is that this 2D block idea is totally optional. You can do everything with 1D blocks or with 2D blocks or with 3D blocks and threads. And just to show that, I've actually got an example at the end here which converts RGB to grayscale using the 2D blocks. Because remember earlier when we did this, it was with 1D blocks. It gives exactly the same result. And if we compare the code, so if we compare the code, the version actually that was done with 1D threads and blocks is quite

[1:09:33] a bit shorter than the version that uses 2D threads and blocks. And so in this case, even though we're manipulating pixels, where you might think that using the 2D approach would be neater and more convenient, in this particular case it wasn't really. It's still pretty simple code that we have to deal with the columns and rows.x.y separately. The guards are a little bit more complex. We have to find out what index we're actually up to here. Where else this kernel, it was just much more direct, just two lines of code. And then calling the kernel, again it's a little bit more complex with the threads per block stuff rather than this. The key thing I wanted to point out is that these two pieces of code do exactly the same thing. So don't feel like if you don't want to use a 2D or 3D block thread structure, you don't have to. You can just use a 1D one.

[1:10:32] The 2D stuff is only there if it's convenient for you to use and you want to use it. Don't feel like you have to. So yeah, I think that's basically all the key things that I wanted to show you all today. The main thing I hope you take from this is that even for Python programmers, for data scientists, it's not way outside our comfort zone. We can write these things in Python, we can convert them pretty much automatically, we end up with code that doesn't look, you know, it looks reasonably familiar even though it's now in a different language. We can do everything inside notebooks, we can test everything as we go, we can print things from our kernels. And so, you know, it's hopefully feeling a little bit less beyond our capabilities than we might have previously

[1:11:35] imagined. So I'd say, yeah, you know, go for it. I think it's also like, I think it's increasingly important to be able to write CUDA code nowadays because for things like flash attention or for things like quantization, GPTQ, AWQ, bits and bytes, these are all things you can't write in PyTorch. You know, our models are getting more sophisticated. The kind of assumptions that libraries like PyTorch make about what we want to do, you know, increasingly less and less accurate.

[1:12:12] So we're having to do more and more of this stuff ourselves nowadays in CUDA. And so I think it's a really valuable capability to have. Now, the other thing I mentioned is we did it all in Colab today, but we can also do things on our own machines if you have a GPU or on a cloud machine. And getting set up for this, again, it's much less complicated than you might expect. And in fact, I can show you it's basically like four lines of code or four lines or three or four lines of bash script to get it all set up. It'll run on Windows or under WSL. It'll also run on Linux. Of course, Mac stuff doesn't really work on... CUDA stuff doesn't really work on Macs. They're not on Mac. Actually, I'll put a link to this into the video notes. But for now, I'm just going to jump to a Twitter thread where I wrote this all down to show you all

[1:13:15] the steps. So the way to do it is to use something called Conda. Conda is something that very, very, very few people understand. A lot of people think it's like a replacement for like PIP or poetry or something. It's not. It's better to think of it as a replacement for Docker. You can literally have multiple different versions of Python, multiple different versions of CUDA, multiple different C++ compilation systems all in parallel at the same time on your machine and switch between them. You can only do this with Conda. And everything just works. So you don't have to worry about all the confusing stuff around .run files or Ubuntu packages or anything like that. You can do everything with just Conda. You need to install Conda. I've actually got a script which you just run the script. It's a tiny script, as you see. If you just run the script, it'll automatically figure out which mini Conda you need. It'll automatically figure out what shell you're on,

[1:14:18] and it'll just go ahead and download it and install it for you. OK, so run that script, restart your terminal. Now you've got Conda. Step two is find out what version of CUDA PyTorch wants you to have. So if I click Linux, Conda, CUDA 12.1 is the latest. So then step three is run this shell command, replacing 12.1 with whatever the current version of PyTorch is. It's actually still 12.1 for me at this point. And that will install everything. All the stuff you need to profile, debug, build, etc. All the NVIDIA tools you need, the full suite, will all be installed, and it's coming directly from NVIDIA so you'll have the proper versions. As I said, you can have multiple versions installed at once in different environments. No problem at all. And then finally,

[1:15:18] install PyTorch. And this command here will install PyTorch. For some reason I wrote nightly here. You don't need the nightly. Just remove dash nightly. So this will install the latest version of PyTorch using the NVIDIA CUDA stuff that you just installed. If you've used Conda before and it was really slow, that's because it used to use a different solver which was thousands or tens of thousands of times slower than the modern one. It's just been added and made default in the last couple of months. So nowadays this should all run very fast. And as I said, it'll run under WSL on Windows. It'll run on Ubuntu. It'll run on Fedora. It'll run on Debian. It'll all just work. So that's how I strongly recommend getting yourself set up for local development. You don't need to worry about using Docker. As I said, you can switch between different CUDA versions, different Python versions, different compilers and so forth without having to worry about any of the

[1:16:23] Docker stuff. And it's also efficient enough that if you've got the same libraries and so forth installed in multiple environments, it'll hard link them. So it won't even use additional hard drive space. So it's also very efficient. Great. So that's how you can get started on your own machine or on the cloud or whatever. So hopefully you'll find that helpful as well. All right. Thanks very much for watching. I hope you found this useful and I look forward to hearing about what you create with CUDA. In terms of going to the next steps, check out the other CUDA mode lectures. I will link to them. And I would also recommend trying out some projects of your own. So for example, you could try to implement something like 4-bit quantization or Flash Attention or

[1:17:24] anything like that. Now those are pretty big projects, but you can try to break them up into smaller things that you build up one step at a time. And of course, look at other people's code. So look at the implementation of Flash Attention. Look at the implementation of bits and bytes. Look at the implementation of GPTQ and so forth. The more time you spend reading other people's code, the better. All right. I hope you found this useful and thank you very much for watching.

在 Vidleaf 工作台中打开

搜索转录文本、选择行、复制带时间戳的引文、翻译。

署名

《面向 Python 程序员的 CUDA 入门》作者 Jeremy Howard(https://www.youtube.com/@howardjeremyp),依据 CC BY 4.0 许可(https://creativecommons.org/licenses/by/4.0/)。源视频:https://www.youtube.com/watch?v=nOxKexn3iBo。本页是该视频的文本转录,添加了段落分隔和时间戳;创作者与 Vidleaf 无关联,也不为其背书。Vidleaf 添加了 AI 标点和 AI 生成的摘要;原始措辞仍可在本页查看。

您是创作者或权利持有人吗?请求更正或移除:copyright@vidleaf.app(参见关于这些页面)。

最后更新于