Files
ssw-mpc/tools/bench_numpy.py
T
admin e01c7f9419 docs: 按新定位重写中文描述,修复参考实现路径误改
- 中文定位从「Rust 重写 Python 算术执行引擎」改为「多方数据协同、数据不出域的安全计算框架」;README/CLAUDE/ARCHITECTURE/GAP_PLAN 同步,沿革小节写明新旧语义差别
- 修复机械替换引入的功能 bug:gen_golden.py / check_psi.py / bench_numpy.py 的 refs/mpc/mpc 路径改回 refs/nax/nax(参考实现真实目录,CI 不跑这些脚本故未暴露)
- 恢复 Python 参考实现包名 import nax;mpc-python 统一改称「Python 参考实现」;远端仓库描述同步
2026-11-05 15:17:28 +08:00

83 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Python 参考实现(numpy)的微基准,与 `crates/mpc-core/examples/bench.rs` 对齐。
同一个机器、同样规模、同样算子,唯一变量是"numpy 的 u64 路径" vs
"Rust 的 u64 路径"。这个对比的意义在于:ML 框架里所有性能优化都建立在
浮点 BLAS 上,而 MPC 用的是 **u64 环算术** —— BLAS 完全帮不上忙,
numpy 只能走通用迭代器循环。这正是 Rust 算子核最大的价值来源。
用法:
.venv/bin/python tools/bench_numpy.py
"""
from __future__ import annotations
import importlib.util
import pathlib
import time
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parent.parent
REF_RING = ROOT / "refs" / "nax" / "nax" / "crypto" / "ring.py"
def load_ring():
spec = importlib.util.spec_from_file_location("ref_ring", REF_RING)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
return mod
def bench(label: str, iters: int, fn) -> float:
fn() # warmup
best = float("inf")
for _ in range(iters):
t = time.perf_counter()
fn()
dt = time.perf_counter() - t
best = min(best, dt)
print(f"{label:<42} {best * 1e3:>10.3f} ms")
return best * 1e3
def main() -> int:
ring = load_ring()
rng = np.random.default_rng(0xC0FFEE)
print("numpy 参考实现微基准")
print(f"numpy {np.__version__}")
print("=" * 30)
print()
print("[矩阵乘 u64 @ u64(mod 2^64)]")
for n in (64, 128, 256):
a = rng.integers(0, 1 << 63, size=(n, n), dtype=np.uint64)
b = rng.integers(0, 1 << 63, size=(n, n), dtype=np.uint64)
iters = 20 if n <= 64 else (5 if n <= 128 else 2)
with np.errstate(over="ignore"):
ms = bench(f" matmul {n}x{n}x{n}", iters, lambda: ring.matmul(a, b))
ops = n**3
print(f" -> {ops / (ms / 1e3) / 1e9:.2f} Gop/s")
print()
print("[逐元素算子,16M 元素]")
length = 16 * 1024 * 1024
a = rng.integers(0, 1 << 63, size=length, dtype=np.uint64)
b = rng.integers(0, 1 << 63, size=length, dtype=np.uint64)
for name, fn in (
("mul (16M)", lambda: ring.mul(a, b)),
("add (16M)", lambda: ring.add(a, b)),
("arshift 18 (16M)", lambda: ring.arshift(a, 18)),
):
with np.errstate(over="ignore"):
ms = bench(f" {name}", 5, fn)
print(f" -> {length / (ms / 1e3) / 1e9:.2f} Gop/s")
return 0
if __name__ == "__main__":
raise SystemExit(main())