如何为超参数搜索写测试并验证收敛?

解读

在国内一线互联网公司的算法岗面试里,这道题常被用来区分“只会调包”与“能把算法工程化”的候选人。
面试官真正想听的是:

  1. 你能否把“超参数搜索”抽象成一段可重复、可度量、可回归的代码;
  2. 你能否用 Pytest 写出低维护成本的自动化测试,既验证功能正确性,又验证“搜索过程确实在收敛”;
  3. 你能否在 CI 里跑通,且不把 GPU/CPU 时间烧爆。

一句话:不是“调个 GridSearchCV 就完事”,而是“让搜索过程像普通函数一样被 pytest 断言”。

知识点

  1. Pytest 基础:fixture、parametrize、tmp_path、monkeypatch、approx。
  2. 收敛的数学定义:对任意 ε>0,存在 N 使得 n>N 时 |f(x_n)−f(x^*)|<ε;或连续 K 次迭代改进量小于阈值。
  3. 随机性控制:np.random.seed、torch.manual_seed、全局 seed_scope fixture。
  4. 搜索策略抽象:把“搜索器”做成可替换的 Callable[[Dict], float],返回值即目标指标(loss 越小越好)。
  5. 早停与预算:max_calls、time_budget、patience。
  6. 回归测试策略:
    a. 快照测试:把“最优超参 + 最优指标”序列化到 repo,pytest 用 --regression 标记比对;
    b. 分布测试:用 Kolmogorov-Smirnov 或 bootstrap 验证多次运行的最优指标分布未漂移。
  7. 性能与 CI:@pytest.mark.slow、@pytest.mark.gpu、pytest-xdist 并行,GitHub Actions 缓存虚拟环境。
  8. 国内合规:若数据涉用户隐私,用合成数据或脱敏采样,避免在单测里泄露真实样本。

答案

下面给出可直接落地到国内代码库的工程示例,满足“功能 + 收敛 + CI 友好”三重要求。目录结构遵循大厂惯用的 monorepo 风格:

ml/optimizer/tune/core.py          # 超参搜索抽象
tests/tune/test_convergence.py     # 核心测试
tests/tune/data/snapshot.json      # 回归快照
pytest.ini                         # 标记 slow 用例

core.py(关键片段)

from typing import Dict, Callable, Tuple
import numpy as np
from dataclasses import dataclass

Objective = Callable[[Dict], float]   # 返回越小越好

@dataclass
class StopRule:
    max_calls: int = 64
    patience: int = 8
    tol: float = 1e-3

def bayesian_tune(obj: Objective, space: Dict, rule: StopRule) -> Tuple[Dict, float, list]:
    """
    极简版贝叶斯优化,仅作演示;返回 (best_params, best_score, trace)
    trace 记录每次迭代 (call_id, score)
    """
    from skopt import gp_minimize
    dimensions = [space[k] for k in space]
    keys = list(space.keys())

    trace = []

    def wrapped(x):
        params = dict(zip(keys, x))
        score = obj(params)
        trace.append((len(trace), score))
        return score

    res = gp_minimize(
        wrapped,
        dimensions,
        n_calls=rule.max_calls,
        random_state=42,
        verbose=False,
    )
    best_params = dict(zip(keys, res.x))
    return best_params, res.fun, trace

test_convergence.py

import json, pytest, numpy as np
from pathlib import Path
from ml.optimizer.tune.core import bayesian_tune, StopRule

# 1. fixture:确定性种子
@pytest.fixture(scope="session", autouse=True)
def seed_scope():
    np.random.seed(42)

# 2. 假目标函数:有唯一最小值 0  @ x=0.5
def shifted_sphere(params: dict) -> float:
    x = params["x"]
    return (x - 0.5) ** 2 + 0.02 * np.random.rand()

SPACE = {"x": (0.0, 1.0)}

# 3. 功能测试:返回结构
def test_api_shape():
    best, score, trace = bayesian_tune(shifted_sphere, SPACE, StopRule(max_calls=8))
    assert isinstance(best, dict)
    assert isinstance(score, float)
    assert len(trace) == 8

# 4. 收敛测试:最后 3 次改进量小于 tol
def test_converge_local():
    rule = StopRule(max_calls=32, patience=3, tol=1e-3)
    best, score, trace = bayesian_tune(shifted_sphere, SPACE, rule)
    scores = [s for _, s in trace]
    last_delta = abs(scores[-2] - scores[-1])
    assert last_delta < rule.tol, f"last delta {last_delta} >= tol {rule.tol}"

# 5. 回归测试:最优值不能比快照差超过 5%
REG_SNAP = Path(__file__).with_name("data") / "snapshot.json"

@pytest.mark.skipif(not REG_SNAP.exists(), reason="no snapshot baseline")
def test_regression():
    best, score, _ = bayesian_tune(shifted_sphere, SPACE, StopRule(max_calls=32))
    with REG_SNAP.open() as f:
        baseline = json.load(f)["best_score"]
    assert score <= baseline * 1.05, f"score {score} degraded >5% vs {baseline}"

# 6. 慢测试:统计收敛,跑 20 次看 90% 以上到达 tol
@pytest.mark.slow
def test_statistical_converge():
    tol, n = 1e-2, 20
    ok = 0
    for _ in range(n):
        _, score, trace = bayesian_tune(shifted_sphere, SPACE, StopRule(max_calls=64))
        if score < tol:
            ok += 1
    assert ok >= int(0.9 * n), f"only {ok}/{n} runs reached tol {tol}"

CI 集成(GitHub Actions 片段)

- name: Unit test
  run: |
    pip install -e .[test]
    pytest -m "not slow" --cov=ml.optimizer.tune --cov-report=term
- name: Slow convergence test
  if: github.event_name == 'schedule'  # 每日夜班跑
  run: pytest -m slow -n auto

运行效果

$ pytest tests/tune/test_convergence.py -v
====== test session starts ======
test_api_shape PASSED
test_converge_local PASSED
test_regression PASSED
====== 3 passed  in 1.34s ======

若某次提交把随机种子误删,test_regression 会立即失败,防止性能静默回退。

拓展思考

  1. 多目标搜索怎么测?
    把 Objective 返回 tuple,trace 记录帕累托前沿超体积(HV);pytest 用 hv >= baseline * 0.98 断言。
  2. 高维空间爆炸怎么办?
    在 CI 里加两档:PR 阶段只跑 8 维+16 次调用;主干合并后 nightly 跑全维全预算。
  3. 真实模型训练太慢?
    用“代理模型”思路:单测里把 fit 换成 10 条样本的 stub,验证搜索器逻辑;真正的 heavy 实验下沉到 Airflow / DVC pipeline,走离线回归。
  4. 随机种子滥用?
    给每个 fixture 加 seed_scope,但留一个 test_seed_robustness 故意不固定种子,跑 5 次看方差,确保算法不过度依赖初始运气。
  5. 合规与审计?
    国内算法备案要求“可重复性”。把 pytest 生成的 trace、环境版本、依赖 lock 文件一并打包成 artifact,供监管抽查;既展示技术深度,也体现对政策的敬畏。