1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

image.png

機械学習やディープラーニングの作業において、GPUのリソース使用状況を把握することは非常に重要です。特にGoogle ColabやJupyter Notebookでの作業中に、GPU使用率やメモリ使用量をリアルタイムで監視できると、モデルの学習状況や処理効率の改善に役立ちます。

この記事では、GPUutilライブラリを使ってGoogle ColabでGPU監視を行う方法を、実際に動作するサンプルコードとともに紹介します。

Google Colabでの準備

この記事の動作確認はランタイムのタイプをT4 GPUを指定して動作確認しています。
image.png

GPU環境の有効化と確認

# GPU環境の確認
!nvidia-smi

# GPUutilのインストール
!pip install GPUtil

image.png

1. 基本的なGPU情報取得

import GPUtil
import time

def show_gpu_status():
    """GPU基本情報と現在の使用状況を表示"""
    print("=== GPU情報 ===")
    
    gpus = GPUtil.getGPUs()
    
    if not gpus:
        print("GPUが見つかりません")
        return
    
    for gpu in gpus:
        print(f"GPU: {gpu.name}")
        print(f"  GPU使用率: {gpu.load * 100:.1f}%")
        print(f"  メモリ使用率: {gpu.memoryUtil * 100:.1f}%")
        print(f"  使用中メモリ: {gpu.memoryUsed:.0f} MB / {gpu.memoryTotal:.0f} MB")
        print(f"  温度: {gpu.temperature}°C")

show_gpu_status()

image.png

2. GPU使用状況の可視化

def gpu_progress_bar():
    """GPU使用状況をプログレスバー形式で表示"""
    def create_progress_bar(percentage, length=40):
        filled = int(length * percentage / 100)
        bar = '' * filled + '' * (length - filled)
        return f"[{bar}] {percentage:.1f}%"
    
    gpus = GPUtil.getGPUs()
    
    if not gpus:
        return
    
    for gpu in gpus:
        gpu_usage = gpu.load * 100
        memory_usage = gpu.memoryUtil * 100
        
        print(f"GPU: {gpu.name}")
        print(f"  GPU使用率:  {create_progress_bar(gpu_usage)}")
        print(f"  メモリ使用率: {create_progress_bar(memory_usage)}")
        print(f"  温度: {gpu.temperature}°C")

gpu_progress_bar()

image.png

3. リアルタイム監視とグラフ表示

import matplotlib.pyplot as plt
from IPython.display import clear_output
from collections import deque

# 日本語フォント設定(オプション)
# plt.rcParams['font.family'] = 'DejaVu Sans'

class GPUMonitor:
    """リアルタイムGPU監視クラス"""
    
    def __init__(self, max_points=30):
        self.max_points = max_points
        self.gpu_usage = deque(maxlen=max_points)
        self.memory_usage = deque(maxlen=max_points)
        self.temperatures = deque(maxlen=max_points)
    
    def update_and_plot(self):
        """GPU情報を更新してプロット"""
        gpus = GPUtil.getGPUs()
        
        if not gpus:
            print("GPUが見つかりません")
            return False
        
        gpu = gpus[0]
        
        # データ更新
        self.gpu_usage.append(gpu.load * 100)
        self.memory_usage.append(gpu.memoryUtil * 100)
        self.temperatures.append(gpu.temperature)
        
        # プロット
        clear_output(wait=True)
        
        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4))
        
        # GPU使用率
        ax1.plot(self.gpu_usage, 'b-', linewidth=2)
        ax1.set_title('GPU Usage')
        ax1.set_ylabel('Usage (%)')
        ax1.set_ylim(0, 100)
        ax1.grid(True, alpha=0.3)
        
        # メモリ使用率
        ax2.plot(self.memory_usage, 'r-', linewidth=2)
        ax2.set_title('Memory Usage')
        ax2.set_ylabel('Usage (%)')
        ax2.set_ylim(0, 100)
        ax2.grid(True, alpha=0.3)
        
        # 温度
        ax3.plot(self.temperatures, 'g-', linewidth=2)
        ax3.set_title('GPU Temperature')
        ax3.set_ylabel('Temperature (C)')
        ax3.grid(True, alpha=0.3)
        
        plt.tight_layout()
        plt.show()
        
        # 現在の状況を表示
        print(f"現在: GPU {self.gpu_usage[-1]:.1f}% | "
              f"メモリ {self.memory_usage[-1]:.1f}% | "
              f"温度 {self.temperatures[-1]}°C")
        
        return True

