逐字稿 · 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 repo 另有一個 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 核心,因此移除內層迴圈並改寫成 kernel;以 Python 的 run_kernel 模擬可重現完全相同的語意,但沒有平行加速效果,而 CUDA 會把範圍切成大小為 256 的區塊,kernel 執行器是一對巢狀迴圈,其中目前索引等於區塊索引乘以區塊維度再加上執行緒索引,執行緒數固定為 256,並以守衛檢查索引不超過像素數。區塊之所以重要,是因為同一個執行緒區塊內的執行緒共享共享記憶體、可以同步,且在同一串流多處理器上執行。環境設定會安裝建置工具與 WorldLitza,並在 torch.utils.cpp extension 中使用 PyTorch 的 LoadInline,再以名為 LoadCuda 的包裝函式簡化流程,將 CUDA 程式碼字串編譯成 Python 模組;建議做法是把 Python kernel 貼進 ChatGPT,請它轉換成等效的 C,結果基本上相當完美,只是它假設使用浮點數。在 1.7 百萬像素上,執行時間從約一秒半降到一毫秒。接著在 MNIST 資料上以純 Python 實作矩陣乘法,再改寫成 CUDA 風格的 2D kernel,將每個輸出儲存格分配給一個執行緒,每個區塊有 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 的評價與筆記本式做法

  • [0:01] 來自 Answer.AI 的 Jeremy Howard 主講「CUDA 入門」,用來撰寫 NVIDIA GPU 程式,以追求速度與最大彈性。
  • [0:17] CUDA 素有難以入門的評價,但 Howard 表示,只要掌握一些訣竅,其實沒那麼糟。
  • [0:38] 所有工作都在筆記本中完成,而非透過編譯器與終端機,這要歸功於 PyTorch 提供的魔法。

透過 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] 從網址下載一張小狗圖片,並以 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] 每個輸出值大約是 x i(紅色分量)輸入值的 0.29 倍,加上 x i 加 n(綠色分量)的 0.59 倍。
  • [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] CUDA 核心可以用 Python 的單一 for 迴圈來模擬,它不會平行執行,因此不會加快速度,但會產生與 CUDA 完全相同的語意。
  • [16:56] run_kernel 函式接收一個函式、執行次數與引數,每次呼叫該函式時傳入索引、時間與所要求的引數。
  • [17:23] 設定階段取得通道數、高度與寬度,計算像素數量,將其攤平,並建立結果張量。
  • [17:35] 程式碼不直接呼叫迴圈,而是以函式名稱 f、像素數量作為迴圈次數,以及引數 out、x 與 n 來呼叫 run_kernel。

