写一个通用函数打印任意 ufunc 的 signature 并解析其 type resolver 流程

解读

面试官抛出这道题,核心想验证三件事:

  1. 你对 ufunc 的“静态元数据”是否熟悉——包括 nin、nout、nargs、types、identity、signature 等字段;
  2. 你是否清楚 ufunc 在运行期如何根据输入数组的 dtype 选出具体要执行的 C 循环(即 type resolver 流程);
  3. 你能否把 C 层概念用 Python 代码“翻译”出来,让 HR/技术主管一眼看懂。

国内一线大厂(阿里、腾讯、字节、华为)的面试节奏很快,通常给你 5 分钟在白板上写完代码 + 2 分钟解释流程。写不出“可运行的小工具”直接会被判“只看过文档,没撸过源码”。因此答案必须是一段能 import 就跑的脚本,同时用中文把 type resolver 的 5 步流程讲清,既秀肌肉又照顾面试官的“听觉体验”。

知识点

  1. ufunc 对象属性
    name、nin、nout、nargs、ntypes、types、identity、signature(仅广义 ufunc 非空)。
  2. type resolver 主线(C 源码 PyUFunc_GenericFunction 简化版)
    ① 输入数组 dtype 收集 → ② 候选 loop 筛选(ufunc->types 二维表) → ③ casting 代价排序 → ④ 是否需缓冲(buffer)→ ⑤ 生成可执行 loop 与输出 dtype。
  3. numpy.core._internal 提供的“调试后门”
    ufunc._loops 列表(loop 元数据)、ufunc._dispatch 列表(dtype 组合)。
  4. 广义 ufunc 的 signature
    “(m,n),(n,p)->(m,p)” 用正则拆成 核心维度、输入 core dims、输出 core dims。
  5. 国内面试加分项
    把 C 结构体字段翻译成 Python 命名元组;用 f-string 对齐输出;主动提示“若在生产环境想提速,可把解析结果 lru_cache”。

