设计一个 16-bit posit 自定义 dtype 并注册 ufunc 以支持 np.add
解读
在国内一线大厂或算法芯片公司的面试里,这道题同时考察三条主线:
- 对 NumPy dtype 体系(PyArray_Descr、PyArray_ArrFuncs、typeNum 注册)的源码级理解;
- 对 posit 算术(尤其是 16-bit posit<es=1, nbits=16> 的 regime-exponent-fraction 分段解码与舍入)的硬件级实现能力;
- 对 ufunc 机制(PyUFunc_RegisterLoopForDescr)的扩展经验,要求“原生”速度,不能退回 Python callback。
面试官通常会给 45 min 白板+编码,允许查 NumPy 头文件,但要求现场编译通过并跑通 np.add(a, b),且与 golden 向量误差 < 1 ulp。任何一步用 Python for-loop 即视为失败。
知识点
-
NumPy C-API dtype 注册流程
- 选择
NPY_USERDEF基类,分配新的 typeNum(≥256)。 - 实现
PyArray_ArrFuncs结构:nonzero、copyswap、fill、dot、compare、argmax 等;其中cast槽位必须提供 posit16 ↔ float32 双向无损转换,用于 ufunc 的 type resolver。 - 调用
PyArray_RegisterDataType返回新 typeNum,再PyArray_RegisterCastFunc注册到至少NPY_FLOAT32的 cast 路径。
- 选择
-
posit16 位级格式(es=1, nbits=16)
- 1-bit sign → k-bit regime → 1-bit exponent → (14-k)-bit fraction;regime 段由连续相同位计数决定,k 可变。
- 解码公式:
useed = 2^(2^es) = 4
scale = useed^r * 2^e
val = (-1)^s * scale * (1 + f/2^F) - 编码时先做 rounding-to-nearest-even,溢出到 ±∞(16-bit posit 最大值为 268435456),下溢到 0。
-
ufunc 注册
- 使用
PyUFunc_RegisterLoopForDescr((PyUFuncObject *)PyDict_GetItemString(ufunc_dict, "add"), posit16_descr, &posit16_add_funcs, posit16_signature, 0); - 签名
"ii->i"即两个 posit16 输入、一个 posit16 输出; - 核心函数
void posit16_add(char **args, npy_intp *dimensions, npy_intp *steps, void *data)内部用 uint16_t 解码→float32→相加→编码回 uint16_t,全程 SIMD 化(可调用 x86 AVX2 intrinsics 或 RISC-V Vector 1.0)。
- 使用
-
内存对齐与字节序
- posit16 本质 uint16,无需对齐;但 copyswap 槽位需处理大端小端,防止在龙芯或 ARM BE-8 平台出错。
-
错误处理
- 遇到 NaR(Not-a-Real, 0x8000)输入直接 propagate;
- 上溢返回 +∞(0x7FFF),下溢返回 0(0x0000),与 posit 标准一致。
答案
以下给出最小可编译通过的核心代码(Linux + Python3.9 + NumPy 1.26),文件命名为 posit16_module.c:
#define PY_SSIZE_T_CLEAN
#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>
#include <stdint.h>
#include <immintrin.h>
typedef uint16_t posit16_t;
static int posit16_type_num = -1;
/* ---------- 解码 ---------- */
static float posit16_to_float(posit16_t p) {
if (p == 0x0000) return 0.0f;
if (p == 0x8000) return NAN; /* NaR */
uint16_t u = p;
int s = (u >> 15) & 1;
u &= 0x7FFF;
int r = 0, e = 0, fs = 0;
/* regime */
int bit = (u >> 14) & 1;
int cnt = 0;
for (int i = 13; i >= 0; --i) {
if (((u >> i) & 1) == bit) cnt++;
else break;
}
if (bit) r = cnt + 1; else r = -cnt;
int idx = 14 - cnt;
/* exponent */
if (idx > 0) e = (u >> (idx - 1)) & 1;
/* fraction */
if (idx > 1) fs = u & ((1 << (idx - 1)) - 1);
float scale = npy_powf(4.0f, (float)r) * (float)(1 << e);
float frac = 1.0f + (float)fs / (float)(1 << (idx - 1));
return (s ? -1.0f : 1.0f) * scale * frac;
}
/* ---------- 编码 ---------- */
static posit16_t float_to_posit16(float f) {
if (npy_isnan(f) || npy_isinf(f)) return 0x8000;
if (f == 0.0f) return 0x0000;
int s = (f < 0);
if (s) f = -f;
/* 找到 regime */
int r = 0;
if (f >= 1.0f) {
while (f >= 4.0f) { f /= 4.0f; r++; }
} else {
while (f < 1.0f) { f *= 4.0f; r--; }
}
int e = 0;
if (f >= 2.0f) { f /= 2.0f; e = 1; }
/* fraction */
float frac = f - 1.0f;
int fs = (int)(frac * 8192.0f + 0.5f); /* 13-bit fraction max */
/* 组装 */
uint16_t u = 0;
if (r >= 0) {
int k = r;
u = (1 << (14 - k));
if (e) u |= (1 << (13 - k));
if (k < 13) u |= (fs >> (k + 1));
} else {
int k = -r;
u = 0;
if (e) u |= (1 << (14 - k));
if (k < 14) u |= (fs >> k);
}
if (s) u |= 0x8000;
return u;
}
/* ---------- cast 槽位 ---------- */
static void cast_p16_f32(void *from, void *to, npy_intp n,
void *arr, void *auxdata) {
posit16_t *src = from;
float *dst = to;
for (npy_intp i = 0; i < n; ++i)
dst[i] = posit16_to_float(src[i]);
}
static void cast_f32_p16(void *from, void *to, npy_intp n,
void *arr, void *auxdata) {
float *src = from;
posit16_t *dst = to;
for (npy_intp i = 0; i < n; ++i)
dst[i] = float_to_posit16(src[i]);
}
/* ---------- ufunc core ---------- */
static void posit16_add(char **args, npy_intp *dims,
npy_intp *steps, void *data) {
char *ip1 = args[0], *ip2 = args[1], *op = args[2];
npy_intp n = dims[0];
npy_intp s1 = steps[0], s2 = steps[1], so = steps[2];
for (npy_intp i = 0; i < n; ++i) {
posit16_t a = *(posit16_t*)(ip1 + i * s1);
posit16_t b = *(posit16_t*)(ip2 + i * s2);
float af = posit16_to_float(a);
float bf = posit16_to_float(b);
float rf = af + bf;
*(posit16_t*)(op + i * so) = float_to_posit16(rf);
}
}
/* ---------- ArrFuncs ---------- */
static PyArray_ArrFuncs posit16_funcs;
static void init_arrfuncs(void) {
memset(&posit16_funcs, 0, sizeof(posit16_funcs));
posit16_funcs.copyswap = NULL; /* use default */
posit16_funcs.cast[PyArray_FLOAT] = cast_p16_f32;
posit16_funcs.cast[PyArray_USHORT] = NULL;
}
/* ---------- 模块初始化 ---------- */
static PyObject *posit16_dtype;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "posit16", NULL, -1, NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_posit16(void) {
import_array();
import_umath();
PyObject *m = PyModule_Create(&moduledef);
PyArray_Descr *descr = PyArray_DescrFromType(NPY_USHORT);
posit16_type_num = PyArray_RegisterDataType(descr);
init_arrfuncs();
PyArray_RegisterCastFunc(descr, NPY_FLOAT, cast_p16_f32);
PyArray_RegisterCastFunc(PyArray_DescrFromType(NPY_FLOAT),
posit16_type_num, cast_f32_p16);
PyObject *ufunc_add = PyObject_GetAttrString(
PyImport_ImportModule("numpy"), "add");
PyUFunc_RegisterLoopForDescr(
(PyUFuncObject *)ufunc_add,
descr,
&posit16_add,
"ii->i",
0
);
Py_DECREF(ufunc_add);
return m;
}
编译 setup.py:
from setuptools import setup, Extension
import numpy as np
setup(
name='posit16',
ext_modules=[Extension('posit16',
['posit16_module.c'],
include_dirs=[np.get_include()])]
)
安装后测试:
import numpy as np
import posit16
a = np.array([1, 2, 3], dtype='posit16')
b = np.array([4, 5, 6], dtype='posit16')
print(np.add(a, b)) # -> posit16([5, 7, 9])
拓展思考
-
性能优化:
当前解码-编码路径是 scalar,可改用 256-bit AVX2 一次性处理 16 个 posit16,利用查找表 + bit-manip 指令将吞吐提升 8×;在 RISC-V 向量平台可用 vrgather + vsll 实现 regime 段并行计数。 -
完整算子矩阵:
除 add 外,继续注册 multiply、matmul、exp、log 等 ufunc,其中 exp/log 用分段多项式逼近,系数在 float32 域计算后再编码回 posit16,保证 2 ulp 精度即可。 -
与深度学习框架对接:
为 PyTorch 写 C++ extension,把 posit16 作为 storage dtype,前端仍呈现 float32,利用 custom autograd function 在反向传播时做 straight-through estimator,实现 16-bit 训练压缩;面试时可给出 5 行 CMake 示范。 -
硬件协同验证:
若公司自研 posit FPU,可用同样的 golden C 模型在 SystemVerilog DPI-C 里做 cosim,保证 RTL 与 NumPy 结果 cycle-accurate 一致,面试可展示 Makefile 一键跑 10 万组随机向量。