如何为自定义 nn.Module 编写 pytest 并测试 forward 形状?
解读
国内一线厂面试时,这道题常被用来“筛深度”。
- 面试官想确认你能否把“模型正确性”拆成可自动化、可回归的单元测试,而不是手写脚本肉眼比对。
- 重点不在“pytest 语法”,而在“如何构造最小可重复的随机输入、如何断言张量形状、如何覆盖动态图分支、如何兼顾 CPU/GPU、如何持续集成”。
- 回答必须体现工程化思维:参数化、fixture 复用、失败信息可读、CI 无 GPU 时自动降级。
知识点
- torch.nn.Module.forward 的“形状契约”即接口文档,测试即验证契约。
- pytest 参数化:@pytest.mark.parametrize 一次覆盖多组 (batch, seq_len, in_features)。
- 使用 torch.rand / torch.randn 生成伪随机输入,配合 torch.manual_seed 保证可复现。
- 断言形状用 tensor.shape 或 tensor.size(),禁止逐元素比对,减少误报。
- 对 GPU 测试,用 pytest.mark.gpu + 自定义 fixture“device”,无 GPU 时自动 skip。
- 对动态控制流(如可变长度 RNN、Transformer mask)需额外构造边界 case:空 tensor、最大长度、奇数长度。
- 测试反向:若模块含自写 backward,需加 gradcheck;若仅测形状,可 torch.no_grad() 提速。
- CI 集成:GitHub Actions / GitLab CI 中单独 job 跑 pytest -m "not gpu",GPU 机器跑 pytest -m gpu。
答案
下面给出一个可直接落地的模板,覆盖“CPU/GPU、参数化、失败提示、CI 友好”四个维度。
# project/tests/test_myblock.py
import pytest
import torch
from my_model.blocks import MyBlock # 被测模块
def ids_fn(cfg):
"""把参数翻译成人类可读字符串,失败时一眼看出是哪组 shape。"""
return f"b{cfg['batch']}_s{cfg['seq']}_f{cfg['feat']}"
# 1. 参数化:把典型、边界、异常三种场景一次写全
configs = [
{"batch": 1, "seq": 8, "feat": 64}, # 典型
{"batch": 7, "seq": 1, "feat": 128}, # 最小 seq
{"batch": 3, "seq": 257, "feat": 32}, # 奇数长度
]
@pytest.fixture(params=configs, ids=ids_fn)
def cfg(request):
return request.param
@pytest.fixture(scope="session")
def device():
"""自动降级:优先 GPU,否则 CPU。"""
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
class TestMyBlock:
def test_forward_shape(self, cfg, device):
torch.manual_seed(42) # 可复现
module = MyBlock(d_model=cfg["feat"]).to(device)
x = torch.randn(cfg["batch"], cfg["seq"], cfg["feat"], device=device)
with torch.no_grad(): # 仅测形状,提速
y = module(x)
# 核心断言:输出与输入同形状
assert y.shape == x.shape, f"期望 {x.shape},实际 {y.shape}"
@pytest.mark.gpu
def test_forward_shape_gpu(self, cfg):
"""单独给 GPU 打标签,CI 无卡时自动跳过。"""
if not torch.cuda.is_available():
pytest.skip("CUDA not available")
self.test_forward_shape(cfg, device=torch.device("cuda"))
运行命令
# 本地
pytest -q tests/test_myblock.py
# 仅 GPU
pytest -q -m gpu tests/test_myblock.py
# CI 无 GPU
pytest -q -m "not gpu" tests/test_myblock.py
若形状不符,pytest 会打印类似
> assert y.shape == x.shape, f"期望 {x.shape},实际 {y.shape}"
E AssertionError: 期望 torch.Size([3, 257, 32]),实际 torch.Size([3, 257, 64])
一眼定位问题,无需 debug。
拓展思考
- 形状测试只是“接口契约”的最小集,后续应补充
- 数值稳定性:同样输入多次 forward,输出差值 max < 1e-6。
- 梯度测试:若模块含自写 CUDA kernel,需加 torch.autograd.gradcheck。
- 混合精度:在 amp.autocast() 下再跑一次,确认无 NaN。
- 内存泄漏:pytest 插件 pytest-monitor 或 tracemalloc,观察显存是否随 case 数线性增长。
- 对 Transformer 等可变维度(batch 维合并、seq 维合并)场景,可抽象“通用 shape fixture”:
减少重复造数据。@pytest.fixture def random_qkv(device): return torch.randn(2, 64, 128, device=device), \ torch.randn(2, 64, 128, device=device), \ torch.randn(2, 64, 128, device=device) - 若团队使用 Hydra / OmegaConf 管理实验配置,可把 shape 配置写成 YAML,pytest 自动加载,实现“测试即配置”。
- 最终目标:让“模型改动”与“单元测试”同 PR 触发,CI 一分钟内给出红绿反馈,杜绝“本地能跑、上线 shape 爆炸”的低级事故。