“最好是为GPU内部的日志分配内存,并且只移动较大的日志”,这句话是什么意思?如何在 GPU 内部处理日志呢?
M1芯片使用GPU
device = torch.device("mps") # 指定使用 MPS 设备
Z = X.to(device) # 将 X 移动到 MPS 设备上
# X 保持在 CPU 上,Z 在 MPS 上
print(X) # 打印原始张量 X
print(Z) # 打印在 MPS 设备上的张量 Z
Mac M1 系列的芯片只有一个 集成 GPU。与传统的独立显卡不同,M1 芯片的 GPU 是 统一内存架构(UMA)的一部分,与 CPU 共享内存。因此,您不需要像使用多 GPU 设备时那样手动指定多个 GPU。
不支持 多 GPU 加速,所以 device=‘mps:0’ 中 0 是唯一的设备索引。
要确保模型和参数都在集成的GPU上
device = torch.device("mps")
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device)
X = X.to(device)
一瞬间完成的任务不会有明显的加速,等待一段时间的任务会有加速;
CPU 时间:21.5534 秒
GPU (MPS) 时间:15.4810 秒
小任务 CPU 时间:0.000382 秒
小任务 GPU (MPS) 时间:0.000853 秒
import time
# 设备配置
device_cpu = torch.device("cpu")
device_mps = torch.device("mps")
# 定义大矩阵
size = 1000
A = torch.randn(size, size)
B = torch.randn(size, size)
# 计算量大任务:CPU
start = time.time()
for _ in range(10000):
C_cpu = torch.matmul(A, B)
time_cpu = time.time() - start
print(f"CPU 时间:{time_cpu:.4f} 秒")
# 计算量大任务:MPS
A = A.to(device_mps)
B = B.to(device_mps)
start = time.time()
for _ in range(10000):
C_mps = torch.matmul(A, B)
time_mps = time.time() - start
print(f"GPU (MPS) 时间:{time_mps:.4f} 秒")
# 计算量小任务对比
A_small = torch.randn(10, 10).to(device_cpu)
B_small = torch.randn(10, 10).to(device_cpu)
start = time.time()
torch.matmul(A_small, B_small)
print(f"小任务 CPU 时间:{time.time() - start:.6f} 秒")
A_small = A_small.to(device_mps)
B_small = B_small.to(device_mps)
start = time.time()
torch.matmul(A_small, B_small)
print(f"小任务 GPU (MPS) 时间:{time.time() - start:.6f} 秒")
问题四无法在我的设备上做到