习题
不用查资料,凭这一章学到的东西做。
基础
1. 造一个 3×4 的张量,元素全是 2.5
2. 下面的形状分别是什么
a = torch.randn(4)
a.shape # ?
a.unsqueeze(0).shape # ?
a.unsqueeze(1).shape # ?
b = torch.randn(2, 1, 3)
b.squeeze().shape # ?3. 哪些能相加,哪些报错
(3, 4) + (4,) # ?
(3, 4) + (3,) # ?
(3, 1) + (1, 4) # ?
(2, 3, 4) + (4,) # ?动手
基础过了,开始写代码。
4. 不用 keepdim,让这段代码能跑
X = torch.randn(5, 3)
X - X.mean(dim=1) # 报错,改成对的两种改法各写一遍。
5. 求梯度
x = torch.tensor([2., 3., 4.], requires_grad=True)
y = (x ** 3).sum()
y.backward()x.grad 是什么?先自己算,再跑代码验证。
6. 搬到 GPU 再搬回来
造一个 100×100 的随机张量,搬到 GPU,平方,再搬回 CPU 转成 numpy。
思考
代码写完了,几道题检验理解深度。
7. 为什么默认 float32
如果用 float64,一个 1000×1000 的参数矩阵要占多少显存?float32 呢?
8. 小张量上 GPU 到底快不快
跑下面这段,把实际数字填进表里:
import torch, time
for n in [10, 100, 1000, 4000]:
a = torch.randn(n, n)
b = torch.randn(n, n)
t = time.perf_counter()
for _ in range(100):
a @ b
cpu = time.perf_counter() - t
a, b = a.cuda(), b.cuda()
torch.cuda.synchronize()
t = time.perf_counter()
for _ in range(100):
a @ b
torch.cuda.synchronize()
gpu = time.perf_counter() - t
print(f"n={n:<5} cpu={cpu:.4f}s gpu={gpu:.4f}s gpu/cpu={gpu/cpu:.2f}")n | CPU | GPU | 谁快 |
|---|---|---|---|
10 | |||
100 | |||
1000 | |||
4000 |
然后回答:从多大的矩阵开始 GPU 才划算?为什么小矩阵反而不如 CPU? 如果把循环次数从 100 改成 1,结论会变吗(想想同步开销)?
9. 这个报错什么意思
RuntimeError: Expected all tensors to be on the same device,
but found at least two devices, cuda:0 and cpu!列出三种可能导致它的写法。
参考答案要点
题 | 要点 |
|---|---|
1 |
|
2 |
|
3 | ✓ / ✗(4 vs 3)/ ✓ / ✓ |
4 |
|
5 |
|
6 |
|
7 | float64 是 8 字节,1000×1000 = 8 MB;float32 是 4 MB |
8 | 张量很小、搬运开销大于计算;或数据本来就在 CPU、来回搬更亏 |
9 | 模型在 GPU 输入没搬 / 输入在 GPU 标签没搬 / 循环里新造的张量默认在 CPU |
下一章
张量能记梯度,但这一章只是"知道有这个功能"。
下一章拆开看:PyTorch 到底怎么记住每一步运算的。