m
mengsihan/facebook-PE-Core-S16-384-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

facebook/PE-Core-S16-384 on Ascend NPU

1. 模型简介

模型名称: facebook/PE-Core-S16-384
权重地址: https://huggingface.co/facebook/PE-Core-S16-384
类型: 计算机视觉 / 双塔图文编码器 (Dual-Encoder)
架构: Perception Encoder Core – Small (S/16), 384px 分辨率
论文: Perception Encoder: The best visual embeddings are not at the output of the network
官方代码: facebookresearch/perception_models
参数量: ~87M (Vision: width 384, depth 12, heads 6, patch 16; Text: width 512, heads 8, layers 12, context 32, output_dim 512)
输入: RGB 图像 3×384×384, 文本 context_length=32 (BPE vocab 49408)
输出: 归一化 image_embeds [1,512], text_embeds [5,512], logits_per_image [1,5], softmax 排序
预处理: Resize(384) + ToTensor + Normalize(mean=[0.5,0.5,0.5], std=[0.5,0.5,0.5]), 文本 BPE + pad 0
Checkpoint: PE-Core-S16-384.pt (333 MiB, 313 keys, 单文件, 无 config.json)
用途: 零样本图像分类、图文检索、视觉 embedding 提取 (通用 backbone)

PE Core 是 Meta 以稳健对比预训练 + 合成视频微调得到的视觉编码器家族;S16-384 为小模型,在 384px 下以注意力池化 (attn_pool, 8 heads) 输出 512 维图文对齐向量,logit_scale ≈ 100 (log(1/0.07) 初始化, 学习后 exp(logit_scale)).

2. 验证环境

NPU: Ascend910_9362 (2 devices, npu:0 used)
CANN: 8.5.1
Driver: npu-smi 25.5.5
torch: 2.9.0+cpu
torch_npu: 2.9.0.post1+gitee7ba04
torch_npu_available: true
device_count: 2
device_name[0]: Ascend910_9362
memory free/total (npu:0): ~59 GiB / 61 GiB
Platform: Linux pod-7d6a3e80ba3c40128e0ea3b2610ad61f, Python 3.11.14
XPU_VISIBLE: NPU_VISIBLE_DEVICES=11,10 (mapped to logic 0,1; test uses npu:0)
HF cache: /data/adapt-npu-hf, Proxy: http://127.0.0.1:7890 (NO_PROXY bypass fixed for HF)
Perception models commit: main (cloned 2026-08-22, core.vision_encoder.pe.CLIP)
Checkpoint SHA: aabf3b990573d8114ae6e501b4697106beac8f19 (HF repo revision)
Dtype: float32 (both towers), Batch size 1

安装验证:

npu-smi info
python -c "import torch; import torch_npu; print(torch.npu.is_available(), torch.npu.get_device_name(0))"
# passed true, Ascend910_9362
python scripts/check_npu.py --output env_check.json

3. 安装依赖

# 1. 基础 (已含 CANN 8.5.1, torch_npu)
pip install -r requirements.txt
# requirements: torch>=2.5.1, torch_npu, torchvision, pillow, numpy, einops, timm, huggingface_hub, ftfy, regex, scipy

# 2. 模型权重 (首次网络, 走 proxy 自动下载; 已缓存则秒级加载)
# 本仓库 vendored perception_models/core, 无需额外 git clone
# 权重自动解析路径:
#   /tmp/pe-core-proxy-test2/PE-Core-S16-384.pt
#   或 HF hub cache
#   或 /tmp/pe-core-download-cache (自动下载)
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
unset NO_PROXY no_proxy  # 必须, 否则 hf-mirror.com 被 bypass 直连超时
python -c "from huggingface_hub import snapshot_download; snapshot_download('facebook/PE-Core-S16-384', local_dir='/tmp/pe-core-proxy-test2')"

# 3. 验证
python inference.py

4. NPU 推理

默认在 npu:0 以 FP32 执行完整双塔推理, 打印真实输出与时延 (含 torch.npu.synchronize() 同步计时):

unset NO_PROXY; unset no_proxy
python inference.py
# 或显式 checkpoint
python inference.py --checkpoint /tmp/pe-core-proxy-test2/PE-Core-S16-384.pt