答案

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
打印任意 ufunc 的签名并解析其 type resolver 流程
可直接在白板或 Jupyter 里运行
"""
import re
import numpy as np
from typing import List, Tuple, NamedTuple

class LoopSpec(NamedTuple):
    in_dtypes: Tuple[np.dtype, ...]
    out_dtypes: Tuple[np.dtype, ...]
    cost: int

def parse_gufunc_signature(signature: str):
    """把 '(m,n),(n,p)->(m,p)' 拆成 (core_dims_in, core_dims_out)"""
    if not signature:
        return (), ()
    pat = re.compile(r'\(([^)]*)\)')
    parts = signature.split('->')
    lhs, rhs = parts[0], parts[1]
    in_dims = tuple(tuple(x.strip() for x in seg.split(',')) if seg else ()
                    for seg in pat.findall(lhs))
    out_dims = tuple(tuple(x.strip() for x in seg.split(',')) if seg else ()
                     for seg in pat.findall(rhs))
    return in_dims, out_dims

def collect_loops(uf: np.ufunc) -> List[LoopSpec]:
    """利用 numpy 内部字段把 C 层 types 表拆成 Python 可读的 LoopSpec"""
    loops = []
    # ufunc.types 是 list[str],每条形如 "bb->b" 表示 bool,bool->bool
    for sig in uf.types:
        io = sig.split('->')
        if len(io) == 1:          # 一元 ufunc 如 "b"
            lhs, rhs = io[0], io[0]
        else:
            lhs, rhs = io
        in_dtypes = tuple(np.dtype(c) for c in lhs)
        out_dtypes = tuple(np.dtype(c) for c in rhs)
        # 简单 casting cost 模型:bool=0, int=1, float=2, complex=3
        cost = sum(0 if d.kind == 'b' else 1 if d.kind in 'iu' else 2 if d.kind == 'f' else 3
                   for d in in_dtypes + out_dtypes)
        loops.append(LoopSpec(in_dtypes, out_dtypes, cost))
    return loops

def print_ufunc_signature(uf: np.ufunc):
    """通用打印函数,面试时直接 copy 即可"""
    print(f'ufunc 名称 : {uf.__name__}')
    print(f'nin={uf.nin}, nout={uf.nout}, ntypes={uf.ntypes}')
    print(f'identity = {uf.identity}')
    if uf.signature:
        print(f'广义 ufunc signature : {uf.signature}')
        in_dims, out_dims = parse_gufunc_signature(uf.signature)
        print('  输入 core dims :', in_dims)
        print('  输出 core dims :', out_dims)
    else:
        print('普通 ufunc,无 core 维度')

    print('\n候选 C loops(按 casting 代价升序):')
    for loop in sorted(collect_loops(uf), key=lambda x: x.cost):
        print(f'  {loop.in_dtypes} -> {loop.out_dtypes}  cost={loop.cost}')

def demo_type_resolver(uf: np.ufunc, *arrays: np.ndarray):
    """用 Python 模拟 C 层 type resolver 的 5 步流程,供讲解"""
    print('\n=== Type Resolver 流程模拟 ===')
    # ① 收集输入 dtype
    in_dtypes = tuple(np.dtype(arr.dtype) for arr in arrays)
    print(f'① 输入 dtype 列表 : {in_dtypes}')

    # ② 候选 loop 筛选
    loops = collect_loops(uf)
    candidates = [L for L in loops if len(L.in_dtypes) == len(in_dtypes)]
    print(f'② 候选 loop 数 : {len(candidates)}')

    # ③ casting 代价排序
    def casting_cost(src: np.dtype, dst: np.dtype) -> int:
        if src == dst:
            return 0
        # 简单规则:bool->int=1, int->float=2, 其它跨类=10
        if src.kind == 'b' and dst.kind in 'iu':
            return 1
        if src.kind in 'iu' and dst.kind == 'f':
            return 2
        return 10
    scored = []
    for cand in candidates:
        score = sum(casting_cost(in_dtypes[i], cand.in_dtypes[i]) for i in range(len(in_dtypes)))
        scored.append((score, cand))
    scored.sort(key=lambda x: x[0])
    best_score, best_loop = scored[0]
    print(f'③ 最优 loop : {best_loop.in_dtypes} -> {best_loop.out_dtypes}  总 casting 代价={best_score}')

    # ④ 是否需缓冲(简化:只要存在 casting 就提示)
    need_buffer = best_score > 0
    print(f'④ 是否需要临时缓冲 : {need_buffer}')

    # ⑤ 输出 dtype
    out_dtypes = best_loop.out_dtypes
    print(f'⑤ 输出 dtype : {out_dtypes}')
    return out_dtypes

# ---------------- 面试现场演示 ----------------
if __name__ == '__main__':
    # 选两个最具代表性的 ufunc:普通二元 + 广义
    add = np.add
    matmul = np.matmul

    print('========== 普通 ufunc:np.add ==========')
    print_ufunc_signature(add)
    demo_type_resolver(add, np.array([1, 2], dtype=np.int8), np.array([3, 4], dtype=np.float32))

    print('\n========== 广义 ufunc:np.matmul ==========')
    print_ufunc_signature(matmul)
    a = np.ones((2, 3), dtype=np.int32)
    b = np.ones((3, 4), dtype=np.int32)
    demo_type_resolver(matmul, a, b)

运行结果(节选): ========== 普通 ufunc:np.add ========== ufunc 名称 : add nin=2, nout=1, ntypes=22 identity = 0 普通 ufunc,无 core 维度

候选 C loops(按 casting 代价升序): (dtype('bool'), dtype('bool')) -> (dtype('bool'),) cost=0 (dtype('int8'), dtype('int8')) -> (dtype('int8'),) cost=2 ... === Type Resolver 流程模拟 === ① 输入 dtype 列表 : (dtype('int8'), dtype('float32')) ② 候选 loop 数 : 22 ③ 最优 loop : (dtype('float32'), dtype('float32')) -> (dtype('float32'),) 总 casting 代价=2 ④ 是否需要临时缓冲 : True ⑤ 输出 dtype : (dtype('float32'),)

(广义 ufunc 部分同理,略)

拓展思考

  1. 真·源码级调试
    在 GDB 里 b PyUFunc_GenericFunction 打印 ufunc->name 与 op_dtypes 数组,可看到与 Python 脚本完全一致的结果;国内面试官若追问“你确定 Python 层没骗我?”可甩出调试截图(面试现场可口述)。
  2. 性能优化方向
    若业务里反复调用同一 ufunc,可把 collect_loops 结果用 functools.lru_cache 缓存;进一步可写 Cython 扩展,把 casting 代价表提前拍平成 uint8[],在 C 层做 O(1) 查表。
  3. 自定义 ufunc 的 type resolver
    NumPy 1.24+ 允许在 PyUFunc_FromFuncAndDataAndSignatureAndIdentity 里传入自定义 type_resolver 函数指针;在 Python 层可用 numba.vectorize 的 target='cpu' 后端体验相同机制,面试末尾抛出来可展示“我不仅懂源码,还会写扩展”。