waylong/facebook-dino-vitb16-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

facebook/dino-vitb16 on Ascend NPU

1. 模型简介

facebook/dino-vitb16 是基于 Vision Transformer (ViT-B/16) 的自监督预训练模型,训练方法为 DINO (Emerging Properties in Self-Supervised Vision Transformers, https://arxiv.org/abs/2104.14294)。模型由 12 层 Transformer encoder 构成,hidden_size=768, patch_size=16, image_size=224, 包含 86M 参数。输入为 224x224 RGB 图像,经 patch embedding (16x16, 196 patches + 1 CLS token = 197 tokens) 后输出 last_hidden_state [1,197,768],CLS token 可作为图像全局特征用于下游分类、检索、聚类等。模型不含微调分类头,官方最小推理示例为 ViTImageProcessor + ViTModel 提取 CLS embedding。

  • 论文: Caron et al. DINO (ICCV 2021)
  • 模型类型: vit / ViTModel
  • 权重格式: pytorch_model.bin 343 MB (FP32)
  • Processor: ViTImageProcessor (ImageNet mean [0.485, 0.456, 0.406], std [0.229, 0.224, 0.225], size 224)
  • 任务路由: vision-encoder (embedding 一致性验证,不要求 classification logits)
  • 加载后端: transformers ViTModel + ViTImageProcessor (无需 trust_remote_code)

本仓库为 Ascend NPU 单卡适配版本,已在 Ascend910_9362 (Ascend910B) 上完成真实推理与 CPU/NPU 一致性验证。

2. 验证环境

组件版本/型号
NPUAscend910_9362 (Ascend910B, SOC ascend910_9391)
CANN8.5.1 (/usr/local/Ascend/cann-8.5.1)
torch2.9.0+cpu
torch_npu2.9.0.post1+gitee7ba04
transformers4.48.0
Python3.11
设备npu:0 (共 2 devices, PhyID 14,15)
NPU 显存64 GiB (total 61.27 GiB free ~60.9 GiB)
npu-smi25.5.5
torch.npu.is_available()True
dtypefloat32 (FP32)
batch size1
image size224x224

环境检查脚本: python .opencode/skills/npu-adapt-skills/scripts/check_npu.py 输出 passed=true, device_name=Ascend910_9362, memory free 60.91 GiB.

3. 安装依赖

pip install -r requirements.txt
# requirements.txt
# torch==2.9.0
# torch-npu==2.9.0.post1
# transformers==4.48.0
# Pillow==10.4.0
# numpy==1.26.4
# huggingface_hub==0.36.2

需要已安装 CANN 8.5.1 与 Ascend 驱动。权重自动从 HuggingFace 下载 (facebook/dino-vitb16),或使用本地缓存 /tmp/dino-vitb16。可通过 HF_ENDPOINT=https://hf-mirror.com 加速。

4. NPU 推理

默认命令 (真实 NPU 推理, npu:0, FP32, 224x224 合成图像 seed=42):

python inference.py

其他模式:

python inference.py --mode validate   # CPU vs NPU 一致性
python inference.py --mode benchmark  # 性能测试 (warmup 3, runs 10)
python inference.py --device cpu      # CPU 对照
python inference.py --dtype float16   # FP16 (可选)

inference.py 至少打印: 模型名、任务、后端、device、dtype、输入摘要、真实输出 (last_hidden_state shape, CLS stats)、同步后计时、PASS/FAIL。

5. 真实推理结果

以下为 python inference.py (npu:0, FP32, 224x224 synthetic image seed=42) 在本次运行中的真实输出 (摘自 logs/evidence/inference.log):

======================================================================
Model: facebook/dino-vitb16
Task: vision-encoder (DINO ViT-B/16 feature extraction)
Loading backend: transformers ViTModel + ViTImageProcessor
Model dir: /tmp/dino-vitb16
Requested dtype: float32
Device: npu:0
----------------------------------------------------------------------
torch version: 2.9.0+cpu
torch_npu version: 2.9.0.post1+gitee7ba04
torch.npu.is_available(): True
device_name: Ascend910_9362
NPU memory free/total: 60.91 GiB / 61.27 GiB
CANN version: /usr/local/Ascend/cann-8.5.1 SOC: ascend910_9391
======================================================================
Processor: ViTImageProcessor
  size: {'height': 224, 'width': 224} do_resize=True do_normalize=True
Loading model /tmp/dino-vitb16 ...
Model param device before to(device): cpu dtype: torch.float32
  hidden_size=768 num_layers=12 patch_size=16 image_size=224
Model param device after to(device): npu:0 dtype: torch.float32
Input: synthetic 224x224 RGB image (seed=42) -> PIL size (224, 224) mode RGB
----------------------------------------------------------------------
Output last_hidden_state shape: [1, 197, 768] device: npu:0 dtype: torch.float32
Output CLS embedding shape: [1, 768] device: npu:0
CLS embedding stats: norm=63.913456 mean=0.006455 std=2.307772 min=-7.431706 max=15.222248
CLS first 5 values: [1.248647689819336, -3.0276296138763428, 0.6706226468086243, -0.04915474355220795, -0.49069252610206604]
Inference latency (synchronized): 213.03 ms
Patch embeddings mean: 0.002213
----------------------------------------------------------------------
PASS: NPU inference successful, output shape correct

关键输出契约:

  • last_hidden_state shape [1, 197, 768] (197 = 196 patches + 1 CLS)
  • CLS embedding shape [1, 768], norm ~63.91, mean ~0.006, 标准差 ~2.30
  • 设备 npu:0, dtype float32
  • 首包编译后延迟 213 ms, 稳定推理延迟见性能测试。

6. CPU-NPU 一致性验证

执行 python inference.py --mode validate (同一张 224x224 synthetic image, seed=42, FP32):

CPU CLS norm: 63.933849
NPU CLS norm: 63.913456
Cosine similarity: 0.999994
MSE: 7.04e-05
Max abs diff: 3.95e-02
Shape ok (expect [1,197,768]): True shape=[1, 197, 768]
NPU latency: 206.49 ms
PASS: CPU-NPU consistency validated (cos>0.99, mse<1e-3)

判定标准 (vision-encoder, 无分类头, embedding 契约):

  • Cosine similarity > 0.99 (实测 0.999994)
  • MSE < 1e-3 (实测 7.04e-05)
  • output shape 正确

本次为单样本 smoke consistency,非完整 ImageNet 数据集评测,旨在证明 NPU 计算与 CPU 在数值上等价。

7. 性能测试

执行 python inference.py --mode benchmark (warmup 3, runs 10, torch.npu.synchronize() 包围计时, batch 1, 224x224, FP32, npu:0):

Benchmark config: warmup=3 runs=10 batch_size=1 image=224x224 dtype=float32 device=npu:0
Avg latency: 5.78 ms
Min: 5.71 ms Max: 5.87 ms
P50: 5.78 ms P90: 5.84 ms P95: 5.85 ms
Throughput: 172.94 images/s
Peak NPU memory (if available): free 60.10 GiB total 61.27 GiB
PASS: Benchmark completed

说明:

  • 首次编译延迟 ~210 ms (含图编译与缓存), 稳定推理延迟 5.78 ms/张。
  • 峰值显存 <1 GiB (模型 0.32 GiB FP32 + 激活), 单卡 64 GiB 充裕。
  • 不同环境首次延迟会波动, 稳定吞吐以 benchmark 模式为准。

8. 自验证截图

三张 PNG 由本次真实日志通过 scripts/render_xterm_evidence.mjs --style raw 渲染 (深灰背景, 等宽字体, 显示命令、退出码、SHA-256):

  • assets/agent_workflow.png - 工作流日志 (环境检查、下载、侦察、加载、NPU推理、验证、性能)
  • assets/npu_device_call.png - 设备调用日志 (npu-smi info, torch.npu.is_available(), device_name, param device npu:0, output device npu:0)
  • assets/model_result.png - 模型结果日志 (python inference.py 真实输出, PASS/FAIL, 延迟)

9. 已知限制

  • 输入固定为 224x224 (模型 image_size=224, patch 16)。其他尺寸需 preprocessor resize, 未在本仓验证。
  • Batch size 仅验证 1; 更大 batch 需额外显存评估。
  • 模型无分类头, 输出为 embedding, 下游任务需自行添加 linear probe; pooler 权重为随机初始化未使用。
  • 仅验证 FP32; FP16/BF16 可加载但未在本仓报告精度。
  • 合成图像 (seed=42) 用于可复现 CI; 真实图像需经 ViTImageProcessor 同样的 resize/center_crop/normalize。
  • 首次推理含编译约 200 ms, 后续稳定 5-6 ms; 不同 CANN/驱动版本可能差异。
  • 权重未随仓提交, 运行时需联网或本地缓存 /tmp/dino-vitb16。

10. 标签

Hardware: NPU, NPU, Ascend, Ascend910, vision-encoder, DINO, ViT, transformers