Files
ssw-mpc/tools/bench_numpy.py
T
admin 54781b3f83
ci / gate (push) Waiting to run
refactor: 项目改名 ssw-mpc,crate 统一到 mpc-* 前缀
- 项目与文档标题:nax-rs → ssw-mpc(尚数网-多方安全计算),二进制 nax → mpc
- 18 个 crate 及目录 nax-* → mpc-*,Rust 引用 nax_* → mpc_*
- 环境变量、C 符号、构建/部署脚本:NAX_* → MPC_*、libnax_ray.so → libmpc_ray.so
- 保留协议域分隔常量与 refs/nax 参考实现路径,维持 golden 向量与历史数据兼容
- 新增 [profile.dev] incremental=false
2026-11-05 15:06:12 +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" / "mpc" / "mpc" / "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())