如何用 pytest 启动多卡训练并验证收敛?

解读

在国内互联网大厂或 AI 初创公司的面试里,这道题不是让你“写个 hello world”,而是考察三件事:

  1. 能否把“训练脚本”与“测试脚本”彻底解耦,让 pytest 只负责调度、断言与报告,而不侵入训练代码。
  2. 能否利用 pytest 的 fixture、参数化、分布式执行机制,把“多卡”这一硬件资源抽象成可复用的测试资源。
  3. 能否在 10~15 min 内给出一条可落地的 CI 命令,既能在 8×A100 机器上跑,也能在 GitHub Actions 的 2×T4 容器里跑,并且用最少 epoch 就能给出“是否收敛”的量化结论。

一句话:面试官想听的是“你怎么用 pytest 把多卡训练当成黑盒测,还要测得准、测得快、测得可迁移”。

知识点

  1. pytest-xdist:把“卡”映射成 worker,--dist=loadgroup 让每张卡跑独立进程,避免 NCCL 互相踩。
  2. pytest fixture 作用域:session 级 fixture 负责拉起 torchrun / torch.distributed.launch,module 级 fixture 负责准备同一份小数据集(如 CIFAR10 前 5 类,2000 张图),function 级 fixture 负责给每个训练进程注入不同的 rank 与 local_rank。
  3. 参数化:@pytest.mark.parametrize("lr,bs", [(1e-3,32),(3e-4,64)]) 把“学习率-批大小”网格搜索变成 N 个独立 test case,pytest-xdist 会天然并行。
  4. 收敛断言:不是等 100 epoch 结束再 assert,而是注册 PyTorch Lightning 的 Callback,每 valid 一次就往 /tmp/conv.json 写一行 {"epoch":e,"val_loss":v}。pytest 用 tail -1 拿到最后一行,断言 val_loss < 0.4 且比第 1 个 epoch 下降 30%。
  5. 超时与重试:pytest-timeout 给每个训练 case 设 15 min 硬上限;pytest-rerunfailures 对“NCCL 握手失败”这类随机错误自动重跑 2 次。
  6. 资源隔离:利用 pytest 的 --forked 或 Docker run --gpus '"device=0,1"',保证并发跑多套代码时显卡不互相污染。
  7. 报告:pytest-html + allure 生成中文报告,直接贴到飞书或企业微信,方便算法老大一眼看到“收敛/发散”趋势图。

答案

下面给出一份可直接 clone 跑通的“最小可行 Demo”,目录结构符合国内大厂惯用的 monorepo 风格:

project/ ├── train/ │ └── mnist_ddp.py # 标准 DDP 训练脚本,0 侵入 ├── tests/ │ ├── conftest.py │ └── test_converge.py ├── requirements.txt └── Makefile

train/mnist_ddp.py(核心片段)

import torch,torchvision,os,json,time
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.distributed as dist

class LitModel(torch.nn.Module):
    def __init__(self): ...
    def forward(self,x): ...

def run(rank,wsize,lr,bs,max_epoch):
    dist.init_process_group("nccl",rank=rank,world_size=wsize)
    torch.cuda.set_device(rank)
    train_loader = torch.utils.data.DataLoader(
        torchvision.datasets.MNIST(root="/tmp/mnist",download=True,
                                   transform=torchvision.transforms.ToTensor()),
        batch_size=bs, shuffle=True, num_workers=2)
    model = LitModel().cuda(rank)
    model = DDP(model, device_ids=[rank])
    opt = torch.optim.Adam(model.parameters(), lr=lr)
    loss_fn = torch.nn.CrossEntropyLoss()

    for epoch in range(max_epoch):
        model.train()
        for x,y in train_loader:
            x,y = x.cuda(rank), y.cuda(rank)
            opt.zero_grad()
            loss = loss_fn(model(x),y)
            loss.backward()
            opt.step()
        # 仅 rank0 写日志
        if rank==0:
            with open("/tmp/conv.json","a") as f:
                f.write(json.dumps({"epoch":epoch,"loss":loss.item()})+"\n")
    dist.destroy_process_group()

tests/conftest.py

import pytest,subprocess,time,os
from pathlib import Path

@pytest.fixture(scope="session",autouse=True)
def prepare_data():
    # 提前下载,避免多进程重复抢锁
    _ = torchvision.datasets.MNIST(root="/tmp/mnist",download=True)