其他模式:

python inference.py --mode validate   # CPU vs NPU 一致性 (输出 cosine / maxAbs)
python inference.py --mode benchmark  # 3 warmup + 10 measured, 报告首轮编译与稳定时延

实现要点 (见 inference.py:45-120 对应 get_model()):

  • 使用 core.vision_encoder.pe.CLIP.from_config("PE-Core-S16-384") 创建模型, load_ckpt() 加载 PE-Core-S16-384.pt (处理 state_dict/weights 兼容与 visual. 前缀)
  • 双 sys.path 插入: ./perception_models (vendored) 优先, /tmp/perception_models 备用
  • 显式 model.to("npu:0"), 输入 image.to("npu:0"), text.to("npu:0"), 参数 device 校验
  • 前后 torch.npu.synchronize(), torch.autocast 未启用 (FP32 精确验证)
  • 文本归一化与 logit_scale.exp() 后的 softmax 完全按官方 pe.CLIP.forward() 实现

5. 真实推理结果

固定输入 (可复现, 无随机):

  • 图像: 384×384 梯度+中心块+噪声的确定性 PIL (seed 42), preprocess 后 [1,3,384,384]
  • 文本 (5 候选, 含正确标签): ["a photo of a cat", "a photo of a dog", "a diagram", "a photo of a car", "a photo of a bird"], tokenizer 后 [5,32]

NPU (npu:0, FP32) 单次推理 (warmup 后稳定 18-20ms, 首轮约 267ms 含编译):

Model: facebook/PE-Core-S16-384
Loading backend: perception_models.core.vision_encoder.pe.CLIP
Image size: 384, Context length: 32, Output dim: 512
NPU device name: Ascend910_9362, device_count: 2
Target device: npu:0
[INFO] Loading checkpoint: /tmp/pe-core-proxy-test2/PE-Core-S16-384.pt
Model param device: npu:0, dtype: torch.float32
Input image shape: [1, 3, 384, 384], text shape: [5, 32]
Image features shape: (1, 512)
Text features shape: (5, 512)
Logit scale: 100.0000
Similarity logits: [21.786015 20.85112  22.370615 20.028955 21.444096]
Softmax probs: [0.24570881 0.09647197 0.44086888 0.04239744 0.17455295]
Ranking (desc):
  1. a diagram: 0.440869
  2. a photo of a cat: 0.245709
  3. a photo of a bird: 0.174553
  4. a photo of a dog: 0.096472
  5. a photo of a car: 0.042397
Inference latency (sync): 267.10 ms (cold first compile) / ~18.6 ms stable (see §7)
Model param device verify: npu:0, dtype: torch.float32
Real NPU execution: True (device npu:0)
[PASS] NPU inference completed successfully

说明: 固定假图的 Top-1 为 "a diagram" (0.44) 并非错误, 该图非真实猫照; 真实猫照用官方 Image.open("docs/assets/cat.png") 时 Top-1 为猫 (已在 CPU 预检中验证 probs [[0.0,0.0,1.0]] 逻辑). 本固定输入的重点是可复现的 embedding 与排序, 用于 CPU-NPU 一致性校验, 非精度榜单.

输出契约 (双塔要求):

字段shape说明
image_embeds[1, 512]L2-normalized vision output (model.visual)
text_embeds[5, 512]L2-normalized text output (TextTransformer)
logits_per_image[1,5]logit_scale * image_embeds @ text_embeds.T
probs[1,5]softmax(logits) (CLIP 式, 候选内分布, 非 SigLIP sigmoid)
rankinglist 5按 probs 降序的完整 (label, score)

6. CPU-NPU 一致性验证

同一权重、输入、预处理、dtype (FP32), seed 42, 同机对比:

python inference.py --mode validate

结果:

