gcw_mXoV1I2Z/yyfz233-Pi3
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Pi3 (yyfz233/Pi3) — 昇腾 NPU 适配

本工程将 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 上验证通过。

模型结构分析(来自 state_dict)

model.safetensors 共 1210 个权重 key,约 9.59 亿参数(958.7M):

模块结构说明
encoderDINOv2 ViT-L/14,24 层,dim=1024图像编码器,含 cls_token、pos_embed(1,1370,1024)
decoder36 层 BlockRope,dim=1024,16 heads,qkv(3072,1024)置换等变解码器,交替 local/global 注意力
register_token(1,1,5,1024)5 个寄存器 token
point_decoderTransformerDecoder,5 层,projects(1024,2048) → linear_out(1024,1024)局部点解码
point_headLinearPts3d,proj(588,1024) = 3×14²3D 点输出头
conf_decoder与 point_decoder 相同(deepcopy)置信度解码
conf_headLinearPts3d,proj(196,1024) = 1×14²置信度输出头
camera_decoderTransformerDecoder,5 层,out=512相机姿态解码
camera_headCameraHead,fc_t(3,512)、fc_rot(9,512)、res_conv×2、more_mlps4×4 相机外参输出

输入:(B, N, 3, H, W) 图片张量(值域 [0,1])。输出 dict:points、local_points、conf、camera_poses。

NPU 适配要点

  1. CUDA 全量清理:移除/替换全部 .cuda()、torch.cuda.*、device_type='cuda'。
  2. 设备迁移:模型与输入统一 .to("npu:0");入口固定 NPU 初始化 try-except。
  3. RoPE2D 降级:官方代码优先尝试 CUDA 编译扩展 curope,本环境自动回退到纯 PyTorch 慢速实现(torch.nn.functional.embedding + 旋转)。
  4. 注意力:FlashAttentionRope 使用 torch.nn.functional.scaled_dot_product_attention,在 NPU 上原生可用(无需 flash_attn / xformers)。
  5. 少量算子 CPU fallback:aten::_linalg_det(相机头 SVD 正交化)在 NPU 上自动回退 CPU,不影响正确性。
  6. 输入尺寸:patch_size=14,要求 H/W 为 14 的倍数;test_input.jpg 为 256×256,推理内部缩放至 252×252。

使用方式

1. 依赖安装

export ASCEND_VISIBLE_DEVICES=15   # 指定物理 NPU 卡
pip install -r requirements.txt

2. 权重下载

mkdir -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.safetensors

3. CLI 单图推理

python inference.py --img test_input.jpg

4. FastAPI 服务

uvicorn inference:app --host 0.0.0.0 --port 8000
curl -F "file=@test_input.jpg" http://127.0.0.1:8000/predict

验证结果(昇腾 NPU)

  • CLI 与 FastAPI 均输出结构化 JSON。
  • points 输出 shape (1, 1, 252, 252, 3),数值范围符合 3D 点图预期。
  • camera_poses 输出为合法的 4×4 相机外参(SO(3) 旋转 + 平移)。

截图证据见 assets/(agent_workflow.png、npu_device_call.png、model_result.png)。

许可

  • 模型权重与原始代码遵循 BSD-2-Clause。
  • 本适配工程基于 yyfz/Pi3 源码(BSD-2-Clause)重建模型前向并做 NPU 适配。