文字起こし · CC BY 4.0

PythonプログラマーのためのCUDA入門 — ジェレミー・ハワード

このページのタイトル、字幕、要約、読書メモは保存済みの AI 翻訳です。誤りが含まれる場合があります。タイムスタンプは原文と同じです。原文の字幕を開き、元の動画と照合できます。

Jeremy Howardが、Python開発者向けにCUDAでのNVIDIA GPUプログラミングを紹介し、並列カーネル、C++テンソル統合、デバッグのワークフローを解説します。

ジェレミー・ハワード · 公開日 · 1時間18分 · 英語 · ライセンス:CC BY 4.0 · 出典:YouTubeで視聴

文字起こしの出典:YouTubeの手動字幕。VidleafによるAI句読点付与。元の文言とタイムスタンプのアンカーは保持されています。元の文字起こしは以下でご覧いただけます。

AI生成の要約

Answer.AIのJeremy Howardが「CUDA入門」を発表し、いくつかのコツを知ればCUDAはそれほど悪くないと主張します。作業はPyTorchを使ったノートブックで行われ、CUDAモードのGitHubリポジトリにあるColab版はGPUなしで無料で実行できますが、ランタイムはT4 GPUに設定する必要があります。事前の講義は不要で、例は「Programming Massively Parallel Processes」の一部に従います。セッションではまず古いPyTorchを多用してアイデアを確立し、その後CUDAに変換します。最初は第2章のRGBからグレースケールへのタスクで、輝度式は赤0.21、緑0.72、青0.07を使用します。ピクセルをベクトルに平坦化し、赤をi、緑をiプラスn、青をiプラス2nでインデックスすると信じられないほど遅く、ほぼ二秒かかります。CUDAが必要なのは、RTX 3090が82個のSMを各128個のCUDAコアで搭載しているためで、内側のループを削除してカーネルとして記述します。Pythonのrun_kernelシミュレーションは並列速度向上なしで同一のセマンティクスを再現し、CUDAは範囲を256のブロックに分割します。カーネルランナーはネストされたループのペアで、現在のインデックスはブロックインデックスにブロック次元を掛けてスレッドインデックスを足したもので、スレッド数は常に256で、ガードがインデックスがピクセル数を超えないことを確認します。ブロックが重要なのは、スレッドブロック内のスレッドが共有メモリを共有し、同期でき、同じストリーミングマルチプロセッサ上で実行されるためです。セットアップではビルドツールとWorldLitzaをインストールし、torch.utils.cpp拡張でPyTorchのLoadInlineを使用します。これはLoadCudaというラッパーで合理化され、CUDAコード文字列をPythonモジュールにコンパイルします。推奨されるアプローチは、PythonカーネルをChatGPTに貼り付けて同等のCに変換するよう依頼することです。これは基本的にほぼ完璧でしたが、浮動小数点数を想定していました。1.7百万ピクセルで、実行時間は約一秒半から一ミリ秒に短縮されました。次に行列乗算がMNISTデータ上で純粋なPythonで実装され、その後CUDAスタイルの2次元カーネルとして各出力セルを一つのスレッドに割り当て、ブロックあたり16×16スレッドとします。MNISTデータセット全体でCUDAは6ミリ秒かかり、最適化されたCPUアプローチの1.3秒に対して、PyTorchのmatmulは2ミリ秒で、特に共有メモリを使用することで高速です。講演者はPythonプログラマーとデータサイエンティストにCUDAを試すよう促し、ノートブックで実行でき、フラッシュアテンション、量子化、GPTQ、AWQ、bits and bytesなどでますます重要になっていると指摘します。第二部ではCondaでCUDA環境を設定する方法を説明し、Dockerの代替として理解する方がPIPやpoetryの代替よりも適切だと位置づけます。Condaは複数のPython、CUDA、C++コンパイルシステムのバージョンを並行して実行し、切り替えることができ、混乱を招く.runファイルやUbuntuパッケージを避けられます。小さなインストールスクリプトが必要なMiniCondaとシェルを検出し、ダウンロードしてインストールし、その後ターミナルを再起動します。次にPyTorchが必要とするCUDAバージョンを確認し、そのバージョンを代入したシェルコマンドを実行してNVIDIAのプロファイリング、デバッグ、ビルドツールスイートをインストールし、-nightlyフラグを削除してPyTorchをインストールします。Condaは古いソルバーのため遅かったですが、現代のデフォルトソルバーでは非常に高速に動作するはずです。セットアップはWindows上のWSLとUbuntu、Fedora、Debianで実行されますが、CUDAはMacでは動作しません。

文字起こしから生成されました。リンクされた箇所は元の動画と照合してください。

タイムスタンプ付きの章の要約

CUDAを始めよう

CUDAの評判とノートブックベースのアプローチ

  • [0:01] Answer.AIのJeremy Howardが、NVIDIA GPUを高速かつ最大限の柔軟性でプログラムするための「CUDAを始めよう」を発表します。
  • [0:17] CUDAは始めるのが難しいという評判がありますが、Howardによれば、いくつかのコツを知っていれば実はそれほど大変ではありません。
  • [0:38] コンパイラやターミナルではなく、PyTorchが提供する魔法のおかげで、すべての作業はノートブックで行われます。

CUDA modeリポジトリとColabで一緒に進める

  • [0:55] Howardは、自分のコンピュータで一緒に進めることを強く勧めています。
  • [1:03] GitHubのCUDA modeオーガニゼーションでは、Lecture 2リポジトリにLecture 3フォルダが含まれています。これはCUDA modeシリーズのLecture 3であり、一緒に進めるのに以前の講義は必要ありません。
  • [1:25] readmeのLecture 3セクションにはColab版へのリンクがあり、GPUがなくても無料で実行できます。

併読書と講義の順序

  • [1:39] 例は書籍『Programming Massively Parallel Processes』の一部に沿っており、Howardはより深く学ぶためにこの本を勧めています。
  • [1:57] 今日のレッスンを終えれば、その内容をより詳しく扱うこの本に素晴らしいスタートを切れるはずです。
  • [2:16] Lecture 2は本の第1章から第3章までの深掘りだったので、より詳しく知りたい場合はこのLecture 3の後にLecture 2を行うと混乱するかもしれません。

PyTorchからCUDAへ:セットアップと最初の演習

ワークフロー:まずPyTorch、次にCUDAへの変換

  • [2:35] セッションは、アイデアを確立するために従来のPyTorchを徹底的に使い、その後これらの各項目をCUDAに変換することを試みます。

T4 GPUでのColabセットアップ

  • [2:56] 作業はColabで行われ、ランタイムはT4 GPUに設定する必要があります。これは無料で多用でき、今日扱うすべてを実行するのに十分な性能です。
  • [3:18] ランタイムが起動したら、必要なライブラリをインポートして最初の演習を始められます。

第2章の最初の演習

  • [3:23] 最初の演習は本の第2章から来ており、進め方を教えてくれます。

CUDAカーネルによるRGBからグレースケールへの変換

