模型适配 · 零样本表格异常检测 (Zero-shot Tabular Outlier Detection) · 昇腾 NPU
Beta 版本头信息
{hardware NPU}model.safetensors (≈ 19.5 MB)零改造适配: 模型全部算子均为 PyTorch 标准实现 —
nn.MultiheadAttention、RouterMHA (einops repeat + 两次 MHA)、nn.LayerNorm、
nn.Linear、nn.GELU — 在昇腾 NPU 上均有原生 kernel, 通过 torch_npu 直接运行,
无需替换任何算子。
项目将官方 pfns/ 源码 (含 fomo_hub.py 的 FoMo0DHub 封装) vendored 到 model/
目录, 自包含可运行, 不依赖官方仓库安装。
推理管线要点 (与官方训练约定一致):
| 步骤 | 说明 |
|---|---|
| 特征维度 | 模型按 num_features=100 训练; 少于 100 维自动补零 |
| 归一化 | 仅用 context 参考集的逐特征 min-max 缩放到 [0,1] (与模型 uniform encoder 假设一致), query 应用同一变换, 不泄漏 query 统计量 |
| 前向 | FoMo0DHub.forward(train_x, test_x) → (n_test, 1, 2) logits |
| 输出 | 异常概率 score = softmax(logits)[:, :, 1], class 1 = 异常; score > 0.5 判为异常 |
首次昇腾前向约 150 ms (算子编译预热), 之后稳态约 5 ms。
| 组件 | 版本 |
|---|---|
| torch | 2.9.0 |
| torch-npu | 2.9.0.post1 |
| einops | 0.8.2 |
| safetensors | 0.7.0 |
| CANN | 8.5.1 |
| NPU | Ascend 910B (2 × 64GB HBM) |
| Python | 3.11 |
# 1. 安装依赖 (昇腾 NPU 环境已装 torch/torch-npu 时, 其余按需)
pip install einops safetensors pandas scikit-learn fastapi uvicorn
# 2. 运行内置演示 (合成数据: 300 正常参考 + 80 正常 + 20 异常), 输出精度与 CPU/NPU 性能
python inference.py --demo
# 3. 对 CSV 打分: 前 300 行视为正常参考, 其余行逐行打分, 结果追加 outlier_score / is_anomaly 列
python inference.py --csv data.csv --context 300
# 4. 服务化推理
python inference.py --serve --port 8000设备选择: 默认 auto (优先 npu:0, 回退 CPU); 可 --device cpu / --device npu:0。
启动 python inference.py --serve --port 8000 后:
GET /health — 服务状态
{"status": "ok", "device": "npu:0"}POST /predict — JSON 打分
{
"context": [[1.1, 2.2, ...], ...],
"data": [[0.9, 2.0, ...], ...],
"threshold": 0.5
}响应: 每行样本的 scores (异常概率) 与 labels (0 正常 / 1 异常)。
POST /predict_csv — 上传 CSV (multipart), query 参数 context = 参考行数, threshold = 阈值。
内置演示 (context 300×5 特征补零至 100 维, 测试 100 行含 20 异常):
| 指标 | 值 |
|---|---|
| CPU 前向稳态 | 81.0 ms |
| NPU 前向稳态 | 5.3 ms (~15× 加速) |
| CPU vs NPU 输出余弦相似度 | 0.99999893 |
| ROC-AUC | 0.9544 |
| 异常精度 (score>0.5) | 1.0000 |
| 异常召回 (score>0.5) | 0.8500 |
| 峰值 HBM 占用 | ≈ 40 MB |
| 正常样本 score | ≈ 0.05 |
| 异常样本 score | ≈ 1.0000 |
FoMo-0D/
├── inference.py # 推理脚本 (demo / csv / serve 三种模式)
├── README.md # 本文档
├── requirements.txt # 环境依赖
├── config.json # 模型超参 (来自官方)
├── model.safetensors # 官方权重 (fp32, 19.5MB)
├── model/ # vendored 官方源码 (自包含)
│ ├── fomo_hub.py # FoMo0DHub 封装 (PyTorchModelHubMixin)
│ └── pfns/ # PFN Transformer 源码 (transformer/layer/encoders/...)
└── assets/ # 截图素材 (agent_workflow / npu_device_call / model_result)