编写一个 float8_e4m3 自定义 DType 并注册 ufunc 以支持 np.add

解读

国内一线大厂(阿里、字节、华为昇腾、寒武纪)在 AI 加速芯片上普遍引入 float8_e4m3(4 位指数、3 位尾数、隐式 1 位符号,共 8 位)作为推理精度。NumPy 官方主线尚未支持该类型,因此面试常要求候选人“徒手”实现一套最小可用闭环:

  1. 用 Cython/C 定义底层 1 字节存储格式;
  2. 继承 np.dtype 注册新 DType;
  3. 实现 cast、can-cast、promotion 规则,保证与 float32 互转;
  4. 为 np.add 注册 ufunc 循环,支持 (e4m3, e4m3)->e4m3 与 (e4m3, float32)->float32 两种签名;
  5. 保证在 Python 层可 np.add(a, b) 直接调用,且 __array_ufunc__ 路径不崩。

面试官重点考察:

  • 是否理解 NumPy DType 的“三件套”:PyArray_Descr、PyArray_ArrFuncs、PyUFuncGenericFunction;
  • 是否能把 float8 的 rounding-mode、subnormal、NaN 行为说清;
  • 是否能在 30 min 内给出可编译的最小 demo,而不是背 API。

知识点

  1. NumPy DType 体系

    • 静态 dtype 结构体:PyArray_Descr,关键字段 elsize=1, kind='V', type_num 需动态申请;
    • ArrFuncs:nonzero、copyswap、cast 等 22 个函数指针;
    • DTypeMeta(3.0 后)允许纯 Python 派生,但国内生产环境仍多用 1.19+,需用 C。
  2. float8_e4m3 格式

    • bias=7,exp 范围 0…15,其中 0 表示 subnormal,15 表示 inf/NaN;
    • 尾数 3 位,隐式前导 1(normal)或 0(subnormal);
    • 可表示区间 ≈ ±240,最小正数 2^-9≈1.95e-3,精度 1/8。
  3. cast 规则

    • e4m3 → float32:零扩展 1 字节到 4 字节,按上述规则解码;
    • float32 → e4m3:round-to-nearest-even,溢出到 ±240,NaN 映射为 NaN。
  4. ufunc 注册

    • PyUFunc_RegisterLoopForDescr 为特定 dtype 签名添加内层循环;
    • 需同时提供 e4m3_add 与 e4m3_float32_add 两个循环函数;
    • 使用 NPY_ITER_BUFFERED | NPY_ITER_EXTERNAL_LOOP 保证向量化。
  5. 编译与分发

    • 国内习惯用 setuptools + numpy.distutils,setup.py 中 Extension 加 include_dirs=[np.get_include()];
    • 需导出 PyInit__e4m3 并在模块初始化里调用 import_array()、PyInit__e4m3_dtype()。

答案

以下给出可直接通过 python setup.py build_ext --inplace 编译的最小闭环(C 文件),面试时可在 20 行内讲清核心路径,其余作为“现场可补”的模板。

// _e4m3.c
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/ufuncobject.h>
#include <numpy/npy_math.h>

typedef uint8_t float8_e4m3;

/* ---------- 解码 ---------- */
static inline float e4m3_to_f32(float8_e4m3 x)
{
    uint32_t sign = (x >> 7) & 1;
    uint32_t exp  = (x >> 3) & 0xF;
    uint32_t mant = x & 0x7;
    float f;
    if (exp == 0) {              // subnormal
        f = ldexpf(mant, -9 - 3); // 2^-9 * mant/8
    } else if (exp == 15) {      // inf/nan
        f = (mant == 0) ? INFINITY : NAN;
    } else {                     // normal
        f = ldexpf((mant + 8), exp - 7 - 4); // (1.mant) * 2^(exp-7)
    }
    return sign ? -f : f;
}

/* ---------- 编码 ---------- */
static inline float8_e4m3 f32_to_e4m3(float f)
{
    uint32_t bits;
    memcpy(&bits, &f, 4);
    uint32_t sign = (bits >> 31);
    int exp;
    float mant = frexpf(fabsf(f), &exp); // mant in [0.5,1)
    if (!(f == f)) return 0x7F;          // NaN
    if (fabsf(f) >= 240.0f) return sign ? 0xFF : 0x7F; // overflow->inf
    int e = exp + 6;                     // bias=7, but mant already *0.5
    if (e <= 0) {                          // subnormal
        int m = (int)roundf(f * 512.0f);   // 2^9
        if (m <= 0) return sign ? 0x80 : 0x00;
        return (sign << 7) | (m & 0x7);
    }
    if (e >= 15) e = 15;
    int m = (int)roundf(mant * 16.0f) - 8; // 3-bit mant
    return (sign << 7) | (e << 3) | (m & 0x7);
}

