运行时环境层
检测Intel GPU是否可用,并在GPU上执行一个简单的矩阵乘法操作,同时打印设备的详细信息和运算结果。
- torch.xpu.get_device_name(device): 获取当前设备的名称。返回的设备名称会显示出来。
- torch.xpu.get_device_properties(device): 获取该设备的详细信息,例如总内存等。
- device_properties.total_memory:设备的总内存(以字节为单位),此处将其转换为GB并输出。
- torch.randn(1000, 1000, device=device): 创建两个1000x1000的随机张量tensor_a和tensor_b,并将它们分配到Intel GPU上(通过device=device指定设备)。这些张量在XPU上进行初始化,意味着所有后续的计算都将在XPU上执行。
- torch.matmul(tensor_a, tensor_b): 进行矩阵乘法运算。此运算也将在Intel GPU上进行。
- result.shape: 打印矩阵乘法结果的形状,这里应该是(1000, 1000)。result.sum().item(): 计算并打印结果张量所有元素的总和。
import torch
import intel_extension_for_pytorch as ipex
# 检查当前是否支持Intel GPU
if torch.xpu.is_available():
device = torch.device("xpu")
print("Intel GPU is available.")
# 获取设备名称
device_name = torch.xpu.get_device_name(device)
print(f"Device Name: {device_name}")
# 打印更多设备信息
device_properties = torch.xpu.get_device_properties(device)
print("Detailed Device Information:")
print(f" - Total Memory: {device_properties.total_memory / (1024 ** 3):.2f} GB")
print("Intel GPU is available. Running on:", torch.xpu.get_device_name(device))
# 创建两个随机张量并移动到 Intel GPU
tensor_a = torch.randn(1000, 1000, device=device)
tensor_b = torch.randn(1000, 1000, device=device)
# 在GPU上进行矩阵乘法
result = torch.matmul(tensor_a, tensor_b)
# 打印结果的一些信息
print(f"Result shape: {result.shape}")
print(f"Sum of elements: {result.sum().item()}")
else:
print("Intel GPU is not available.")
结果
Intel GPU is available.
Device Name: Intel(R) Arc(TM) A770 Graphics
Detailed Device Information:
- Total Memory: 15.11 GB
Intel GPU is available. Running on: Intel(R) Arc(TM) A770 Graphics
Result shape: torch.Size([1000, 1000])
Sum of elements: 24389.48828125