# 使用例:5回データを取得してプロット
monitor = GPUMonitor()
for i in range(5):
    monitor.update_and_plot()
    time.sleep(2)

image.png

4. 実用的な監視ツール

GPU監視ダッシュボード

import datetime

def gpu_dashboard():
    """簡潔なGPU監視ダッシュボード"""
    gpus = GPUtil.getGPUs()
    
    if not gpus:
        print("GPUが見つかりません")
        return
    
    print(f"=== GPU監視 - {datetime.datetime.now().strftime('%H:%M:%S')} ===")
    
    for gpu in gpus:
        gpu_usage = gpu.load * 100
        memory_usage = gpu.memoryUtil * 100
        
        # ステータス判定
        if gpu_usage > 80:
            status = "🔥 高負荷"
        elif gpu_usage > 30:
            status = "⚡ 動作中"
        else:
            status = "💤 待機中"
        
        print(f"{gpu.name} {status}")
        print(f"  GPU: {gpu_usage:.1f}% | メモリ: {memory_usage:.1f}% | 温度: {gpu.temperature}°C")
        print(f"  メモリ: {gpu.memoryUsed:.0f}MB / {gpu.memoryTotal:.0f}MB")

gpu_dashboard()

image.png

アラートシステム

def gpu_alert():
    """GPU使用量アラート"""
    gpus = GPUtil.getGPUs()
    alerts = []
    
    if not gpus:
        return
    
    for gpu in gpus:
        gpu_usage = gpu.load * 100
        memory_usage = gpu.memoryUtil * 100
        
        if gpu_usage > 90:
            alerts.append(f"⚠️ GPU使用率が高いです: {gpu_usage:.1f}%")
        if memory_usage > 85:
            alerts.append(f"⚠️ メモリ使用率が高いです: {memory_usage:.1f}%")
        if gpu.temperature > 80:
            alerts.append(f"🌡️ GPU温度が高いです: {gpu.temperature}°C")
    
    if alerts:
        print("🚨 アラート:")
        for alert in alerts:
            print(f"  {alert}")
    else:
        print("✅ GPU正常")

gpu_alert()

image.png

5. 機械学習での活用

def monitor_training():
    """学習中のGPU監視例"""
    import torch
    
    if not torch.cuda.is_available():
        print("CUDAが利用できません")
        return
    
    # ダミーの学習処理
    device = torch.device('cuda')
    x = torch.randn(1000, 1000, device=device)
    y = torch.randn(1000, 1000, device=device)
    
    print("=== 学習中のGPU監視 ===")
    
    for epoch in range(5):
        # 計算処理
        result = torch.mm(x, y)
        
        # GPU状況を監視
        gpus = GPUtil.getGPUs()
        if gpus:
            gpu = gpus[0]
            print(f"Epoch {epoch+1}: GPU {gpu.load*100:.1f}% | "
                  f"Memory {gpu.memoryUtil*100:.1f}% | "
                  f"Temp {gpu.temperature}°C")
        
        time.sleep(1)

monitor_training()

image.png

6. 継続監視

def continuous_monitor(duration=30, interval=5):
    """指定時間の継続監視"""
    start_time = time.time()
    end_time = start_time + duration
    
    print(f"=== {duration}秒間GPU監視開始 ===")
    
    try:
        while time.time() < end_time:
            clear_output(wait=True)
            gpu_dashboard()
            gpu_alert()
            
            remaining = int(end_time - time.time())
            print(f"残り: {remaining}")
            time.sleep(interval)
            
    except KeyboardInterrupt:
        print("監視中断")
    
    print("監視終了")

# 使用例(コメントアウト)
# continuous_monitor(30, 5)

image.png

まとめ

image.png

GPUutilを使えば、Python環境から手軽にGPUの使用状況を監視できます。特に機械学習の現場では、モデル学習中のリソース使用状況の把握やGPU使用効率の最適化、メモリ不足・過熱の早期発見などに役立ちます。

また、Google ColabのようなGPU環境でも、リアルタイムでGPUの使用状況を確認できるため、処理を効率化し、無駄な計算資源の消費を抑えることが可能です。

シンプルなコードで導入できるため、機械学習プロジェクトにおけるGPU監視ツールとして、ぜひ活用してみてください。

参考情報

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?