@pytest.fixture(scope="module",params=[("1e-3",32),("3e-4",64)])
def cfg(request):
    lr,bs = request.param
    return {"lr":lr,"bs":bs,"epoch":3,"gpus":2}

@pytest.fixture
def launch_ddp(cfg):
    # 用 torchrun 启动多卡
    gpus = cfg["gpus"]
    lr  = cfg["lr"]
    bs  = cfg["bs"]
    epoch = cfg["epoch"]
    cmd = [
        "torchrun",
        f"--nproc_per_node={gpus}",
        "train/mnist_ddp.py",
        "--lr", str(lr),
        "--bs", str(bs),
        "--epoch", str(epoch)
    ]
    # pytest-xdist 下每个 worker 独立目录,避免日志互写
    log = Path(f"/tmp/conv_{lr}_{bs}.json")
    env = os.environ.copy()
    env["CONV_JSON"] = str(log)
    subprocess.run(cmd, env=env, check=True)
    return log

tests/test_converge.py

import json,pytest

def read_last_metric(log):
    with open(log) as f:
        *_, last = map(json.loads, f)
    return last

def test_loss_decrease(launch_ddp):
    log = launch_ddp
    metrics = [json.loads(l) for l in open(log)]
    first, last = metrics[0], metrics[-1]
    assert last["loss"] < 0.4, f"最终 loss {last['loss']} 未达 0.4"
    assert last["loss"] < first["loss"] * 0.7, "loss 下降不足 30%"

def test_epoch_enough(launch_ddp):
    log = launch_ddp
    metrics = [json.loads(l) for l in open(log)]
    assert len(metrics) >= 3, "epoch 数量不足"

运行命令(单台 2 卡 A100 机器)

pip install -r requirements.txt          # 含 pytest-xdist,pytest-timeout
make test

Makefile

test:
	pytest -s -q --tb=short \
	       --dist=loadgroup \
	       -n 2 \
	       --timeout=900 \
	       tests/

解释:

  • -n 2 表示起 2 个 worker,对应 2 张卡;pytest-xdist 会把两组 (lr,bs) 参数自动分到两个 worker,互不干扰。
  • timeout=900 秒防止 hanging。
  • 所有断言在 3 epoch 内完成,整轮 CI 不超过 10 min,符合国内“日构建”节奏。

拓展思考

  1. 多机多卡怎么办?
    把 torchrun 换成 torchrun --nnodes=2 --node_rank=$CI_NODE_INDEX --master_addr=$MASTER_IP ...,pytest 侧不需要改代码,只需在 CI 里把每个节点当成独立 job,最后把 /tmp/conv*.json 聚到一处再断言即可。GitHub Actions + Kubernetes 集群已能低成本模拟。

  2. 如何测“精度收敛”而不是“loss 收敛”?
    在训练脚本里同步跑 valid set,把 top1-acc 写进 conv.json;pytest 中断言“第 3 个 epoch 的 top1-acc > 95%”即可。若精度要求更高,可用早停策略:当连续 2 个 epoch 精度提升 < 0.1% 就自动结束,pytest 只需检查是否达到目标阈值。

  3. 如何同时测“性能回归”?
    在 conv.json 里加 {"epoch":e,"imgs_per_sec":ips},pytest 里断言 ips > 基线 95%,否则视为性能回退。基线值可存成 tests/baseline.json,由 CI 每日自动更新移动平均。

  4. 如何做到“零 GPU 也能跑”?
    把 fixture 里 torchrun 的判断条件换成 if os.getenv("CPU_ONLY"): import multiprocessing; multiprocessing.set_start_method("spawn") ... 用 CPU 模拟 2 进程,虽然慢,但能让应届生在笔记本上跑通全部 case,降低门槛。

  5. 与算法平台的集成
    国内不少公司用自研“训练平台”封死了 ssh 权限,只允许提交 .zip 包。此时可以把 pytest 封装成“评测镜像”,平台调用 docker run --gpus all my-pytest:v1 即可,pytest 入口用 __main__.py 保证无外部依赖。镜像里预置 /tmp/conv.json 的解析与上报脚本,直接把结果 POST 回平台,实现“黑盒评测”。

掌握以上思路,你就能在面试现场把“pytest 启动多卡训练并验证收敛”讲成一套可落地、可度量、可 CI 的工程方案,而不是简单回答“用 os.system 调一下 torchrun”。