/* ---------- add ufunc ---------- */
static void e4m3_add(char **args, npy_intp *dims, npy_intp *steps, void *data)
{
    npy_intp n = dims[0];
    char *i1 = args[0], *i2 = args[1], *o = args[2];
    for (npy_intp k = 0; k < n; k++) {
        float8_e4m3 a = *(float8_e4m3*)i1;
        float8_e4m3 b = *(float8_e4m3*)i2;
        float sum = e4m3_to_f32(a) + e4m3_to_f32(b);
        *(float8_e4m3*)o = f32_to_e4m3(sum);
        i1 += steps[0]; i2 += steps[1]; o += steps[2];
    }
}

/* ---------- dtype descriptor ---------- */
static PyArray_Descr e4m3_descr = {
    .typeobj = NULL,           // filled at runtime
    .kind = 'V',
    .type = 'e',
    .byteorder = '=',
    .flags = 0,
    .elsize = 1,
    .alignment = 1,
};

static PyTypeObject PyE4m3_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "e4m3",
    .tp_basicsize = sizeof(float),
    .tp_flags = Py_TPFLAGS_DEFAULT,
};

static int e4m3_cast(PyArrayObject *from, PyArrayObject *to, int casting)
{
    npy_intp n = PyArray_SIZE(from);
    float8_e4m3 *src = (float8_e4m3*)PyArray_DATA(from);
    float *dst = (float*)PyArray_DATA(to);
    for (npy_intp i = 0; i < n; i++) dst[i] = e4m3_to_f32(src[i]);
    return 0;
}

static PyArray_ArrFuncs e4m3_funcs;
static PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT, "_e4m3", NULL, -1, NULL, NULL, NULL, NULL, NULL
};

PyMODINIT_FUNC PyInit__e4m3(void)
{
    import_array();
    PyObject *m = PyModule_Create(&moduledef);
    PyE4m3_Type.tp_base = &PyGenericArrType_Type;
    if (PyType_Ready(&PyE4m3_Type) < 0) return NULL;
    e4m3_descr.typeobj = &PyE4m3_Type;
    memcpy(&e4m3_funcs, PyArray_GetArrFuncs(&e4m3_descr), sizeof(e4m3_funcs));
    e4m3_funcs.cast[ NPY_FLOAT ] = (PyArray_VectorUnaryFunc*)e4m3_cast;
    PyArray_RegisterDataType(&e4m3_descr);
    /* register ufunc */
    PyObject *add = PyObject_GetAttrString(PyImport_ImportModule("numpy"), "add");
    PyUFunc_RegisterLoopForDescr((PyUFuncObject*)add,
                                   &e4m3_descr, &e4m3_descr, &e4m3_descr,
                                   e4m3_add, NULL, 0);
    Py_DECREF(add);
    return m;
}

setup.py(国内镜像源)

from setuptools import setup, Extension
import numpy as np
setup(
    name='_e4m3',
    ext_modules=[Extension('_e4m3', ['_e4m3.c'],
                           include_dirs=[np.get_include()],
                           extra_compile_args=['-std=c99'])],
    zip_safe=False,
)

测试脚本

import numpy as np
import _e4m3
a = np.array([1, 2, 240], dtype='e4m3')
b = np.array([2, 3, 240], dtype='e4m3')
print(np.add(a, b))   // -> e4m3 array([3, 5, inf])

面试现场只需把“解码-编码-add 循环”三处讲清,其余说“模板可抄”即可。

拓展思考

  1. 如果硬件提供 e4m3 FMA 指令,如何把 ufunc 改成 SIMD 版本?
    答:在 e4m3_add 里先批量转 float32,再调用 npy_simd_f32fma,最后批量转回;或写 AVX512 内联汇编,一次处理 64 个元素。

  2. 如何支持 e4m3 × float16 的混合精度乘法?
    答:在 promotion 表把 (e4m3, float16) 提升到 float32,注册新循环签名 (e4m3, float16)->float32,避免额外临时数组。

  3. 如果要在 PyTorch 侧复用该 dtype,需要做什么?
    答:把 C 文件封装成 torch.library.register_dtype,并在 ATen 侧实现 cuda::e4m3_add,保证与 NumPy 的 rounding 位一致,才能做 zero-copy 数据交换。