Apple Metal Performance Shi Apple Metal Pafoo Mansu

Home PDF

以下は、PyTorchを使ってMetal (GPU) のパフォーマンスをテストするためのスクリプトです。

import torch
import argparse
import time

parser = argparse.ArgumentParser(description="Test torch with MPS or CPU.")
parser.add_argument("--device", type=str, default="mps", choices=["mps", "cpu"], help="Device to use (mps or cpu)")
args = parser.parse_args()

if args.device == "mps":
    if torch.backends.mps.is_available():
        print("Metal is available")
        device = torch.device("mps")
    else:
        print("Metal is not available, using CPU instead")
        device = torch.device("cpu")
elif args.device == "cpu":
    device = torch.device("cpu")
    print("Using CPU")
else:
    print("Invalid device specified, using CPU instead")
    device = torch.device("cpu")

# 指定されたデバイスにテンソルを作成して移動
x = torch.randn(5000, 5000, device=device)
y = torch.randn(5000, 5000, device=device)

# より複雑な計算を行う
start_time = time.time()
result = torch.matmul(x, y)
for _ in range(10):
    result = torch.matmul(result, y)
end_time = time.time()

# 結果を表示
print(result)
print(f"Time taken: {end_time - start_time:.4f} seconds")

結果は、MPSがCPUの約0.2%の実行時間で動作することを示しています。

% python scripts/test_metal.py --device cpu
Time taken: 2.8784 seconds

% python scripts/test_metal.py --device mps
Time taken: 0.0061 seconds

Back 2025.02.22 Donate