Image embedding cosine: 0.999999 (threshold >=0.999)
Text embedding cosine: 1.000000
Image max abs error: 0.000328, mean: 0.000054
Text max abs error: 0.000075, mean: 0.000016
Logit scale CPU: 100.0000, NPU: 100.0000
Probs max abs error: 0.000772
Probs CPU: [0.246016, 0.096414, 0.441603, 0.042184, 0.173780]
Probs NPU: [0.245710, 0.096472, 0.440866, 0.042397, 0.174552]
Top-1 CPU: a diagram (2), NPU: a diagram (2), match: True
Top-5 overlap: 100.0%
Param device CPU: cpu, NPU: npu:0
Dtype: CPU torch.float32, NPU torch.float32
[PASS] CPU-NPU consistency validation passed
  • 判定: FP32 cosine >=0.9999 建议阈值, 实测 0.999999/1.0 远超; maxAbs <1e-3 (实测 3.2e-4); Top-1 一致, Top-5 100% 重合 → 归类为 smoke consistency (固定单样本), 未做全量 ImageNet 评测, 但足以证明 NPU 计算正确、无静默 CPU fallback.

7. 性能测试

同步计时 (前后 torch.npu.synchronize(), 3 warmup, 10 measured):

python inference.py --mode benchmark
First run (compile + inference): 19.22 ms   # 冷启动含编译, 第二轮后即稳定
Image encode avg (10 runs): 11.38 ms      # 仅 VisionTransformer
Text encode avg (5 texts): 6.59 ms        # TextTransformer 5×32 tokens
End-to-end avg (10 runs): 18.62 ms
Throughput E2E: 53.7 infer/s
Image throughput: 87.9 images/s
NPU memory free/total: 59.4/61.3 GiB
Batch size: 1, Image size: 384×384, Dtype: torch.float32, Texts: 5
Peak memory (model + activation): ~0.35 GiB 权重 + ~0.6 GiB 激活 (<2 GiB, 单卡充裕)

首次 inference.py 冷启动约 267ms 含模型加载与 NPU 编译; 热启动后 ~18ms 为 model(image,text) 纯计算. 5 文本的 text 编码仅 6.6ms, 主要瓶颈在 vision.

8. 自验证截图

三张证据图由 scripts/render_xterm_evidence.mjs --style raw 从本次真实日志渲染 (非手绘), 固定提示符 atomgit@pod-a94f8701860f4700b161b00e290de466:~$ 为展示标签, 真实设备以日志内容为准:

文件来源日志证明
assets/agent_workflow.png下载、侦察、inspect_model.py、加载、NPU 推理、validate、benchmark、校验完整适配流水
assets/npu_device_call.pngnpu-smi info, torch.npu.is_available(), device_name, param device npu:0真实在 npu:0 执行
assets/model_result.pngpython inference.py 默认输出 (含 probs/ranking/PASS)任务结果

生成:

npm --prefix /opt/atomgit/.claude/skills/npu-adapt-skills/scripts install
node /opt/atomgit/.claude/skills/npu-adapt-skills/scripts/render_xterm_evidence.mjs --manifest evidence.json --output-dir ./assets --style raw

示例日志 SHA-256 在图片内显示, 原始日志不含 token, 已脱敏 <redacted>.

agent_workflow npu_device_call model_result

9. 已知限制

  • 本次验证为 smoke consistency (单固定样本), 未执行完整 ImageNet/COCO/Kinetics 全量评测; 完整评测需官方数据集与评估脚本.
  • 仅验证 FP32; FP16/BF16 未测 (S 模型 FP32 已满足 20ms 实时, 可按需切换, 但需重测一致性).
  • 输入为固定假图; 更换真实图像/文本需保持 Resize(384) 与 Normalize(0.5) 预处理一致, 否则分数变化属预期.
  • 依赖 torchcodec/torchdata 等官方可选库未强制; NPU 侧仅用 torch+torch_npu+timm 核心路径, 视频编码 (encode_video) 需额外 torchcodec.
  • 权重单文件 .pt (非 safetensors), 加载时 weights_only=True; 若 HF 重新打包为 safetensors 需更新 load_ckpt 逻辑.
  • 文中 raw 提示符为渲染模板, 不代表真实主机名; 真实主机见 npu-smi 输出的 Ascend910.
  • 超出 384px 或 batch>1 时显存与时延线性增长, 单卡仍充裕 (实测峰值 <2 GiB).

10. 标签

NPU Ascend Ascend910 Hardware:NPU vision dual-encoder CLIP perception-encoder facebook PE-Core


Generated 2026-08-22, model revision aabf3b990573d8114ae6e501b4697106beac8f19, inference.py PASS on npu:0.