当 GPU 不足时,如何自动降级为 CPU 并跳过部分测试?
解读
国内互联网公司普遍采用“GPU 弹性池”+“CI 共享集群”的混合模式,白天 GPU 被训练任务占满,夜间才空出卡。面试时,面试官想确认三点:
- 你能否在测试代码里“感知”GPU 可用性,而不是写死 skip;
- 你能否让“GPU 测试”与“CPU 测试”共用同一套用例,避免维护两份代码;
- 你能否让降级行为对开发者透明,CI 日志里一眼看出“哪些用例因 GPU 不足被跳过”,方便后续重跑。
因此,回答必须围绕“自动感知 + 条件跳过 + 统一 fixture”展开,并给出可在 Jenkins/GitHub Actions 里直接落地的代码片段。
知识点
- pytest 的 fixture 作用域与依赖注入:autouse=True 的 session 级 fixture 可在所有用例开始前完成 GPU 检测。
- pytest.skip() 与 pytest.importorskip() 的区别:前者可在任意逻辑分支里动态调用,后者用于模块级别。
- 自定义 marker(pytest.mark.gpu)与 pytest.ini 的 markers 声明,保证 -m gpu 参数化运行时不报警告。
- 通过“fixture 回退”技巧:gpu_device fixture 返回 torch.device("cuda") 或 torch.device("cpu"),测试函数只关心 device,不关心背后资源。
- 利用 pytest 的 stash(pytestconfig.stash)做进程级缓存,避免每轮测试都执行 nvidia-smi,提升 CI 效率。
- 与 xdist 并行兼容:session 级 fixture 在 master 节点执行一次,worker 通过 stash 读取结果,防止重复检测。
答案
- 在项目根目录创建 conftest.py,实现“GPU 可用性”统一检测:
# conftest.py
import subprocess
import pytest
import torch
def detect_gpu_available() -> bool:
"""检查是否有空闲 GPU,符合国内 CI 实际:先查 nvidia-smi,再试能否初始化 cuda。"""
try:
# 1. 驱动层面
r = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True)
if r.returncode != 0:
return False
# 2. PyTorch 层面
return torch.cuda.is_available() and torch.cuda.device_count() > 0
except Exception:
return False
@pytest.fixture(scope="session", autouse=True)
def _global_gpu_check(pytestconfig):
"""只在 master 节点执行一次,结果存入 stash,供所有 worker 共享。"""
if not hasattr(pytestconfig, "stash"):
pytestconfig.stash = {}
if "gpu_ok" not in pytestconfig.stash:
pytestconfig.stash["gpu_ok"] = detect_gpu_available()
return pytestconfig.stash["gpu_ok"]
@pytest.fixture
def device(request, pytestconfig):
"""测试函数只关心 device,自动降级。"""
gpu_ok = pytestconfig.stash.get("gpu_ok", False)
if request.node.get_closest_marker("gpu") and not gpu_ok:
pytest.skip("GPU 不可用,自动跳过 GPU 测试")
return torch.device("cuda" if gpu_ok else "cpu")
- 在 pytest.ini 注册 marker,避免警告:
[pytest]
markers =
gpu: 需要 GPU 的测试
- 测试层零改造,仅加标记:
# test_model.py
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(3, 8, 3)
@pytest.mark.gpu
def test_net_forward(device):
net = Net().to(device)
x = torch.randn(2, 3, 32, 32).to(device)
y = net(x)
assert y.shape == (2, 8, 30, 30)
- CI 层零额外配置,直接跑:
pytest -m "gpu or not gpu" --tb=short
当 GPU 被占满时,nvidia-smi 检测失败,pytest 自动跳过带 @pytest.mark.gpu 的用例,其余用例在 CPU 上完成;夜间 GPU 空闲时,同一命令又会全量跑在 GPU 上,实现“一套代码,两种资源”。
拓展思考
- 重跑策略:可在 CI 里加
--last-failed,把因 GPU 不足被跳过的用例单独重跑;结合pytest-rerunfailures插件,实现“GPU 测试失败时自动重试 2 次,仍失败再降级”。 - 资源配额精细化:将 detect_gpu_available 升级为“显存大于 6G 且利用率 <30% 才算可用”,避免抢到卡却显存不足导致 OOM。
- 与容器平台对接:在阿里 PAI-DSW、腾讯 TI-ONE 等国内平台,可通过平台 API 先申请 GPU 配额,申请不到再回退 CPU,实现“测试任务主动退让”。
- 多卡并行:借助 pytest-xdist 的
--dist=loadgroup,把 GPU 测试分到独立 worker 组,CPU 测试分到另一组,互不阻塞,提高 CI 吞吐。 - 生成测试报告:使用 pytest-html 插件,在报告里单独列出“Skipped due to GPU unavailable”,方便测试经理一眼看出资源瓶颈,推动扩容。