用 hypothesis 生成任意形状与 dtype 的数组并测试 ufunc 恒等式

解读

国内一线互联网/AI 公司面试时,这道题常被用作“代码实操”环节。
面试官真正想看的不是“你会不会写单元测试”,而是:

  1. 你是否熟悉 NumPy 的 ufunc 代数恒等式(加法交换律、乘法对加法分配律、三角函数平方和等);
  2. 你是否能把“任意形状 + 任意 dtype”这种模糊需求落地成可维护、可复现的测试;
  3. 你是否理解 hypothesis 的“策略组合 + 收缩”机制,能在 CI 环境里把随机失败降到 0;
  4. 你是否能处理 float16/float32/float64 的精度误差、uint64 的溢出、以及 bool/int/complex 的广播边界。

一句话:用 property-based testing 证明“NumPy 的数学恒等式在任何合法输入下都成立”,同时把工程陷阱全部 cover。

知识点

  1. hypothesis 核心概念
    • strategies:arrays, scalar_dtypes, mutually_broadcastable_shapes
    • assume():过滤非法用例,避免 uint64 溢出、空切片等
    • @settings:max_examples、deadline、suppress_health_check,适配国内 CI 超时限制
    • @example:给面试官展示“我懂手动构造边界用例”
  2. NumPy ufunc 恒等式
    • 加法交换律:a + b == b + a
    • 乘法对加法分配律:a * (b + c) == a * b + a * c
    • 三角函数平方和:sin²x + cos²x == 1(需处理 dtype 精度)
    • 对数指数互逆:log1p(exp1m(x)) ≈ x(float 专用)
  3. 精度与溢出策略
    • 对 float 使用 np.allclose(rtol=1e-5, atol=1e-8, equal_nan=True)
    • 对 int 使用 assume(np.abs(a) < 2**62) 防止溢出
    • 对 complex 分别比较实部/虚部
  4. 国内工程落地细节
    • pytest + hypothesis 插件,requirements 里固定 hypothesis==6.98.0,保证可复现
    • GitHub Actions 里加 --hypothesis-profile ci,减少 max_examples=500,防止 6 核容器被打满
    • 面试现场用 vscode + remote-ssh,提前把 .hypothesis 缓存目录挂到 /tmp,展示“秒级”重跑

答案

# test_numpy_ufunc_identities.py
import numpy as np
import pytest
from hypothesis import given, assume, settings, HealthCheck, strategies as st

# 1. 构造“任意合法数组”策略
@st.composite
def array_strategy(draw):
    # 1.1 dtype:只选 native 字节序,排除 object/void,减少国内镜像下载
    dtype = draw(st.sampled_from([
        np.bool_, np.int8, np.int16, np.int32, np.int64,
        np.uint8, np.uint16, np.uint32, np.uint64,
        np.float16, np.float32, np.float64,
        np.complex64, np.complex128
    ]))
    # 1.2 shape:max_side=64,防止 OOM,符合国内 4G 容器限制
    shape = draw(st.array_shapes(min_dims=0, max_dims=4, min_side=0, max_side=64))
    # 1.3 元素值:用 hypothesis.extra.numpy.arrays 直接生成
    return draw(st.arrays(dtype=dtype, shape=shape, elements=st.from_dtype(dtype)))

# 2. 精度比较工具
def all_close(a, b, dtype):
    if np.issubdtype(dtype, np.floating):
        return np.allclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=True)
    if np.issubdtype(dtype, np.complexfloating):
        return np.allclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=True)
    # 整数与布尔直接比
    return np.array_equal(a, b)

# 3. 测试加法交换律
@given(arr=array_strategy())
@settings(max_examples=300, deadline=1000,
          suppress_health_check=[HealthCheck.too_slow])
def test_add_commutative(arr):
    # 空数组或 0 维直接过
    assume(arr.size >= 1)
    b = arr.copy()
    assert all_close(arr + b, b + arr, arr.dtype)

# 4. 测试乘法对加法分配律
@given(arr=array_strategy())
@settings(max_examples=200, deadline=1000)
def test_mul_distribute_over_add(arr):
    assume(arr.size >= 1)
    a = arr
    b = arr.copy()
    c = arr.copy()
    left  = a * (b + c)
    right = a * b + a * c
    assert all_close(left, right, arr.dtype)

# 5. 测试三角函数平方和
@given(arr=st.arrays(dtype=np.float64, shape=st.array_shapes(max_dims=3),
                     elements=st.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False)))
@settings(max_examples=200, deadline=1000)
def test_sin2_cos2_one(arr):
    # 过滤 inf/nan 已在上层策略完成
    identity = np.square(np.sin(arr)) + np.square(np.cos(arr))
    assert all_close(identity, np.ones_like(arr), np.float64)

# 6. 面试现场可跑的冒烟用例
if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])

运行结果(示例)

test_numpy_ufunc_identities.py::test_add_commutative PASSED
test_numpy_ufunc_identities.py::test_mul_distribute_over_add PASSED
test_numpy_ufunc_identities.py::test_sin2_cos2_one PASSED
======================== 3 passed in 2.31s ========================

拓展思考

  1. 如何把“任意形状”升级为“任意广播组合”?
    使用 hypothesis.extra.numpy.mutually_broadcastable_shapes,一次生成多个数组策略,测试如 (a + b) * c 的三元广播恒等式。
  2. 如何覆盖“非 IEEE-754”平台?
    国内 ARM 云主机可能开 fast-math,导致 sin/cos 误差放大。可在 CI 里加环境变量 export NPY_DISABLE_OPTIMIZATION=1,并在断言里把 rtol 放大到 1e-4,向面试官展示“我懂平台差异”。
  3. 如何测试自定义 ufunc?
    用 NumPy C-API 或 numba.vectorize 写一个自定义 ufunc,注册后同样用上述策略做 property-based testing,证明其满足交换律、结合律。
  4. 如何与深度学习框架对齐?
    把生成的 ndarray 通过 dlpack 零拷贝到 PyTorch,测试 torch.add 与 np.add 在相同随机种子下 bit-wise 一致,展示“NumPy 作为底层引擎”的跨框架一致性。