輝度の公式と画像の読み込み

  • [3:31] このタスクは、推奨される輝度の公式を用いてRGBカラー画像をグレースケールに変換するものです。赤が0.21、緑が0.72、青が0.07で、それらを合計します。
  • [3:55] この標準的なRGBからグレースケールへの手法は、CUDAカーネルとして実装されます。
  • [4:07] 子犬の画像をURLからダウンロードし、すでにColabに含まれているtorchvision.ioで読み込みます。
  • [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 ですが、さらに多くの CUDA コアを持つ GPU も存在します。

内側のループをカーネルとして抽出する

  • [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テンソルへのアクセス、入出力の使用、例外チェックのためのヘッダーも含まれます。
  • [29:08] 三つのマクロが定義されています。一つはテンソルがCUDA上にあることを確認し、一つはメモリ上で連続していることを確認し、check inputは両方を確認します。CUDA上にない、または連続していないテンソルはフラット化された形では使えないためです。
  • [29:45] 切り上げ除算が定義され、別の実装も示されており、必要なブロック数を計算するために呼び出されます。

PythonからCUDAカーネルを書いて起動する

PythonカーネルをChatGPTでCに変換する

  • [30:19] 推奨される方法は、PythonカーネルをChatGPTに貼り付け、可能な限り同じ名前と書式を使って等価なCコードに変換するよう依頼することです。
  • [30:42] Cに慣れているなら自分でCを書いても構いませんが、既存のPythonを再利用すればゼロから始めずに済みます。
  • [30:48] 変換はほぼ完璧でしたが、値が実際にはそうでないのにfloatと仮定していたため、いくつかのデータ型を変更する必要がありました。
  • [31:09] 今では主にPythonプログラマーという人にとって、これは必要なコードの95%を書くのに良い方法です。

PythonとCの構文の違い

  • [31:18] 先ほどの図とは異なり、組み込み変数は blockIdx.x、blockDim.x、threadIdx.x として書かれているので、.x を付ける必要があります。
  • [31:37] 二つのコードはほぼ同じに見えますが、変更点はデータ型の追加、セミコロン、波括弧の追加、そしてコロンの削除です。
  • [32:02] この種の計算負荷の高い作業では、C はそれほど変わらないので、C の経験が少なくても大きな問題ではありません。
  • [32:18] unsigned char は C で uint8 を書く方法にすぎず、データ型の綴りは ChatGPT や Google で確認できます。

ポインタ、配列、カーネル修飾子

  • [32:37] アスタリスクは基本的に変数が配列であることを示します。実際にはポインタを意味しますが、C はポインタを配列として扱うので、配列と考えることができます。
  • [33:05] C はここでは一次元配列しか扱えないため、テンソルは常に平坦化する必要があり、多次元テンソルはこれらの CUDA カーネルで直接使うことはできません。
  • [33:32] void は関数が何も返さないことを意味し、__global__ はコードをどのようにコンパイルするかを示す CUDA 独自の追加です。
  • [33:47] __device__ は GPU 上でのみ呼び出せるようにコンパイルし、__global__ は CPU または GPU から呼び出せて GPU 上で実行されることを意味し、__host__ は CPU 側で実行される通常の C または C++ プログラムを意味します。
  • [34:15] CPU 側から呼び出して GPU 上で実行するもの、つまりカーネルのほぼすべての場合には、__global__ と書きます。

三つの山括弧でカーネルを起動する

  • [34:36] CUDA では先ほどのブロックカーネル関数のような特別な関数は必要なく、カーネルに組み込まれた特別な構文がその役割を果たします。
  • [35:01] 三つの山括弧は C++ への CUDA 独自の拡張で、これが GPU 上で呼び出されるカーネルであることを意味します。
  • [35:19] 少なくとも最初の二つの値は三つの山括弧の間に渡す必要があります。ブロック数はピクセル数をスレッド数で切り上げ除算して計算し、スレッド数は常に 256 に設定します。
  • [35:45] 入力テンソル、出力テンソル、ピクセル数が引数として渡され、各テンソルは特別な .data_ptr() メソッドを使って C ポインタに変換されます。

データ型と C++ メソッド構文

  • [36:13] また、ポインタをどのデータ型として扱うかを伝える必要があり、uint8 として扱うことを示す C++ テンプレートパラメータを使います。
  • [36:31] C++ ではドットはオブジェクトのメソッド呼び出しを意味し、二重コロンは基本的に Python でクラスのメソッドを呼び出すようなものなので、出力を作成するには torch.empty ではなく torch::empty と書きます。

PyTorch C++ 拡張: テンソル作成とカーネルエラーチェック

C++ のリスト初期化子で 2 次元テンソルを作成する

  • [37:04] 高さと幅を含むC++のリスト初期化子を波括弧で渡すことで二次元テンソルを作成でき、末尾にドットビューを付ける必要がなくなります。
  • [37:25] ドットビューを使う方法でも動作しますし、一貫性を保つ方がよいだろうと話者は述べていますが、当時はこのように書かれていました。

input.options()とautoを使ってdtypeとdeviceを指定する

  • [37:36] input.options()を渡すと、出力は入力テンソルと同じデータ型と同じCUDAデバイスを使うようになり、話者はPythonには存在しない便利な方法だと考えています。
  • [37:55] torch::tensorの代わりにautoと書くとコンパイラが型を推論してくれます。これも便利なC++の機能です。

PyTorchのマクロでカーネルのエラーをチェックする

  • [38:14] カーネルにエラーがあっても必ずしも通知されるわけではないため、エラーをチェックするためにカーネル呼び出しの後にPyTorchが提供するマクロを書く必要があります。
  • [38:25] マクロの詳細は重要ではなく、正しく動作することを確認するためにカーネル呼び出しの後には常に呼び出すべきです。
  • [38:31] チェックの後、確保してポインタとして渡し、値を埋めたテンソルを返すことができます。

CUDAソースと並ぶC++ソース

  • [38:40] CUDAソースに加えて、C++ソースも必要です。

PyTorchでCUDA拡張をコンパイルする

Pythonに公開する関数を宣言する

  • [38:52] 外部、この場合はPythonに公開する関数の詳細のリストが、実質的にヘッダーの役割を果たします。
  • [39:06] 関数定義から行全体をコピーして貼り付け、末尾にセミコロンを追加すればよいです。
  • [39:20] load CUDA関数は、CUDAソースコード、C++ソースコード、そしてPythonで利用可能にする関数名のリストを渡して呼び出されます。
  • [39:31] 渡される関数はRGBからグレースケールへの変換関数一つだけで、必要なのはそれだけです。

自動ビルドとモジュールの読み込み

  • [39:38] この処理はバックグラウンドで自動的にコンパイルし、main.cppを作成してmain.oにコンパイルした後、すべてをリンクして一つのモジュールにします。
  • [40:05] 返されたモジュールはmoduleという変数に格納され、コンパイルが終わると読み込まれます。
  • [40:18] 通常の自動生成されたPythonの内容に加えて、モジュールにはRGBからグレースケールへの変換関数が含まれており、CUDA関数をPythonから利用できるようにします。
  • [40:37] ビルド場所にはmain.cpp、コンパイル済みのmain.o、ロード可能なライブラリ、CUDAファイル、ビルドスクリプトがあり、すべてPyTorchによって処理されます。

入力テンソルの準備

  • [41:17] テンソルを関数に渡すには、連続していることとCUDA上にあることを確認する必要があります。
  • [41:24] imageC変数が、連続化されてCUDAデバイス上に配置された画像として作成され、関数がフルサイズの画像上で実行できるようになります。

Python CUDAカーネルの性能とワークフロー

最小化画像と比較した解像度と速度の向上

  • [41:41] 新しい画像は1.7百万ピクセルで、以前はおよそ34,000–35,000でした。
  • [41:57] 実行時間は約一・五秒から一ミリ秒に短縮され、コードがコンパイルされてGPU上で実行されるため劇的に高速になりました。

計測に含まれるものと含まれないもの

  • [42:16] GPUへのデータ移動は計測されていません。通常は一度だけ行ってから多くのCUDA演算を実行するため、これはおそらく妥当です。
  • [42:29] GPUからCPUへデータを戻す処理は計測に含まれています。
  • [42:36] この手順がなければ、CUDAコードがまだ実行中でもPythonコードが実行できてしまい、同期が完了していないため表示される時間が劇的に短くなります。
  • [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 風2次元カーネル実行

ドット積をセルごとのカーネルにする

  • [50:54] 出力テンソルの各セルは、内積を実行する一つのCUDAスレッドに割り当てられ、これがmatmulブロックカーネルとなります。
  • [51:26] カーネル本体は上記からコピーしたまったく同じコードなので、それを実行するには別の仕組みが必要です。

2次元および3次元のブロックとスレッドのインデックス指定

  • [51:53] CUDAでは、ブロックとスレッドは1次元ベクトルである必要はなく、2次元あるいは3次元テンソルにすることもできます。
  • [52:38] 各ブロックは単一の整数のブロックインデックスではなく、(0,0)、(1,3)、(3,4)のようなタプルインデックスを持ちます。
  • [53:28] スレッドインデックスも二つの要素を持ち、ブロック内の行と列を与えるため、位置はブロックとスレッドの両方の座標によって定義されます。
  • [54:32] 2次元グリッドの使用は単なる利便性であり、CUDAは最大三つの次元を許容します。

カーネルランナー内の四つのネストされたループ

  • [54:41] カーネルランナーは二つのネストされたループを四つに置き換えます。すなわち、y方向のブロック、x方向のブロック、y方向のスレッド、x方向のスレッドです。
  • [55:27] この直積は、各ブロックについて、各スレッドについてという意味であり、単純な名前空間オブジェクトがy座標とx座標を提供します。
  • [56:13] カーネルはブロックオブジェクトとスレッドオブジェクトを伴って呼び出され、最終的にすべての可能なブロックと各ブロック内のすべてのスレッドをカバーします。
  • [56:27] ランナーには各ブロックの高さと幅も伝える必要があり、xとyを持つ単純な名前空間として渡されます。

純粋なPyTorch実行と境界ガード

  • [56:49] すべては純粋なPyTorchであり、インデックス指定とテンソル作成のための少しのPyTorch以外にCUDAや他のライブラリへの呼び出しはないため、デバッガでステップ実行できます。
  • [57:16] ガードは、現在の行がテンソルの高さを超えておらず、現在の列が幅を超えていないことを確認します。
  • [57:33] 列は以前と同じ方法で計算され、これがCUDAが三次元構造の一部としてblockIdx.xを使用する理由です。
  • [57:55] 行はy軸でどれだけのブロックとスレッドが通過したかから求められ、位置が範囲外なら停止し、そうでなければ出力テンソルへの内積を実行します。

行列乗算のための2次元ブロック構成

2次元のスレッドとブロックの次元の導出

  • [58:27] カーネルは両方の入力行列の高さと幅を使用し、内側の次元kとk2は一致する必要があります。
  • [58:41] ブロックあたりのスレッド数はxとyの値のペアになり、それらが掛け合わされて256になるように選ばれ、二次元入力をうまく分散させます。
  • [59:05] ブロックあたりのスレッド数は1024を超えることはできないため、256は安全であり、ここでは16掛ける16がブロックあたりのスレッド数になります。

ブロック制限と共有メモリの根拠

  • [59:30] ブロックの最大数は、次元0では2から31、次元1と2では2から16で、場合によっては1を引いた数になります。
  • [59:43] 各対称型マルチプロセッサは同じデバイス上のすべてのブロックを実行し、共有メモリへのアクセスを共有するため、ブロックあたりのスレッド数は少なくなります。

2次元カーネルの起動と結果の検証

  • [59:53] xとyのブロック数は、以前の例からコピーしたコードを使って切り上げ除算で計算されます。
  • [1:00:11] 2次元ブロックカーネルランナーは、カーネル、ブロック数、ブロックあたりのスレッド数、平坦化された入力行列、平坦化された出力行列、および必要な次元を指定して呼び出され、結果を返します。
  • [1:00:35] 2次元ブロックでmapMoleを呼び出すと、同じコードを実行するため、元の手動ループと近い結果が得られます。

CUDA行列乗算とCPUベースラインの比較

CUDA版は完全な行列を使用

  • [1:00:51] CUDA版ははるかに高速になると予想されるため、縮小した行列は不要になり、行列全体を使用できます。

ブロードキャストベースのCPUリファレンス

  • [1:01:08] 以前の方法では39,000個の要素に約一秒かかったため、正しさを確認するには高速なCPUベースのアプローチが必要です。
  • [1:01:17] 高速なCPUアプローチでは、高速AIコースで教えられたブロードキャストを使用し、三重のネストされたループを単一の純粋なPythonループに置き換えます。
  • [1:01:34] ブロードキャストアプローチは、縮小したテンソルに対して同じ答えを出しますが、わずか四ミリ秒で実行されます。

完全な入力行列での実行

  • [1:01:47] 十分に高速であるため、ブロードキャストアプローチは入力行列全体で実行でき、約1.3秒かかります。
  • [1:02:06] ブロードキャスト最適化版は、実質的に三つのループの中央で392百万回の加算を実行しますが、ブロードキャストを使用しています。
  • [1:02:19] このCPUアプローチの主な理由は、比較用のリファレンスとして結果を保存することです。

Pythonのmatmul関数をCUDAに変換

ChatGPTを使ってPython関数をCで書き直す

  • [1:02:35] 話者はPython関数をChatGPTに渡してCで書き直すよう依頼し、最初の試行で使えるコードを得ました。
  • [1:02:48] C版はunsigned charポインタの代わりにfloatポインタを使用しますが、それ以外は以前と同じ変更を加えたPythonコードをほぼ忠実に反映しています。

カーネル起動の設定とアサーション

  • [1:03:02] コードは .y と .x アクセサを使用し、CPU から呼び出されたときにカーネルが GPU 上で実行されるべきことを示す DunderGlobal アノテーションを使用しています。
  • [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] カーネルは通常の関数のように呼び出されますが、三つの山括弧でブロックとスレッドを指定し、それらは今や int ではなく 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] at を介した PyTorch の行列乗算は同じ答えを出し、2 ミリ秒かかり、三倍高速であり、多くの状況では三倍よりもはるかに高速になります。

PyTorch の高速化の秘訣としての共有メモリ

  • [1:07:40] PyTorch が特に高速なのは、ブロック内のスレッド間で共有される小さなメモリ空間である共有メモリを活用しているためで、これはグローバルメモリよりもはるかに高速です。
  • [1:08:03] 行列乗算では、各ブロックが同じ SM 上で実行され、同じ 16 かける 16 のブロック、同じ 16 行と列を、同じ共有メモリへのアクセスとともに何度も繰り返し再利用します。
  • [1:08:22] これにより、必要な情報の多くをキャッシュし、遅いメモリに何度も戻る代わりに再利用できる可能性があります。これは、その段階に達したときに最適化できることの一例です。

2Dブロックはオプションです

  • [1:08:43] 2Dブロックのアイデアは完全にオプションであり、すべては1Dブロックで行えます。

RGBからグレースケールへの変換における1Dブロックと2Dブロック

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コードを書けることは、PyTorchでは書けないflash attention、量子化、GPTQ、AWQ、bits and bytesなどにとってますます重要になっています。
  • [1:11:58] モデルがより高度になるにつれ、PyTorchが私たちのやりたいことについて持つ前提は、ますます不正確になっていきます。
  • [1:12:12] この作業のますます多くの部分を、今では開発者自身がCUDAで行わなければならなくなっています。

Condaを使ったローカルGPU開発環境のセットアップ

Dockerのような環境マネージャーとしてのConda

  • [1:13:15] セットアップにはCondaを使用します。これはPIPやpoetryの代替というより、Dockerの代替として理解する方が適切です。
  • [1:13:34] Condaを使えば、複数のバージョンのPython、CUDA、C++コンパイルシステムを並行して実行し、それらを切り替えることができます。
  • [1:13:55] Condaを使えば、紛らわしい.runファイルやUbuntuパッケージを避けられ、すべてをCondaだけで完結できます。

CondaのインストールとPyTorchに合わせたCUDAの設定

  • [1:14:01] 小さなインストールスクリプトが、必要なMiniCondaとお使いのシェルを自動検出してダウンロード・インストールし、その後ターミナルを再起動します。
  • [1:14:23] 二つ目のステップは、PyTorchがどのCUDAバージョンを必要とするかを確認することです。当時、Linux向けのCondaビルドはCUDA 12.1を使用していました。
  • [1:14:46] 三つ目のステップでは、現在のCUDAバージョンを代入したシェルコマンドを実行し、NVIDIAのプロファイリング、デバッグ、ビルドツール一式を適切なバージョンでNVIDIAからインストールします。
  • [1:15:18] 最後に、示されたコマンドでPyTorchをインストールします。-nightlyフラグを外すことで、最新の安定版が先ほどインストールしたNVIDIA CUDAの設定を使用します。

速度、プラットフォーム対応、ストレージ効率

  • [1:15:29] Condaは以前、古いソルバーのせいで遅かったのですが、ここ数か月でデフォルトになった現代的なソルバーにより、非常に高速に動作するはずです。
  • [1:15:47] このセットアップはWindows上のWSL、およびUbuntu、Fedora、Debianで動作しますが、MacではCUDAは動作しません。
  • [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を超高速に動かし、最大限の柔軟性を得るために使うものです。そして、なかなか始めるのが難しいという評判があります。実は、それほど悪くはありません。ちょっとしたコツを知っていればいいだけです。そこで、この動画ではそのコツをいくつかお見せします。では、画面に切り替えて見てみましょう。今日はすべてノートブックで作業します。これは意外に思えるかもしれません。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シリーズのLecture 3です。ただし、一緒に進めるのに過去の講義を見ている必要はありません。readmeにはLecture 3セクションがあり、その下部にColab版へ移動するクリックリンクがあります。そうです、これらすべてをColabで無料で実行できます。GPUが手元になくても、すべてを実行できます。

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

[1:39]

この本『Programming Massively Parallel Processes』のいくつかの例に沿って進めます。『Programming Massively Parallel Processes』は読むのにとても良い本で、今日のレッスンを終えれば、この本に十分取りかかれるようになっているはずです。今日わりと速く扱う内容について、より詳しく説明しています。本がなくても大丈夫ですが、より深く学びたいなら強くおすすめします。実際、このシリーズのLecture 2は、その本の第1章から第3章までの深掘りでした。ですから、混乱するかもしれませんが、今日話す内容の詳細を知るために、この後のLecture 3の前にLecture 2をやるとよいかもしれません。では、ノートブックに入りましょう。今日やることは、たくさんのことを行います

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を超高速に動かし、最大限の柔軟性を得るために使うものです。そして、なかなか始めるのが難しいという評判があります。実は、それほど悪くはありません。ちょっとしたコツを知っていればいいだけです。そこで、この動画ではそのコツをいくつかお見せします。では、画面に切り替えて見てみましょう。今日はすべてノートブックで作業します。これは意外に思えるかもしれません。CUDAで作業するには、コンパイラやターミナルなどを扱わなければならないと思われるかもしれません。しかし実際には、PyTorchが提供する魔法のおかげで、その必要はまったくありません。これらの手順はすべて一緒に進められますし、ご自身のコンピュータでそうすることを強くおすすめします。

[1:03] GitHubのCUDA modeオーガニゼーションにアクセスし、そこのLecture 2リポジトリを見つけると、Lecture 3フォルダがあるのがわかります。これはCUDA modeシリーズのLecture 3です。ただし、一緒に進めるのに過去の講義を見ている必要はありません。readmeにはLecture 3セクションがあり、その下部にColab版へ移動するクリックリンクがあります。そうです、これらすべてをColabで無料で実行できます。GPUが手元になくても、すべてを実行できます。

[1:39] この本『Programming Massively Parallel Processes』のいくつかの例に沿って進めます。『Programming Massively Parallel Processes』は読むのにとても良い本で、今日のレッスンを終えれば、この本に十分取りかかれるようになっているはずです。今日わりと速く扱う内容について、より詳しく説明しています。本がなくても大丈夫ですが、より深く学びたいなら強くおすすめします。実際、このシリーズのLecture 2は、その本の第1章から第3章までの深掘りでした。ですから、混乱するかもしれませんが、今日話す内容の詳細を知るために、この後のLecture 3の前にLecture 2をやるとよいかもしれません。では、ノートブックに入りましょう。今日やることは、たくさんのことを行います

まず古いPyTorchで[2:41]を行い、すべてのアイデアを確実に理解してから、それぞれをCUDAに変換していきます。そこで、まずはたくさんのものをインポートするところから始めます。実際、これはすべてColabでやりましょう。ではColabに来ました。ColabではランタイムをT4 GPUに設定してください。これは無料でたくさん使えて、今日やることをすべて実行するのに十分な性能です。それが動いたら、必要なライブラリをインポートして、最初の演習を始められます。最初の演習は実は本の第2章と第2章から来ていて、RGBカラー画像をグレースケール画像に変換する問題のやり方を教えてくれます。そして、推奨される式は、赤ピクセルの0.21、緑ピクセルの0.72、

[3:44] 青ピクセルの0.07を足し合わせるというもので、それによってここに見えている輝度値が作られます。これはRGBからグレースケールへ変換する一般的な方法、いわば標準的な方法です。これをやっていきます。これを実行するCUDAカーネルを作ります。まず必要なのは画像です。画像が必要なときはいつでも、子犬の画像をおすすめします。ここに子犬の画像のURLがあります。これをダウンロードして、torchvision.ioで読み込みます。これはすでにColabの一部です。自分のマシンやクラウドのサーバーで実行したい場合の設定方法は、この講義の最後に説明します。では画像を読み込み、その形状を見てみると、3×1066×1600と表示されています。ここでは基本を理解していると仮定します

[4:44] PyTorchの基本です。PyTorchの基本を知らない方には、私は少し偏っているかもしれませんが、まさにそれを扱う私のコースを強くおすすめします。course.fast.aiに行けば、とてもかわいいウサギたちも見られます。そのかわいいウサギたちと一緒に、現代の深層学習の有効な実践者になるために必要なすべてを基本的に学べます。

[5:14] ですので、もしすぐにそういった詳細に進みたいならパート一を終えてください。しかし、最初の二、三のレッスンだけでも、この種のコードやこの種の出力を理解するのに十分すぎるほど以上のことを学べます。では、シグマがあります、あなたはそれをすべて終えました。ここで見えるのは、ランク3のテンソルです。三つのチャンネルがあるので、いわば立方体の面のようなものです。各面には1066行あるのでそれが高さで、各行には16列あるのでそれが幅です。では、最初のいくつかのチャンネルと最初の三行、最初の四列を見ると、ここにあるのは符号なし8ビット整数であることがわかります。つまりバイトで、ここにあります。これが画像の姿です。もうご存じだと思います。では、私たちの画像を見てみましょう。そのために、簡単な小さな関数show imageを作って、mat lipプロットを作成します。軸を削除します。これがカラーの場合

[6:23] これは軸の順序を、PyTorchが使うチャネル×高さ×幅から、mat plot lipが期待する高さ×幅×チャネルに変えます。今日は調子が悪いようです。では、軸の順序を1 2 0に変えて、エッジを表示できます。必要ならCPUに載せます。これからこの画像をPythonで扱いますが、最初はCUDAに切り替える前に純粋なPythonで行います。とても遅いので、最小の長さ、最小の次元が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の空のベクトルから始めます。n個の値すべてを0からnマイナス1まで調べ、出力値として0.29倍くらいを入れます。

[11:17] x i の入力値です。これはここの赤い部分にあります。そして、0.59掛ける x i プラス n です。ここでのnはこの距離です。ピクセル数、1、2、3、4、5、6です。だから緑に到達するには i プラス n までジャンプしなければなりません。そして青に到達するには i プラス2n までジャンプしなければなりません。これがこの仕組みです。すべてを平坦化し、この平坦化されたものに直接インデックスを付けています。その結果、最終的にグレースケールがすべて完成します。そこで、これを高さ×幅に再形成するだけです。そして、できあがりです。グレースケールの子犬がいます。そして、あなたは

[12:26]がここで確認できます。平坦化された画像は単一のベクトルにすぎず、説明したとおり、すべてのチャネルの値が平坦化されています。さて、これは信じられないほど遅いです。わずか34,000ピクセルを処理するのにほぼ二秒かかります。そこで高速化するためにCUDAを使いたくなります。なぜCUDAは高速化できるのでしょうか。CUDAが高速化できる理由は、通常のCPUとはまったく異なる仕組みで構成されているからです。これは、たとえばRTX 3090カードに何が入っているかという情報を見れば実際にわかります。RTX 3090カードは素晴らしいGPUです。中古で手に入れることもでき、かなりお得です。特に

[13:31]のような趣味の人にとっては本当に良い選択です。3090の中には何があるのでしょうか。82個のSMがあります。SMとは何でしょうか。SMはストリーミングマルチプロセッサです。これはコンピュータの中の別のCPUのようなものだと考えられます。そしてこれが82個あります。これはすでにコンピュータのCPUの数よりはるかに多いです。さらに、それぞれに128個のCUDAコアがあります。これらのCUDAコアはすべて同時に動作できます。これらのマルチプロセッサはすべて同時に動作できます。つまり128掛ける82、合計10,500個のCUDAコアがすべて同時に動作できるということです。これは私たちが知っているどのCPUよりもはるかに多くのことができます。

[14:26]そして3090は最上位のものではありません。本当に非常に優れたGPUですが、さらに多くのCUDAコアを持つものもあります。では、どうやってそれらをすべて使うのでしょうか。そのためには、コードを次のように設定する必要があります。つまり、これは多くの異なるデータ、多くの異なるメモリ上で同時に実行できるコードの一部であり、10,000個の処理を同時に行えると指定できるようにします。CUDAはこれを非常にシンプルでかなりエレガントな方法で実現します。基本的には、内側のループを取り出すと言うのです。これが内側のループです。10,000個を同時に実行できる部分です。これらは互いにまったく影響し合いません。ご覧のとおり、これらは互いにまったく影響し合いません。それらは何かを出力メモリに入れるだけです。したがって、何かを返すことすらしません。これらのCUDAカーネル(そう呼ばれることになります)から何かを返すことはできません。できるのは、メモリを変更することだけであり、その方法では何が

[15:30] 実行される順序です。すべて同時に実行されることもあります。あるものが別のものより少し早く実行されることもあります。CUDAではこれを、関数を書いてください、そしてその関数の中に、必要なすべての処理を行うために何十回、何百回、何千回、何百万回と呼び出すコードを一行書いてください、という形で実現します。そして、できる限り並列に処理します。3090上で実行する場合、最大10,000回、最大10,000個の処理を同時に行います。そして可能な限り速く処理を終わらせます。つまり、何度も呼び出したいコードを一行書くだけでよいのです。次に必要なのは、そのコードを何回呼び出すかを指定することです。すると、カーネルと呼ばれるそのコードが呼び出されます。指定した引数、この場合は入力配列テンソル、出力テンソル、そしてサイズが渡されます。

[16:35] 各チャンネルに何ピクセルあるか。そして、これは私がそれを呼び出した ith 回目だと教えてくれます。これを Python で非常に簡単に、単一の for ループでシミュレートできます。これは並列には実行されないので高速化はされませんが、結果の種類やセマンティクスは CUDA と同一になります。ここに関数 run kernel があります。これに関数を渡します。関数を何回実行するか、そして関数を呼び出す際の引数を指定します。すると毎回、インデックス、時刻、そして要求した引数を渡して関数を呼び出します。では、これを呼び出すものを作れます。では、先ほどと同じように、チャンネル数、高さ、幅、ピクセル数を取得し、平坦化し、結果を格納する結果テンソルを作成します。今回はループを直接呼び出すのではなく、run kernel を呼び出します。そこに、の名前を渡します。

[17:42] 呼び出される関数をfとして渡します。回数、つまりループのピクセル数を渡します。そしてカーネル内で必要な引数を渡します。out、x、nが必要です。ご覧のとおり、外部ライブラリは一切使っていません。純粋なPythonと、テンソルの作成とインデックス操作に必要な最小限のPyTorchだけです。概念的には、CUDAカーネルが行うこととほぼ同じです。その「ほぼ」についてはすぐに説明します。しかし概念的には、これが互いに完全に独立した多数の処理を実行していると分かっていれば、概念的には何か書けることがお分かりいただけるでしょう。

[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個のスレッドを持ちたいとしよう。これは内側のループだということを覚えておいてほしい。あるいはここにあるカーネルランナーの内部を見ると、それが内側のループだ。だから、それぞれを呼び出す。これは256回呼ばれることになる。では、これを何回呼び出す必要があるか?ピクセル数を256で割った回数だけ呼び出す必要がある。これは整数にならないかもしれないので、切り上げる必要がある。これがブロック数を計算する方法だ。カーネルが十分な回数呼ばれることを確認する必要がある。しかしここで問題がある。以前はピクセル数に等しかった、呼び出したい回数が、256の倍数でないかもしれない。その結果、行き過ぎてしまうかもしれない。

[23:02]行き過ぎてしまう。だからこそ、今カーネル内でこのif文も必要になる。これは、現在のインデックスが持っているピクセル数を超えないことを確認するものだ。これは、ほぼすべてのCUDAカーネルで見られるもので、ガード、またはガードブロックと呼ばれる。これが、範囲外に出ないようにするためのガードだ。これは以前と同じコード行だ。今はインデックスを計算するこの部分も追加し、ガードも追加した。

[23:34]これは、どのCUDAカーネルでもよくある標準的な最初の行だ。これで実行でき、以前とまったく同じ動作をする。すると当然の疑問が浮かぶ。なぜ?なぜCUDAカーネルはこのような奇妙なブロックとスレッドの方式で動くのか?回数だけを伝えて実行させればいいのではないか?なぜブロックとスレッドでやらなければならないのか?その理由は、ここにある詳細の一部にある。CUDAが私たちのために設定してくれるので、同じブロック内のすべて、より完全に言えばスレッドブロック、つまり同じブロック内のものには、すべて共有メモリが与えられる。また、同期する機会もすべてに与えられる。つまり、このブロック内のすべてがこの地点に到達するまで、あなたは

[24:35]先に進めない。ブロック内のすべてのスレッドは同じストリーミングマルチプロセッサ上で実行される。後の講義で見ることになるが、私が教えるわけではないが、ブロックを賢く使うことでコードをより速く実行できる。そして共有メモリは特に重要だ。共有メモリとはGPU内の小さなメモリで、ブロック内のすべてのスレッドが共有し、高速だ。

[25:08] これは超、超、超高速です。ここで「あまり多くない」と言うと、3090上では128K程度です。つまり非常に小さいです。これは基本的にCPUのキャッシュと同じです。ただし違いは、CPUではキャッシュに何を入れるかを手動で決めることはありません。しかしGPUでは、自分で決めます。すべてあなた次第です。ですから現時点では、CUDAコードを作成するときにこのキャッシュは使われません。まだ始めたばかりだからです。なのでその最適化は気にしません。しかし高速化するには、そのキャッシュを使いたいところです。また、レジスタファイルも使いたいところです。多くの人が気づいていないことですが、実はかなりの量のレジスタメモリがあり、共有メモリよりも多くのレジスタメモリがあります。ともかく、これらは後で気にすべきことで、始めるには必要ありません。では、CUDAをどう使うのでしょうか。基本的に標準的な

[26:15] 私が追加する、そしてこれから追加するセットアップブロックがあります。このセットアップブロックでは、環境変数を設定します。本番環境や高速化には使わないでしょう。しかしこれは、エラーが発生したらすぐに停止する、というものです。ですからどうなるか見てみましょう。そうすれば、エラーがいつ、どこで発生したかを正確に教えてくれます。そのため遅くなりますが、開発には良いです。また、二つのモジュールをインストールします。一つはビルドツールで、C++のCUDAコードをコンパイルするためにPyTorchが必要とします。二つ目はWorldLitzaという非常に便利な小さなものです。これが使われるのを見るのは、ここでWorldLitzaという拡張機能を読み込むこの行だけです。これがないと、CUDAコードから、実際にはC++コードからprintしたものはノートブックに表示されません。ですからCUDAで作業する

[27:19] ノートブックでは常にこれをしたいところです。そうすればprint文を使ってデバッグできます。では、CUDAコードがあるとして、それをPythonからどう使うのでしょうか。答えは、PyTorchにはLoadInlineという非常に便利なものがあり、それはtorch.utils.cpp extensionの中にあります。LoadInlineは素晴らしい関数で、コンパイルしたいCUDAコード文字列のリスト、コンパイルしたいプレーンなC++文字列、そのC++の中でPyTorchから利用可能にしたい関数を渡すだけです。するとすべてをコンパイルし、Pythonモジュールに変換して、すぐに利用可能にしてくれます。これはかなり驚きです。私はちょうど小さなラッパーを作りました、

[28:26] それを LoadCuda と呼んでいます。ほんの少しだけ簡略化するためです。裏側では、単に LoadInline を呼び出すだけです。もう一つ私がやったのは、いくつかの C++ コードを含む文字列を作成したことです。これはすべて C コードだと思いますが、C++ コードとしてコンパイルされます。C++ コードと呼びましょう。すべての CUDA ファイルに含めたい C++ コードです。PyTorch のテンソル関連にアクセスできるようにするため、このヘッダーファイルをインクルードする必要があります。I.O. を使えるようにし、例外をチェックできるようにしたいのです。そしてさらに三つのマクロを定義します。最初のマクロは、テンソルが CUDA 上にあることをチェックするだけです。二つ目は、メモリ上で連続していることをチェックします。なぜなら、PyTorch は時々、異なるメモリ領域に分割することがあるからです。そして、もしこれをこの

[29:29] 平坦化された形でアクセスしようとすると、うまくいきません。そして実際の使い方としては、check input で、その両方をチェックするだけです。つまり、何かが CUDA 上になく、連続していなければ、それを使うことはできません。なので、常にこれを持っています。そしてここで行う三つ目は、切り上げ除算を定義することです。切り上げ除算はこれだけです。ただし、このように別の方法で実装することもできます。これで切り上げ除算が行われます。そしてこれが、必要なブロック数を計算するために呼び出すものです。なので、この詳細についてあまり心配する必要はありません。これはただ、私たちが使う標準的な設定です。では、CUDA カーネルを書く必要があります。さて、どうやって CUDA カーネルを書くのでしょうか?

[30:19] 私がやったこと、そして皆さんにもお勧めするのは、Python カーネルを ChatGPT に貼り付けて、同じ名前や書式などを使って同等の C コードに変換してくださいと頼むことです。可能なら貼り付ければ、ChatGPT がやってくれます。C に非常に慣れているなら、自分で書いても構いません。しかし、すでに Python があるのですから、こうしない手はありません。私が見た限り、ほぼ完璧でした。ただし、これらを float と仮定していましたが、実際には float ではありませんでした。いくつかのデータ型を変更する必要がありましたが、ほぼそのまま使えました。特に、最近の私のように Python プログラマー寄りの人にとっては、必要なコードの 95% を書くのに良い方法です。他に何を変更する必要があるでしょうか?先ほどの図で見たように、これは block とは呼ばれていません。

[31:28] IDX、これはブロックIDX.x、ブロックdim.x、スレッドIDX.xと呼ばれます。ですから、そこにドットXを追加する必要があります。それ以外は、比較するとですね。ご覧の通り、この二つのコードはほぼ同じに見えます。データ型を追加する必要がありました。セミコロンを追加する必要がありました。コロンを削除する必要がありました。中括弧を追加する必要がありました。それくらいです。ですから、まったく大差ないのです。もしCプログラミングをあまりやったことがなくても、心配しすぎないでください。というのも、実際のところ、この種の計算集約的な作業ではそれほど違いはないのです。話しておくべきことの一つはこれです。unsigned cast Rとは何でしょうか。これはCでUint 8を書く方法にすぎません。もしよくわからない場合は、そのまま使えます。

[32:32] Pytorchの表記とCの表記の間でデータ型を変更する方法がよくわからない場合は、ChatGPTに聞くか、Googleで検索できます。しかし、これがbyteを書く方法です。実際には、アスタリスクは基本的に「これは配列である」と言う方法です。つまり、これはXがバイトの配列であることを示しています。実際にはポインタを意味しますが、ご覧の通り、Cではポインタは配列として扱われます。ですから、ポインタであることをあまり気にする必要はありません。私たちにとっては単に配列を意味するだけです。しかしCでは、扱える配列は一次元配列だけです。だからこそ、常に平坦化する必要があるのです。多次元テンソルをこのようにCUDAカーネルで直接使うことはできません。ですから、最終的にはこれらの一次元C配列を使うことになります。それ以外は、まったく同じに見えます。実際、Pythonで書いたように

[33:32] それも、まったく同じに見えます。ここでのvoidは、何も返さないという意味にすぎません。そして、ここのダンダーglobalはCUDAによって追加された特別なものです。三つのものが現れる可能性があります。これは単に、これを何のためにコンパイルすべきかを示しています。ですから、ダンダーdeviceを書くことができ、それはGPU上でのみ呼び出せるようにコンパイルするという意味です。ダンダーglobalと書くこともでき、それはCPUまたはGPUから呼び出せてGPU上で実行されるという意味です。あるいは、ダンダーhostと書くこともできますが、必須ではありません。それは単にCPU側で実行される通常のCまたはC++プログラムであるという意味です。ですから、CPU側から何かを呼び出してGPU上で何かを実行したいとき、つまりカーネルを扱うときはほぼ常にそうですが、ダンダーglobalと書きます。ここではダンダーglobalがあり、カーネルがあり、それだけです。次に必要なのは

[34:36] それがカーネルを呼び出すためのものです。先ほどカーネルを呼び出すには、このブロックカーネル関数を呼び出し、カーネルとブロック、スレッドを渡しました。CUDAでは引数を渡すのに特別な関数を使う必要はありません。カーネルに組み込まれた奇妙な特別な構文がそれを代わりに行ってくれます。その奇妙な特別な構文を使うには、呼び出したいカーネル、つまり関数は何かと指定し、その後でこの奇妙な三連山括弧を使います。つまり、三連山括弧はC++言語へのCUDA独自の拡張であり、これはカーネルでありGPU上で呼び出してくださいという意味です。

[35:19] そして三連山括弧の間には、いくつか渡せるものがありますが、少なくとも最初の二つ、つまりブロック数とスレッド数を渡す必要があります。ブロック数は、ピクセル数をスレッド数で割った切り上げ除算です。スレッド数は、先ほど言ったように常に256を選んで気にしないことにしましょう。これはこの関数をGPUカーネルとして呼び出し、これらの引数を渡すという意味です。入力テンソル、出力テンソル、そしてピクセル数を渡す必要があります。そして、これらのテンソルそれぞれについて、特別なメソッドであるドットdataポインタを使う必要があることがわかります。これにより、テンソルへのCポインタに変換されます。だからこそ、カーネルに届く時点ではCポインタになっているのです。また、どのデータ型として扱うかを伝える必要があります。これはUntatesとして扱うという意味です。つまりこれがこの

[36:23] はここではC++のテンプレートパラメータです。そしてこれはメソッドです。もう一つ知っておくべきことは、C++ではドットはオブジェクトのメソッドを呼び出すことを意味し、そうでなければコロンコロンは基本的にCやPythonでクラスのメソッドを呼び出すのに似ています。つまり、torchドットemptyとは書かず、出力を作成するにはtorchコロンコロンemptyと書きます。あるいは以前Pythonでやった時は、torchドットemptyと書きました。

[36:55] これはPythonでも同じです。ああ、なるほど。ではPythonでは、その通りです。長さとベクトルを作成してから、ドットビューを行いました。やり方はあまり重要ではありません。しかしこの場合、実際には二次元テンソルを作成しました。ここで中括弧の中にこれを渡しています。これはC++のリスト初期化子と呼ばれます。基本的には高さ、カンマ、幅を含む小さなリストです。これにより二次元行列を作成するよう指示されるので、最後にドットビューが必要ないのです。ドットビューの方法でもできました。おそらく一貫性を保つ方が良いでしょう。しかしこれは当時私が書いたものです。出力を作成する際のもう一つの興味深い点は、input.optionsを渡す場合です。これは入力テンソルで、入力と同じデータ型と同じデバイス、CUDAデバイスを使うように指示しています。これは非常に便利な方法で、Pythonにはないと思いますが、同じデータ型と同じデバイスであることを確認できます。ここでautoと書けば、とても便利です。型を指定する必要がありません。

[38:01] これはです。torch::tensorと書くこともできました。しかしautoと書くことで、自分で判断してくれという意味になります。これも便利なC++の小さな機能です。カーネルを呼び出した後、エラーがあっても必ずしも通知されません。エラーをチェックするように指示するには、これを書く必要があります。これはPyTorchが提供するマクロです。詳細は重要ではありません。カーネルを呼び出した後は常にこれを呼び出して動作を確認すべきです。そして、確保してポインタとして渡し、埋めたテンソルを返すことができます。OK。さて、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変数を作成し、imageを連続的にして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 でブロックとスレッドを使って二次元グリッドにインデックスする方法です。そうしなければならないわけではありません。望むなら便利なだけです。実際、最大三次元まで使えます。カーネルランナーを作るには、ブロックとスレッドのための二重ループだけでなく、二組の二重ループを持つ必要があります。x と y の両方、ブロックとスレッド、つまり行と列のブロックとスレッドです。その結果、少し見苦しくなります。なぜなら四重の for ループになるからです。y 軸のブロックを回し、次にブロックを

[55:21] x 軸で回し、次に y 軸のスレッドを回し、次に x 軸のスレッドを回します。つまり、このデカルト積は各ブロックについて、各スレッドについてと考えることができます。さて、dot y と dot x を得るには、simple namespace という便利な Python 標準ライブラリのものを使います。よく使うので、手早く雑に書くコードではいつも名前空間を使うため、NS という名前を付けています。これら四つすべてを回します。次にカーネルを呼び出し、y と x 座標を含むオブジェクトを渡します。それがブロックになります。またスレッドも渡し、それはスレッドの y と x 座標を持つオブジェクトです。そして最終的に、各ブロックについてすべての可能なブロックとすべての可能なスレッド番号を処理します。また各ブロックの大きさも伝える必要があります。

[56:27] どれだけ高く、どれだけ広いか。これがその内容です。ご覧の通り、これは単純な名前空間で、x と y を持つオブジェクトになります。ですから、それらがどれだけ大きいかを知る必要があります。先ほどと同じように、ブロックの次元を知る必要がありました。だから threads を渡したのです。これはすべて純粋な PyTorch であることを覚えておいてください。実際には CUDA を呼び出しているわけではありません。インデックス作成とテンソル作成のためにほんの少し PyTorch を使う以外は、他のライブラリを呼び出していません。ですから、これらすべてを手動で実行できます。理解を確実にしてください。デバッガに入れて、ステップ実行できます。そして、私たちの関数を呼び出します。これが行列乗算関数です。先ほど述べたように、これは以前に書いたドット積を含むカーネルです。ですから、ガードは、現在の行番号が持っている高さを超えていないこと、および現在の列番号が持っている幅を超えていないことを確認する必要があります。また、どの行番号にいるのかも知る必要があります。

[57:27] 現在の位置です。これはまったく同じです。実際、列は以前に見たものとまったく同じだと言うべきでしょう。実際、CUDA では block IDX.x があったのを覚えているかもしれません。これがその理由です。CUDA では常にこれらの三次元の dim three 構造が与えられるからです。ですから、この .x を付ける必要があります。これで列を見つけることができます。そして、行は、いくつのブロックを通過したか、y 軸での各ブロックの大きさ、y 軸でいくつのスレッドを通過したかを見ることで見つけられます。現在の行番号は何か?現在の列番号は何か?それはテンソルの境界内にあるか?そうでなければ停止し、そうでなければドット積を実行して出力テンソルに入れます。これはすべて純粋な Python です。これで、最初の入力の高さと幅、二番目の入力の高さと幅を取得して呼び出せます。

[58:35] 二番目の入力の高さと幅を取得して呼び出せます。そして、k と k2、内側の次元は一致するはずです。その後、出力を作成できます。これで、スレッド毎のブロックは単なる数値 256 ではなく、数値のペアです。x と y です。そして、掛け合わせて 256 になる二つの数値を選びました。繰り返しますが、二次元入力がある場合にうまく分散させるための合理的な選択です。ここで注意すべき点は、スレッド毎のブロックが 1024 より大きくできないことです。ですから、安全な 256 を使用しています。そして、これらを掛け合わせる必要があることに注意してください。16 掛ける 16 がスレッド毎のブロック数になります。ですから、これらは安全な数値です。ブロックが不足することはありません。

[59:30] 2から31までは、次元0の最大ブロック数であり、次に2から16までは次元1と2のためのものです。実際にはマイナス1だと思いますが、気にしないでください。ですから、スレッドをあまり多く持たないでください。ただし、ブロックはたくさん持つことができます。しかしもちろん、各対称モデルプロセッサはこれらすべてを同じデバイス上で実行し、共有メモリにもアクセスできます。だからこそ、ブロックごとに少数のスレッドを使用するのです。ですから、ブロックのxには切り上げ除算を使用します。yにも同じ切り上げ除算を使用します。もしこれらに馴染みがなければ、以前の例に戻ってください。コードはすべてそこからコピーされているからです。そして今、カーネルを渡して2Dブロックカーネルランナーを呼び出すことができます。ブロック数、ブロックごとのスレッド数、平坦化された入力行列、平坦化された出力行列、そして必要な次元を渡します。これらはすべてここで使用されるからです。そして結果を返します。そして、そのmapMoleを呼び出すと、

[1:00:35] 2Dブロックで、元の手動ループで得たものに近いことを確認できます。もちろん、同じコードを実行しているので、近いのです。さて、それができたので、CUDAバージョンに進めます。CUDAバージョンははるかに高速になるので、この縮小された行列を使う必要はもうありません。全体を使えます。正しいことを確認するために、比較できる高速なCPUベースのアプローチが欲しいです。以前は39,000要素で約一秒かかりました。これがどう動作するかは説明しませんが、ブロードキャストのアプローチを使って高速なCPUベースのアプローチを得ます。fast AIコースを確認すれば、このブロードキャストのアプローチのやり方を教えています。しかし、これは純粋なPythonのアプローチで、三つのネストされたループではなく単一のループで全体を処理します。縮小されたテンソルでは同じ答えを出します。

[1:01:47] しかしはるかに高速で、わずか四ミリ秒です。ですから、今では全体の入力行列で実行できるほど高速です。そして約1.3秒かかります。このブロードキャスト最適化バージョンは、ご覧のとおり、はるかに高速です。そして今、三つのループの真ん中で、実質的には三つのループですがブロードキャストしているので、392百万回の加算が行われています。ですから、これははるかに高速です。

[1:02:19] しかし、私がこれを実際に行っている理由は、この結果を比較用に保存できるようにするためです。これにより、私たちのCUDAバージョンが正しいことを確認できます。では、これをどうやってCUDAに変換するのでしょうか?驚かないかもしれませんが、私がやったのはこの関数をコピーしてChatGPTに渡し、「これをCで書き直してください」と頼んだことです。そして、基本的に初回で使えるものを返してくれました。それがこちらです。今回はunsignedキャストのスターではなく、floatのスターになっています。それ以外は、以前見たのとまったく同じ変更を加えたPythonとほぼ同じに見えます。今度は.yと.xのバージョンがあります。繰り返しになりますが、CPUから呼び出したときにGPUで実行するよう指示するDunderGlobalがあります。カーネルについては、特に話すことはないと思います。そしてカーネルを呼び出す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構造になり、その場合インデックスの一と二、つまりドットX、ドットY、ドットZの値が自動的に一に設定されていたということです。つまり、実は気づかないうちにすでにdim3構造を使っていたのです。そして以前と同じように、必要なすべてのテンソルを渡し、それらをポインタにキャストし、単なるキャストではなく、何らかのデータ型を通じてポインタに変換し、関数やカーネルが必要とするその他の情報を渡します。では、再びload CUDAを呼び出します。これでこれがモジュールにコンパイルされ、

[1:06:21]それらが両方とも連続していてCUDAデバイス上にあることを確認します。そして、moduleドットmapmulを呼び出してそれらを渡し、CPUに載せてすべてが近い値か確認すると、はい、近いと返ってきます。これは今や最初の五行だけでなく、MNISTデータセット全体で実行されています。MNISTデータセット全体で、最適化されたCPUアプローチを使うと1.3秒かかりました。CUDAを使うと6ミリ秒です。つまり、かなりの改善です。いいですね。もちろん他に言及すべきことは、PyTorchはatを使うだけで行列積を計算してくれるということです。どれくらいかかるか、そして当然同じ答えを返しますが、実行にどれくらいかかるでしょうか?それは2ミリ秒かかります。つまり三倍速いのです。そして多くの状況では、三倍どころでは

[1:07:26]ありません。では、なぜ私たちはまだPyTorchに比べてかなり遅いのでしょうか?つまり、6ミリ秒で392百万回の計算を行うのは悪くありません。しかしPyTorchがそんなにはるかに速くできるなら、彼らは何をしているのでしょうか?その秘訣は、彼らが特にこの共有メモリを活用していることです。共有メモリとは、ブロック内のスレッド間で共有される小さなメモリ空間で、グローバルメモリよりもはるかに高速です。私たちの行列積では、これらのブロックの一つがあるとき、同じSM内で一度に一ブロックずつ処理するので、同じ16×16ブロックを再利用することになります。同じ16行と列を何度も何度も使い、そのたびに同じ共有メモリにアクセスします。ですから、必要な情報の多くを実際にキャッシュして再利用できる可能性があることがお分かりいただけるでしょう。そうする代わりに

[1:08:28] 何度も何度も遅いメモリに戻ってしまいます。ですからこれは、その段階に到達したら最適化できる可能性があるものの一例です。ここで言及しておきたいもう一つの点は、この2次元ブロックのアイデアは完全に任意だということです。1次元ブロックでも、2次元ブロックでも、3次元ブロックとスレッドでも、すべてを行うことができます。それを示すために、最後に2次元ブロックを使ってRGBをグレースケールに変換する例を用意しています。先ほどこれを行ったときは1次元ブロックを使っていたのを覚えているでしょう。まったく同じ結果が得られます。そしてコードを比較すると、1次元スレッドとブロックで行ったバージョンはかなり

[1:09:33] 2次元スレッドとブロックを使うバージョンより少し短くなっています。ですからこの場合、ピクセルを操作しているので2次元のアプローチを使う方がすっきりして便利だと思うかもしれませんが、この特定のケースではそうでもありませんでした。列と行をx、yで別々に扱うコードはまだかなりシンプルです。ガードはもう少し複雑になります。ここで実際にどのインデックスにいるのかを把握する必要があります。一方、このカーネルではずっと直接的で、わずか二行のコードでした。そしてカーネルを呼び出す際も、これではなくスレッド毎ブロックの扱いがある分、少し複雑になります。指摘したかった重要な点は、これら二つのコードがまったく同じことをするということです。ですから2次元や3次元のブロック・スレッド構造を使いたくないなら、使う必要はありません。1次元のものを使うだけでよいのです。

[1:10:32] 2次元のものは、使うのが便利で使いたい場合にのみ存在します。使わなければならないと感じる必要はありません。そうですね、今日皆さんにお見せしたかった重要な点は基本的にこれで全部だと思います。これから得ていただきたい主なことは、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を自動的に判断し、どのシェルを使っているかも自動的に判断します。

[1:14:18] これを実行すれば、ダウンロードしてインストールしてくれます。では、そのスクリプトを実行して、ターミナルを再起動してください。これで Conda が使えるようになります。ステップ二は、PyTorch が要求する CUDA のバージョンを確認することです。Linux、Conda をクリックすると、CUDA 12.1 が最新です。次にステップ三は、このシェルコマンドを実行することです。12.1 を現在の PyTorch のバージョンに置き換えてください。私の場合は今のところまだ 12.1 です。これで必要なものがすべてインストールされます。プロファイリング、デバッグ、ビルドなどに必要なもの、必要な NVIDIA ツール一式がすべてインストールされ、NVIDIA から直接提供されるので適切なバージョンになります。先ほど言ったように、異なる環境に複数のバージョンを同時にインストールすることもできます。まったく問題ありません。そして最後に、

[1:15:18] PyTorch をインストールします。ここのこのコマンドで PyTorch がインストールされます。なぜかここでは nightly と書いてしまいました。nightly は必要ありません。ダッシュ nightly を削除するだけです。これで、先ほどインストールした NVIDIA CUDA を使って最新バージョンの PyTorch がインストールされます。以前に Conda を使ったことがあり、とても遅かったという方は、それは以前は別のソルバーを使っていて、それが現代のものより数千倍、数万倍も遅かったからです。ここ数か月で追加され、デフォルトになったばかりです。なので今ではすべて非常に速く実行されるはずです。先ほど言ったように、Windows では WSL 上で動作します。Ubuntu でも動作します。Fedora でも動作します。Debian でも動作します。すべてそのまま動きます。これが、ローカル開発のための環境構築として私が強くお勧めする方法です。Docker を使う心配はありません。先ほど言ったように、異なる CUDA バージョン、異なる Python バージョン、異なるコンパイラなどを、何も気にせず切り替えられます。

[1:16:23] Docker 関連のことを気にする必要はありません。また、複数の環境に同じライブラリなどがインストールされている場合、ハードリンクされるので十分効率的です。追加のハードディスク容量を使うことすらありません。とても効率的です。素晴らしい。これが、自分のマシンでもクラウドでも、どこでも始められる方法です。お役に立てれば幸いです。では、ご視聴ありがとうございました。お役に立てたならうれしいですし、CUDA で何を作ったか聞けるのを楽しみにしています。次のステップとしては、他の CUDA モードの講義をチェックしてみてください。リンクを貼っておきます。また、自分自身でいくつかプロジェクトを試してみることもお勧めします。たとえば、4 ビット量子化や Flash Attention などを実装してみるとよいでしょう。

[1:17:24] のようなものです。さて、これらはかなり大きなプロジェクトですが、一度に一歩ずつ積み上げる小さなものに分割してみることができます。そしてもちろん、他の人のコードを見てください。Flash Attentionの実装を見てください。bits and bytesの実装を見てください。GPTQの実装なども見てください。他の人のコードを読む時間が増えれば増えるほど良いです。では。これがお役に立てば幸いです。ご視聴ありがとうございました。

英語の原文字幕を見る

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Vidleaf リーダーで開く

文字起こしを検索し、行を選択し、タイムスタンプ付きで引用をコピーし、翻訳します。

出典表示

Jeremy Howardによる「Getting Started With CUDA for Python Programmers」(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を推奨するものでもありません。VidleafはAIによる句読点の付加とAI生成の要約を追加しました。元の文言はこのページで引き続きご覧いただけます。

あなたは制作者または権利者ですか? 訂正または削除を依頼する: copyright@vidleaf.app (これらのページについてをご覧ください)。

最終更新