sample-datasets / strix-halo /gpu_test.py
sayakpaul's picture
sayakpaul HF Staff
Upload gpu_test.py
89c4c11 verified
Raw
History Blame Contribute Delete
2.84 kB
"""
Small PyTorch model + training step to verify AMD GPU (ROCm) execution.
Target hardware: AMD Radeon 8060S (Strix Halo APU, gfx1151), ROCm build of PyTorch.
On ROCm builds, the AMD GPU is exposed through the CUDA API, so device name is 'cuda'.
"""
import os
import torch
import torch.nn as nn
def pick_device() -> torch.device:
if torch.cuda.is_available():
return torch.device("cuda")
raise SystemExit(
"No GPU visible to PyTorch. torch.cuda.is_available() is False.\n"
"For this Strix Halo (gfx1151) APU, try exporting "
"HSA_OVERRIDE_GFX_VERSION=11.0.0 before running."
)
class TinyNet(nn.Module):
"""A minimal MLP: 64 -> 128 -> 10."""
def __init__(self, in_features=64, hidden=128, out_features=10):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_features, hidden),
nn.ReLU(),
nn.Linear(hidden, out_features),
)
def forward(self, x):
return self.net(x)
def main():
print("=" * 60)
print("PyTorch build :", torch.__version__)
print("Built with ROCm/HIP:", torch.version.hip)
print("CUDA-API available :", torch.cuda.is_available())
print("Device count :", torch.cuda.device_count())
device = pick_device()
if device.type == "cuda":
print("GPU name :", torch.cuda.get_device_name(0))
print("HSA_OVERRIDE_GFX_VERSION =", os.environ.get("HSA_OVERRIDE_GFX_VERSION", "(unset)"))
print("=" * 60)
torch.manual_seed(0)
model = TinyNet().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
loss_fn = nn.CrossEntropyLoss()
# Synthetic classification data, created directly on the GPU.
x = torch.randn(256, 64, device=device)
y = torch.randint(0, 10, (256,), device=device)
print("\nTraining 20 steps on", device, "...")
for step in range(20):
optimizer.zero_grad()
logits = model(x)
loss = loss_fn(logits, y)
loss.backward()
optimizer.step()
if step % 5 == 0 or step == 19:
print(f" step {step:2d} loss = {loss.item():.4f}")
# Confirm tensors and compute really lived on the GPU.
assert logits.is_cuda, "logits are not on the GPU!"
torch.cuda.synchronize()
# A quick matmul to exercise the GPU compute path directly.
a = torch.randn(1024, 1024, device=device)
b = torch.randn(1024, 1024, device=device)
c = a @ b
torch.cuda.synchronize()
print("\nResult tensor device :", logits.device)
print("Matmul output device :", c.device, "| shape:", tuple(c.shape))
mem = torch.cuda.memory_allocated() / (1024 ** 2)
print(f"GPU memory allocated : {mem:.1f} MiB")
print("\n✅ SUCCESS: model trained and ran on the AMD GPU via ROCm.")
if __name__ == "__main__":
main()