GPU対応PyTorch 2.3のセットアップと性能確認(Windows 上)

概要

Windows環境でのPyTorch 2.3のインストール手順と動作確認方法を詳細に説明している.主な内容としては,Build Tools for Visual Studio 2022,NVIDIAドライバ,NVIDIA CUDAツールキット,NVIDIA cuDNNの事前インストール,PyTorch公式ページ https://pytorch.org/ からのインストールコマンド取得,コマンドプロンプトでの実行である.また,インストール後の動作確認として,GPUとCPUの性能比較を行う行列積計算プログラムの実行方法が示されている.さらに,画像分類タスクのためのImageNetで学習済みのConvNeXtBaseモデルを用いたリアルタイム画像分類プログラムの実装例も提供されている.各ステップでは,具体的なコマンドラインの操作を示している.

目次

サイト内の関連ページ

【付記】 本ページのプログラムはAIのアシストを受けて作成しています

前準備

Python 3.12 のインストール

Pythonのインストールを行い、Pythonのプログラムを実行する環境を整える。扱う環境は、Windows搭載パソコンである。金子研究室では、Python 3.12.10を推奨する。

[Windows での Python 3.12 のインストール手順を見るには、ここをクリック]

Windows での Python 3.12 のインストール

以下のいずれかの方法でPython 3.12をインストールする。Pythonがインストール済みの場合、この手順は不要である。

方法 1:winget によるインストール

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動するとPATHが反映される。

REM Python 3.12 をシステム領域にインストール
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
if not "%ERRORLEVEL%"=="0" ( color 0c & echo Python 3.12 のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; if(Test-Path $p){$k=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment',$true); $c=$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $t=$k.GetValueKind('Path'); $new=$c; if((';'+$new+';') -notlike \"*;$p;*\"){$new=$p+';'+$new}; if((';'+$new+';') -notlike \"*;$s;*\"){$new=$s+';'+$new}; if($new -ne $c){$k.SetValue('Path',$new,$t)}; $k.Close()}"

REM 現在のセッションにも反映(システムPATHを再取得して連結)
for /f "usebackq tokens=2,*" %A in (`reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) do set "PATH=%B"

REM pip / wheel の更新
python -m pip install --no-user -U pip wheel
if not "%ERRORLEVEL%"=="0" ( color 0c & echo pip / wheel の更新に失敗しました & ping 127.0.0.1 -n 6 >nul & color )

方法 2:インストーラーによるインストール

  1. Python公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンからWindows用インストーラーをダウンロードする。
  2. ダウンロードしたインストーラーを実行する。
  3. 初期画面の下部に表示される「Add python.exe to PATH」にチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから python コマンドを実行できない。
  4. 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。

インストールの確認

コマンドプロンプトで以下を実行する。

python --version

バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

Build Tools for Visual Studio 2026(ビルドツール)のインストール

Build Tools for Visual Studio 2026(ビルドツール)のインストールを行い、C/C++ コードのビルド環境を整える。

[Build Tools for Visual Studio 2026(ビルドツール)のインストール手順を見るには、ここをクリック]

Windows での Build Tools for Visual Studio 2026 のインストール

Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。インストール済みの場合,この手順は不要である。

以下のコマンドは、Build Tools が未インストールの場合は winget で新規インストールし、インストール済みの場合は setup.exe modify でコンポーネントを追加する(バージョンは変更しない)。

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windows キーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

REM ============================================================
REM Visual C++ 再頒布可能パッケージ (VCRedist 2015-)
REM ============================================================
winget install --scope machine --id Microsoft.VCRedist.2015+.x64 -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/quiet /norestart"
if not "%ERRORLEVEL%"=="0" ( color 0c & echo VCRedist のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM ============================================================
REM Visual Studio Build Tools + Desktop development with C++
REM (VCTools、MSBuildTools、CMake連携、Clang、Windows 11 SDK)
REM ============================================================
REM 進行中のインストーラーを停止(ロック競合回避。対象プロセスが存在しない場合は
REM taskkillがエラーを返すが、これは想定内であるため出力のみ抑制する)
taskkill /F /IM vs_setup.exe /T >nul 2>&1
taskkill /F /IM vs_installer.exe /T >nul 2>&1
taskkill /F /IM vs_installerservice.exe /T >nul 2>&1
taskkill /F /IM msiexec.exe /T >nul 2>&1

REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
REM 未インストール時: winget で新規インストール
REM インストール済み時: setup.exe modify でコンポーネント追加(バージョンは変更しない)
winget list --id Microsoft.VisualStudio.BuildTools 2>nul | findstr /i "BuildTools" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    for /f "usebackq delims=" %P in (`"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do start /wait "" "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" modify --installPath "%P" --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64 --includeRecommended --quiet --norestart --nocache
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のコンポーネント追加に失敗しました & ping 127.0.0.1 -n 6 >nul & color )
) else (
    winget install --scope machine --id Microsoft.VisualStudio.BuildTools -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64"
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )
)

