本工程将 HuggingFace 模型 yyfz233/Pi3(Pi-Cubed,可扩展置换等变视觉几何学习,image-to-3d)适配到昇腾 NPU(torch_npu),并提供双模式推理入口 inference.py。
原始权重仅含 config.json({"decoder_size": "large", "pos_type": "rope100"})与 model.safetensors,无模型架构代码。本工程依据 model.safetensors 的 state_dict 结构分析,并结合官方源码(yyfz/Pi3,BSD-2-Clause)重建了完整可运行前向,并在 npu:0 上验证通过。
model.safetensors 共 1210 个权重 key,约 9.59 亿参数(958.7M):
| 模块 | 结构 | 说明 |
|---|---|---|
encoder | DINOv2 ViT-L/14,24 层,dim=1024 | 图像编码器,含 cls_token、pos_embed(1,1370,1024) |
decoder | 36 层 BlockRope,dim=1024,16 heads,qkv(3072,1024) | 置换等变解码器,交替 local/global 注意力 |
register_token | (1,1,5,1024) | 5 个寄存器 token |
point_decoder | TransformerDecoder,5 层,projects(1024,2048) → linear_out(1024,1024) | 局部点解码 |
point_head | LinearPts3d,proj(588,1024) = 3×14² | 3D 点输出头 |
conf_decoder | 与 point_decoder 相同(deepcopy) | 置信度解码 |
conf_head | LinearPts3d,proj(196,1024) = 1×14² | 置信度输出头 |
camera_decoder | TransformerDecoder,5 层,out=512 | 相机姿态解码 |
camera_head | CameraHead,fc_t(3,512)、fc_rot(9,512)、res_conv×2、more_mlps | 4×4 相机外参输出 |
输入:(B, N, 3, H, W) 图片张量(值域 [0,1])。输出 dict:points、local_points、conf、camera_poses。
.cuda()、torch.cuda.*、device_type='cuda'。.to("npu:0");入口固定 NPU 初始化 try-except。curope,本环境自动回退到纯 PyTorch 慢速实现(torch.nn.functional.embedding + 旋转)。FlashAttentionRope 使用 torch.nn.functional.scaled_dot_product_attention,在 NPU 上原生可用(无需 flash_attn / xformers)。aten::_linalg_det(相机头 SVD 正交化)在 NPU 上自动回退 CPU,不影响正确性。test_input.jpg 为 256×256,推理内部缩放至 252×252。export ASCEND_VISIBLE_DEVICES=15 # 指定物理 NPU 卡
pip install -r requirements.txtmkdir -p ./model_weights/yyfz233/Pi3
curl -sfL "https://hf-mirror.com/yyfz233/Pi3/resolve/main/config.json" -o ./model_weights/yyfz233/Pi3/config.json
curl -sfL "https://hf-mirror.com/yyfz233/Pi3/resolve/main/model.safetensors" -o ./model_weights/yyfz233/Pi3/model.safetensorspython inference.py --img test_input.jpguvicorn inference:app --host 0.0.0.0 --port 8000
curl -F "file=@test_input.jpg" http://127.0.0.1:8000/predictpoints 输出 shape (1, 1, 252, 252, 3),数值范围符合 3D 点图预期。camera_poses 输出为合法的 4×4 相机外参(SO(3) 旋转 + 平移)。截图证据见 assets/(agent_workflow.png、npu_device_call.png、model_result.png)。