最少的相依性與概念上的等效性

  • [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。

用於在筆記本中從 CUDA 列印輸出的 WorldLitza

  • [27:02] WorldLitza 只用於載入擴充功能的那一行;沒有它,從 CUDA 或 C++ 程式碼列印的任何內容都不會出現在筆記本中。
  • [27:12] 在筆記本中載入 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 就只是 uint8 在 C 中的寫法,而資料型別的拼寫可以用 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++ 列表初始化器,就能建立二維張量,如此一來便不需要在最後加上 dot view。
  • [37:25] 使用 dot view 的做法其實也行得通,講者提到保持一致性大概會更好,不過這就是當時所寫的內容。

使用 input.options() 與 auto 來指定 dtype 和 device

  • [37:36] 傳入 input.options() 可讓輸出使用與輸入張量相同的資料型別及相同的 CUDA 裝置,這是個便利的做法,講者認為 Python 中並沒有這種方式。
  • [37:55] 寫 auto 而非 torch::tensor,可讓編譯器自行推斷型別,這是 C++ 另一項便利的功能。

使用 PyTorch 巨集檢查核心錯誤

  • [38:14] 若核心發生錯誤,你不一定會被告知,因此必須在呼叫核心之後寫上 PyTorch 提供的巨集來檢查錯誤。
  • [38:25] 巨集的細節並不重要;每次呼叫核心後都應呼叫它,以確保運作正常。
  • [38:31] 檢查完畢後,便可回傳你所配置、以指標傳入並填妥的張量。

C++ 原始碼與 CUDA 原始碼並列

  • [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 大部分可以透過 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] 快速 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 執行緒來執行點積,這就成為 matmul 區塊核心。
  • [51:26] 核心主體與上方複製的程式碼完全相同,因此需要一個獨立的機制來執行它。

2D 與 3D 區塊及執行緒索引

  • [51:53] 在 CUDA 中,區塊和執行緒不必是 1D 向量;它們可以是 2D 甚至 3D 張量。
  • [52:38] 每個區塊都有一個元組索引,例如 (0,0)、(1,3) 或 (3,4),而不是單一整數區塊索引。
  • [53:28] 執行緒索引也有兩個元素,分別代表區塊內的行和列,因此位置由區塊和執行緒座標共同定義。
  • [54:32] 使用 2D 網格只是一種便利,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 軸上已遍歷的區塊和執行緒數量求得;如果位置超出邊界則停止,否則將點積結果寫入輸出張量。

用於矩陣乘法的 2D 區塊配置

推導 2D 執行緒與區塊維度

  • [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 以 C 改寫 Python 函式

  • [1:02:35] 講者拿 Python 函式請 ChatGPT 改寫成 C,第一次就得到可用的程式碼。
  • [1:02:48] C 版本使用 float 指標而非 unsigned char 指標,但除此之外與 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 結構,其 dot X、dot Y 與 dot Z 值會自動設為一。

在完整 MNIST 上啟動、編譯與驗證

  • [1:05:49] 張量會轉換為特定資料型別的指標,並連同核心所需的任何其他資訊一起傳入。
  • [1:06:10] load CUDA 會將程式碼編譯成模組,檢查連續性與 CUDA 裝置配置,並呼叫 module dot 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] 所有事情都能在筆記本中完成,邊做邊測試,並從核心中列印東西。
  • [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 安裝完整的效能剖析、除錯與建置工具套件,並確保版本正確。
  • [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 的實作,投入的時間越多越有收穫。

免裝外掛讀取附時間戳記的現有字幕,匯出 TXT、SRT 或 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》是一本非常值得讀的好書,等你完成今天的課程後,應該就能對這本書有個很好的起步。它會更深入地講解一些我們今天會相當快速帶過的主題。沒有這本書也沒關係,但如果你想更深入,我強烈建議你買一本。事實上,你會在這個儲存庫裡看到,本系列的第 2 講其實就是深入探討那本書的第 1 到 3 章。所以,雖然有點令人混淆,你或許會想在這講之後再去看第 2 講、第 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》是一本非常值得讀的好書,等你完成今天的課程後,應該就能對這本書有個很好的起步。它會更深入地講解一些我們今天會相當快速帶過的主題。沒有這本書也沒關係,但如果你想更深入,我強烈建議你買一本。事實上,你會在這個儲存庫裡看到,本系列的第 2 講其實就是深入探討那本書的第 1 到 3 章。所以,雖然有點令人混淆,你或許會想在這講之後再去看第 2 講、第 3 講,以取得我們所談內容的更多細節。好,那我們就進入 notebook 吧。今天我們要做的事情,就是進行一大堆的東西

[2:41],先使用舊版 PyTorch,以確保我們掌握所有概念,接著我們會嘗試把這些東西逐一轉換成 CUDA。所以,為了做到這件事,我們要先匯入一堆東西。其實,我們就在 Colab 裡做這一切吧。所以我們現在在 Colab 裡,你應該確認在 Colab 中把執行環境設為 T4 GPU。這個你可以免費大量使用,而且它很容易就足以執行我們今天做的所有事情。然後,一旦你把它跑起來,我們就可以匯入需要的函式庫,並開始我們的第一個練習。所以第一個練習其實來自本書第 2 章和第 2 章,教的是如何解決這個問題,也就是把 RGB 彩色圖片轉換成灰階圖片。結果發現,這件事建議的公式是取紅色像素的 0.21、綠色像素的 0.72、

[3:44] 0.07 的藍色像素,並把它們加總在一起,這樣就產生了亮度值,也就是我們在這裡看到的結果。這是常見的做法,算是從 RGB 轉到灰階的標準做法。所以我們要來做這件事,我們要寫一個 CUDA 核心來做這件事。所以我們首先需要的是一張圖片,而每當你需要一張圖片時,我建議去找一張小狗的照片。所以我們這裡有一個小狗照片的網址。我們就直接下載它,然後我們可以用 torchvision.io 來載入它。這已經是 Colab 的一部分了。如果你有興趣在自己的機器或雲端伺服器上執行東西,我會在這堂課最後示範如何設定。所以我們來讀取這張圖片,如果我們看一下它的形狀,它顯示是 3 乘 1066 乘 1600。所以我假設你已經知道基礎的

[4:44] 的 PyTorch。如果你不熟悉 PyTorch 的基礎,我有點偏頗,但我強烈推薦我的課程,它正好涵蓋這些內容。你可以到 course.fast.ai,你還可以順便看到一些非常可愛的兔子,而且除了這些非常可愛的兔子之外,它基本上會帶你走過成為現代深度學習有效實踐者所需的一切。

[5:14] 所以如果你想直接進入那些細節,就完成第一部分,但即使你只做前兩三課,那也會給你超過足夠的知識來理解這類程式碼和這類輸出。所以我有一個 sigma,你已經完成了所有這些。所以你會看到這裡我們有一個秩為 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,這裡的 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++ 程式碼印出的任何東西,都不會出現在筆記本裡。所以你總會想在

[27:19] 筆記本裡做 CUDA 相關的事情,這樣你就能用 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 檔案中。我們需要 include 這個標頭檔,以確保能存取 PyTorch tensor 的東西。我們希望能使用 I.O.,也希望能檢查例外狀況。然後我還定義了三個巨集。第一個巨集只是檢查 tensor 是否在 CUDA 上。第二個檢查它在記憶體中是否連續,因為有時候 PyTorch 實際上會把東西拆散到不同的記憶體區塊。然後如果我們試著在這種

[29:29] 攤平的形式中存取它,就行不通。然後我們實際要使用它的方式,check input,就只是檢查這兩件事。所以如果某個東西不在 CUDA 上而且不連續,我們就沒辦法使用它。所以我們總是有這個。然後我們在這裡做的第三件事是定義向上取整除法。向上取整除法就是這個。雖然你也可以用像這樣的不同方式來實作。所以這會做向上取整除法。這就是我們要、這就是我們要呼叫來算出需要多少個 block 的方式。所以這只是,你不必太擔心它的細節。這只是我們要使用的標準設定。好,現在我們需要寫我們的 CUDA kernel。那麼,你要怎麼寫 CUDA kernel?

[30:19] 嗯,我所做的,我也建議你這麼做,就是把你 Python 的 kernel 拿來,貼到 chat GPT,然後說把這個轉換成等效的 C 程式碼,使用相同的名稱、格式等等。在可行的情況下,貼進去,chat GPT 就會幫你做好。除非你對 C 非常熟悉,那就自己寫也沒關係。但這樣一來,既然你已經有 Python 了,何不就这么做呢?我發現它基本上相當完美。雖然它假設這些是 float,但它們其實不是 float。我們必須改幾個資料型別,但基本上我幾乎可以原封不動地使用它。所以特別是,你知道,對於現在像我這樣更像是 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,或者你可以 Google 一下。但這就是你寫 byte 的方式。那個星號實際上,基本上就是你說這是一個陣列的方式。所以這表示 X 是一個 byte 的陣列。它實際上是指標,但如你在這裡所見,指標被 C 當作陣列來處理。所以你其實不必擔心它是指標這件事,對我們來說它就只是表示它是個陣列。但在 C 裡,它唯一知道怎麼處理的陣列種類就是這些一維陣列。這就是為什麼我們總是要把東西攤平。我們無法在這些 CUDA kernel 裡用這種方式直接使用多維張量。所以我們最後會得到這些一維的 C 陣列。對,除此之外,它看起來會完全一樣,事實上,我的意思是,甚至因為我們把 Python 寫得像

[33:32] 那樣,它看起來會一模一樣。這裡的 void 只是表示它不傳回任何東西。然後這裡的 Dunder global 是 CUDA 加入的特殊東西。可以出現三種東西。而這單純是在說,我應該把這個編譯成做什麼?所以你可以放 Dunder device,那表示把它編譯成只能在 GPU 上呼叫。你可以寫 Dunder global,那表示,好,你可以從 CPU 或 GPU 呼叫它,而它會在 GPU 上執行。或者你可以寫 Dunder host,你不一定要寫。那只是表示它是一個在 CPU 端執行的普通 C 或 C++ 程式。所以每當我們想從 CPU 端呼叫某個東西來在 GPU 上執行,這基本上幾乎總是我們在做 kernel 的時候,你就寫 Dunder global。所以在這裡我們有 Dunder global,我們有我們的 kernel,就這樣。所以接著我們需要

[34:36] 用來呼叫該核心的名稱。所以先前要呼叫核心時,我們呼叫了這個區塊核心函式,傳入核心,並傳入區塊與執行緒。而在 CUDA 中傳遞引數時,我們不必使用特殊函式。核心內建了一種奇特的特殊語法,會替我們完成這件事。要使用這種奇特的特殊語法,你就說:好,我要呼叫的核心是哪個函式?然後使用這些奇特的三重角括號。所以三重角括號是 CUDA 對 C++ 語言的特別擴充。它的意思是:這是核心,請在 GPU 上呼叫它。

[35:19] 而在三重角括號之間,你可以傳入若干項目,但至少必須傳入前兩項,也就是多少個區塊、多少個執行緒。所以多少個區塊,就是向上取整除法,像素數除以執行緒數。而多少個執行緒,如我們先前所說,就一律選 256,不必操心。所以這表示把這個函式當作 GPU 核心來呼叫,然後傳入這些引數。我們必須傳入輸入張量、輸出張量,以及像素數。你會看到,對每個張量,我們都必須使用特殊方法 dot data pointer。這會把它轉換成指向該張量的 C 指標。所以這就是為什麼當它抵達我們的核心時,它是 C 指標。你還必須告訴它,你希望把它當作什麼資料型別來處理。這表示把它當作 Untates。所以這就是這個

[36:23] 在這裡是 C++ 範本參數。而這是一個方法。另一件你需要知道的事是,在 C++ 中,dot 表示呼叫物件的方法,否則雙冒號基本上就像在 C 中、在 Python 中呼叫類別的方法。所以你不說 torch dot empty,而是說 torch 雙冒號 empty 來建立我們的輸出。否則,回到我們用 Python 做的時候,我們說的是 torch dot empty。

[36:55] 在 Python 中也是如此。喔,好的。所以在 Python 中,這是對的。我們剛剛建立了一個長度和向量,然後做了 dot view。我們怎麼做其實不太重要。但在這個案例中,我們實際上建立了二維張量,方式是傳入……我們在這裡的大括號中傳入這個東西。這叫做 C++ list initializer。它基本上就是一個包含 height 逗號 width 的小清單。所以這告訴它要建立一個二維矩陣,這就是為什麼我們最後不需要 dot view。我們也可以用 dot view 的方式來做。保持一致性可能比較好。但這是我當時寫的。建立輸出時另一個有趣的地方是,如果你傳入 input 點 options。所以這是我們的輸入張量,它只是說,喔,使用相同的資料型別和相同的裝置,也就是和我們的輸入相同的 CUDA 裝置。這是一個很好、非常方便的方式,我甚至不認為我們在 Python 中有這個,可以說確保這是相同的資料型別、相同的裝置。如果你在這裡寫 auto,這相當方便。你不必指定型別。

[38:01] 這是……我們可以寫 torch 冒號冒號 tensor。但寫 auto 的話,它就只是說自己搞定。這是另一個方便的小 C++ 特性。在我們呼叫 kernel 之後,如果其中有錯誤,我們不一定會被告知。所以要告訴它檢查錯誤,你必須寫這個。這是一個同樣由 PyTorch 提供的巨集。細節不重要。你應該總是在呼叫 kernel 之後呼叫它,以確保它能運作。然後你可以回傳你配置的張量,你把它當作指標傳入,然後你填入了它。好的。現在,除了 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 裡建立東西的一貫方式。我基本上幾乎不需要除錯。我的程式碼幾乎不會出現錯誤、非預期的錯誤,因為我已經把每一行都

[49:57] 在 Python 裡一步一步寫好。我一邊寫一邊檢查每一行。然後我把所有儲存格複製起來合併在一起,像這樣加上函式標頭。這就是 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 讓我們使用區塊和執行緒索引二維網格的方式。我們不一定要這樣做,這只是如果我們想用的話的一種便利。事實上,我們最多可以使用三個維度。所以現在要建立我們的 kernel 執行器,不再只是有兩個巢狀迴圈分別處理區塊和執行緒,我們會有兩組各兩個巢狀迴圈,分別處理我們的 x 和 y、區塊和執行緒,也就是我們的列和欄的區塊和執行緒。所以最後看起來會有點凌亂,因為我們現在有四個巢狀 for 迴圈。所以我們會先沿著 y 軸走過我們的區塊,然後走過我們的區塊

[55:21] 沿著 x 軸,然後沿著 y 軸走過我們的執行緒,再沿著 x 軸走過我們的執行緒。所以這代表的是,你可以把這個笛卡兒積想成是對每個區塊、對每個執行緒。現在要取得 dot y 和 dot x,我們會用這個方便的 Python 標準函式庫小工具,叫做 simple namespace。我太常用它了,所以直接給它 NS 這個名字,因為我在快速草稿程式碼裡總是使用命名空間。所以我們走過這四個,然後呼叫我們的 kernel,並傳入一個包含 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 區塊核心執行器,傳入核心、區塊數、每個區塊的執行緒數、攤平後的輸入矩陣、攤平後的輸出矩陣,以及它所需的維度,因為這些都會在這裡用到,然後回傳結果。所以如果我們用一個

[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 上執行這個。至於核心,我想那裡沒什麼好談的。然後呼叫核心的 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,向上取整除法。這就是我們有的區塊數。所以就跟之前一樣,我們呼叫核心,就像呼叫一般函式一樣。但接著我們加上這個奇怪的三重角括號,告訴它有多少個區塊和多少個執行緒。所以這些不再是 int 了。這些現在是 dim3 結構。而這就是我們使用的,

[1:05:18]這些 dim3 結構。而事實上,甚至更早之前,當我們做灰階那件事時,背後實際發生的情況是,即使我們傳入了 256,舉例來說,我們最後其實得到了一個 dim3 結構,而在那種情況下,索引一和二,或者 dot X、dot Y 和 dot 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 mode 的講座。我會附上連結。我也會建議你試試自己的專案。例如,你可以試著實作像 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 工作台中開啟

搜尋逐字稿、選取行、複製帶時間戳的引文、翻譯。

署名

Jeremy Howard 的《給 Python 程式設計師的 CUDA 入門》(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(參見 關於這些頁面)。

最後更新