REM
REM BuildTools のインストールパスを vswhere.exe で取得(メジャーバージョンに依存しない)
set "VSWHERE=C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
set "BT_PATH="
for /f "usebackq delims=" %P in (`"%VSWHERE%" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do set "BT_PATH=%P"
if not defined BT_PATH ( color 0c & echo Build Tools のインストールパスを取得できませんでした & ping 127.0.0.1 -n 6 >nul & color )

REM 破損時の修復(任意、動作がおかしくなった場合)
REM if defined BT_PATH "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" repair --installPath "%BT_PATH%" --quiet --norestart
REM 導入確認(インストールパスが表示されれば正常)
"%VSWHERE%" -products * -requires Microsoft.VisualStudio.Workload.VCTools -property installationPath

上記のコマンドでは、Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし、続いて以下のコンポーネントを追加している。

追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。

インストール完了の確認

winget list Microsoft.VisualStudio.BuildTools

Visual Studio を必要とするとき

Visual Studio の機能を必要とする場合は,追加インストールできる。

NVIDIA CUDA Toolkit 12.8のインストール

以下のコマンドを管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。

REM NVIDIA CUDA Toolkit 12.8 をシステム領域にインストール
winget install --scope machine --id Nvidia.CUDA --version 12.8 -e --silent --disable-interactivity --force --uninstall-previous --accept-source-agreements --accept-package-agreements --override "-s -n"

REM 環境変数TEMP, TMPの設定(一時ファイルの保存先を短いパスに変更)
mkdir C:\TEMP
set "TEMP_PATH=C:\TEMP"
setx TEMP "%TEMP_PATH%" /M >nul
setx TMP "%TEMP_PATH%" /M >nul

PyTorch のインストール(Windows 上)

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. 使用する Python のバージョンの確認
    python --version
    
  3. PyTorch の Web ページを開く

    https://pytorch.org/

  4. ランタイムコマンドを表示させる

    次のように選ぶと,その下に,ランタイムコマンドが表示される

    • Your OS: Windows を選ぶ
    • Package: pip を選ぶ
    • Language: Python を選ぶ
    • CUDA: 使用している CUDA のバージョンを選ぶ
  5. ランタイムコマンドを,先ほどのコマンドプロンプト(管理者として実行したもの)で実行
    PyTorch 2.3 のインストール手順例は次の通り
    1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
    2. PyTorch のページを確認

      PyTorch の公式ページ: https://pytorch.org/index.html

    3. 次のようなコマンドを実行(実行するコマンドは,PyTorch のページに表示されるコマンドを使う).

      次のコマンドを実行することにより, PyTorch (NVIDIA CUDA 12.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.

      事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 12.8 が前もってインストール済みであるとする).

      PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.

      python -m pip install -U --ignore-installed pip
      python -m pip uninstall -y torch torchvision torchaudio torchtext xformers
      python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu128
      
      python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
      
  6. Python でPyTorch のバージョン確認
    python -c "import torch; print( torch.__version__ )"
    
  7. 動作確認

    https://pytorch.org/get-started/locally/ に記載の Python プログラムを動かしてみる

    Python プログラムの実行

    Python のまとめ: 別ページ »にまとめ

    1. コマンドプロンプトで次を実行
      python
      
    2. Python プログラムを実行する

      PyTorch を使用して,5行3列のランダムな値を持つテンソル (多次元配列) を作成し,それを表示するプログラム.

      import torch
      x = torch.rand(5, 3)
      print(x)
      

行列の掛け算,主成分分析,特異値分解(PyTorch のプログラム例)(Windows 上)

行列の掛け算

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd /d c:%HOMEPATH%
    notepad pytorchmul.py
    
  3. エディタで,次のプログラムを保存
    このプログラムは,PyTorch を使用して GPU と CPU での行列積の性能を比較する.異なるサイズ (5000x5000, 10000x10000, 15000x15000, 20000x20000) で,ランダムな値を持つ2つの行列を生成し,それらの行列積を計算する.GPU と CPU それぞれで,行列積の計算時間を測定し,結果を出力する.このことで,GPU と CPU での行列積の性能を比較できる.
    import torch
    import time
    
    def measure_time(func):
        start_time = time.perf_counter()
        func()
        if torch.cuda.is_available():
            torch.cuda.synchronize()
        end_time = time.perf_counter()
        return end_time - start_time
    
    def run_matmul(device_type, matrix_size):
        print(f'実行開始 - Matrix Size: {matrix_size}')
        print('device_type の設定:', device_type)
    
        if device_type == 'GPU' and not torch.cuda.is_available():
            print("CUDA is not available. Skipping GPU computation.")
            return
    
        device = torch.device('cuda' if device_type == 'GPU' else 'cpu')
    
        X = torch.rand(matrix_size, matrix_size, device=device)
        Y = torch.rand(matrix_size, matrix_size, device=device)
    
        calculation_time = measure_time(lambda: torch.matmul(X, Y))
    
        print(f"Running on {device_type}")
        print(f"Available devices: {device}")
        print(f"Calculation time: {calculation_time:.6f} seconds")
        print()
    
    def main():
        matrix_sizes = [5000, 10000, 15000, 20000]
    
        for size in matrix_sizes:
            print(f'Matrix Size: {size}')
            run_matmul('GPU', size)
            run_matmul('CPU', size)
            print('---')
    
    if __name__ == '__main__':
        main()
    
  4. Python プログラムの実行

    プログラムを pytorchmul.pyのようなファイル名で保存したので, 「python pytorchmul.py」のようなコマンドで行う.

    python pytorchmul.py
    
  5. 結果の確認

    行列積の計算時間が表示される.

主成分分析,特異値分解

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd /d c:%HOMEPATH%
    notepad pypcasvd.py
    
  3. エディタで,次のプログラムを保存
    このプログラムは,PyTorch を使用して,行列に対してPCA(主成分分析)とSVD(特異値分解)の計算を行い,GPUとCPUでの実行時間を比較する. [1000, 2000, 3000, 4000] の異なる4通りのサイズの行列に対して, PCAとSVDの計算時間を測定し,結果を表示することで,GPUとCPUの性能の違いを確認できる.
    import torch
    import time
    
    def measure_time(func):
        start_time = time.perf_counter()
        func()
        if torch.cuda.is_available():
            torch.cuda.synchronize()
        end_time = time.perf_counter()
        return end_time - start_time
    
    def run_pca_svd(device_type, matrix_size):
        print(f'実行開始 - Matrix Size: {matrix_size}')
        print('device_type の設定:', device_type)
    
        if device_type == 'GPU' and not torch.cuda.is_available():
            print("CUDA is not available. Skipping GPU computation.")
            return
    
        device = torch.device('cuda' if device_type == 'GPU' else 'cpu')
        X = torch.randn(matrix_size, matrix_size, device=device)
    
        def pca_operation():
            mean = torch.mean(X, dim=0)
            X_centered = X - mean
            cov_matrix = torch.matmul(X_centered.T, X_centered) / (matrix_size - 1)
            torch.linalg.svd(cov_matrix)
    
        def svd_operation():
            torch.linalg.svd(X)
    
        pca_time = measure_time(pca_operation)
        svd_time = measure_time(svd_operation)
    
        print(f"Running on {device_type}")
        print(f"Available devices: {device}")
        print(f"PCA Calculation time: {pca_time:.6f} seconds")
        print(f"SVD Calculation time: {svd_time:.6f} seconds")
        print()
    
    def main():
        matrix_sizes = [1000, 2000, 3000, 4000]
        for size in matrix_sizes:
            print(f'Matrix Size: {size}')
            run_pca_svd('GPU', size)
            run_pca_svd('CPU', size)
            print('---')
    
    if __name__ == '__main__':
        main()
    
  4. Python プログラムの実行

    プログラムを pypcasvd.pyのようなファイル名で保存したので, 「python pypcasvd.py」のようなコマンドで行う.

    python pypcasvd.py
    
  5. 結果の確認

ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類(PyTorch を使用)

ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類を行う.

  1. パソコン接続のカメラを使用するので準備しておく
  2. 前準備として Python 用 opencv-python のインストール
    python -m pip install -U opencv-python opencv-contrib-python
    
  3. Windows で,コマンドプロンプトを実行
  4. エディタを起動
    cd /d c:%HOMEPATH%
    notepad pyconvnext.py
    
  5. エディタで,次のプログラムを保存
    このプログラムは、PyTorchとImageNetで学習済みのConvNeXtBaseモデルを活用し、カメラから取得した画像をリアルタイムで分類します。プログラムでは、GPUの設定、モデルのロード、フレームの前処理、画像分類、結果と推論に要した時間の表示を行います。カメラからの画像をリアルタイムで分類し、その結果をビジュアルに確認できるプログラムです。

    【使い方】

    1. 必要な準備

      プログラムを実行する前に、必要なライブラリ(PyTorch、torchvision、OpenCV)がインストールされていることを確認してください。

    2. カメラの設定

      プログラムはデフォルトでカメラデバイス0を使用します。 異なるカメラを使用する場合は、cv2.VideoCapture(0)の引数を適切なデバイスIDに変更してください。

    3. GPUの使用

      プログラムは、利用可能な場合はGPUを使用します。 GPUが利用可能でない場合は、自動的にCPUにフォールバックします。

    4. プログラムの実行

      プログラムを実行すると、カメラからのリアルタイム画像分類が開始されます。 分類結果、信頼度、推論時間、フレームレートが画面上に表示されます。

    5. キー操作:

      'q'キーを押すとプログラムが終了します。 'p'キーを押すと、画像の分類を一時停止/再開できます。

    import torch
    import torchvision.models as models
    from torchvision.models import ConvNeXt_Base_Weights
    import cv2
    import time
    import numpy as np
    
    # ==== 設定 ====
    FPS_BUFFER_SIZE = 10
    # =============
    
    # ImageNet のクラス名(学習済み重みに付属するメタ情報から取得)
    weights = ConvNeXt_Base_Weights.DEFAULT
    imagenet_labels = weights.meta["categories"]
    preprocess = weights.transforms()
    
    def load_model(device: torch.device) -> torch.nn.Module:
        model = models.convnext_base(weights=weights)
        model.eval()
        model.to(device)
        return model
    
    def print_model_info(model: torch.nn.Module) -> None:
        num_classes = model.classifier[2].out_features
        print("Model: convnext_base")
        print("Pretrained dataset: ImageNet")
        print(f"Number of classes: {num_classes}")
    
    def preprocess_image(img: np.ndarray) -> torch.Tensor:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        tensor = torch.from_numpy(img).permute(2, 0, 1)
        tensor = preprocess(tensor)
        return tensor.unsqueeze(0)
    
    def classify_image(model: torch.nn.Module, img: torch.Tensor, device: torch.device):
        with torch.no_grad():
            img = img.to(device)
            outputs = model(img)
            probs = torch.softmax(outputs, dim=1)
            confidence, pred = torch.max(probs, 1)
            class_name = imagenet_labels[pred.item()]
        return class_name, confidence.item()
    
    def update_fps(fps_buffer, prediction_time):
        fps_buffer.append(prediction_time)
        if len(fps_buffer) > FPS_BUFFER_SIZE:
            del fps_buffer[0]
        return len(fps_buffer) / sum(fps_buffer)
    
    def display_results(frame, class_name, confidence, prediction_time, fps):
        cv2.putText(frame, f"Class: {class_name}", (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"Confidence: {confidence:.4f}", (10, 70),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"Time: {prediction_time:.4f} seconds", (10, 110),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"FPS: {fps:.2f}", (10, 150),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    
    def classify_camera_frames(model: torch.nn.Module, device: torch.device) -> None:
        cap = cv2.VideoCapture(0)
        if not cap.isOpened():
            print("Error opening camera")
            return
    
        fps_buffer = []
        paused = False
    
        while cap.isOpened():
            if not paused:
                ret, frame = cap.read()
                if not ret:
                    print("Error reading frame from camera")
                    break
    
                img = preprocess_image(frame)
                start_time = time.perf_counter()
                class_name, confidence = classify_image(model, img, device)
                prediction_time = time.perf_counter() - start_time
                fps = update_fps(fps_buffer, prediction_time)
                display_results(frame, class_name, confidence, prediction_time, fps)
    
            cv2.imshow("Camera Classification", frame)
    
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == ord('p'):
                paused = not paused
    
        cap.release()
        cv2.destroyAllWindows()
    
    def main():
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        print(f"Using device: {device}")
    
        model = load_model(device)
        print_model_info(model)
        classify_camera_frames(model, device)
    
    if __name__ == '__main__':
        main()
    
  6. Python プログラムの実行

    プログラムを pyconvnext.pyのようなファイル名で保存したので, 「python pyconvnext.py」のようなコマンドで行う.

    python pyconvnext.py
    
  7. 結果の確認

    終了は q キー

【まとめ】 WindowsでのPyTorch 2.3のインストールから,GPUとCPUの性能比較,高度な画像分類タスクまでの一連のプロセスを説明.