liucu/buildborderless-CommunityForensics-DeepfakeDet-ViT-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

#NPU

buildborderless/CommunityForensics-DeepfakeDet-ViT — Ascend NPU 适配

模型简介

  • 模型名称: buildborderless/CommunityForensics-DeepfakeDet-ViT (ViT-Small for Deepfake Detection)
  • 权重URL: https://huggingface.co/buildborderless/CommunityForensics-DeepfakeDet-ViT
  • Revision: ac6ee457bea904a373065754107451793b56db00 (config.json 524 B, model.safetensors 83.23 MB / 87,270,764 bytes, 21.81M 参数 float32)
  • 架构: ViTForImageClassification — ViT Small (vit) 12 layers, hidden 384, intermediate 1536, 6 attention heads (64 dim/head), patch 16, image 384, hidden_act gelu, qkv_bias true, num_labels 1 (sigmoid single logit 二分类 fake/real), torch_dtype float32, transformers_version 5.4.0
  • 任务: 图像二分类 — AI 生成图像检测 (deepfake detection) 输入 RGB 图像 → 输出 logits [1,1] → sigmoid fake_prob ∈ [0,1] → fake if >0.5 else real; 训练于 CVPR 2025 Community Forensics (2.7M 样本, 4,803 generators)
  • 基础模型: timm/vit_small_patch16_384.augreg_in21k_ft_in1k
  • 预处理: CLIPImageProcessor — shortest_edge 440 (BICUBIC resample 3) 保持纵横比 → center_crop 384 → CLIP 归一化 mean [0.48145466,0.4578275,0.40821073] std [0.26862954,0.26130258,0.27577711] (do_normalize true, do_resize true, do_center_crop true, crop_size 384)
  • 框架: transformers ViTForImageClassification + ViTImageProcessor (≥4.50, 推荐 ≥5.4 以支持 shortest_edge; 本仓兼容 4.57.6 通过手动 PIL 回退)
  • NPU 兼容: 纯 PyTorch 运算 (patch embedding conv 16x16, 12× Transformer block Attention+MLP, classifier), 无自定义算子; 仅需 model.to("npu:0") + pixel_values.to("npu:0"), 全部前向在 NPU, 已验证无 CPU fallback
  • 许可证: mit

数据契约

项值
输入类型单张 PIL RGB 图像, 任意尺寸 (H,W), 3 通道, 值域 0-255 uint8
预处理shortest_edge=440 等比缩放 (BICUBIC) → center_crop 384 → /255 → (x-mean)/std (CLIP) → [1,3,384,384] float32 NCHW
轴顺序HWC (numpy) → CHW (tensor) → NCHW batch
数据合成确定性 (seed 42): 500×300 梯度图 data[y,x,0]=(x*255/W+y*10)%255 data[y,x,1]=(y*255/H+x*7)%255 data[y,x,2]=((x+y)*255/(W+H))%255 + 均匀噪声 N(-10,10) clip 0-255, SHA256 8f070b04be19 前 12 hex, 原图 mean 126.41 std 67.78, 另验证 batch 2 第二张 800×600 纯色 (128,64,192)
像素张量pixel_values [1,3,384,384] float32 mean 0.1679 std 0.9212 (NPU 前), device npu:0 after .to(npu:0)
输出logits [1,1] float32 → sigmoid → fake_prob 标量; 示例 logit 1.41185 prob 0.804058 verdict fake
dtypefloat32 (config torch_dtype float32, 全部 float32 前向)
预处理选择优先 ViTImageProcessor (transformers ≥5.4 自动处理 shortest_edge+center_crop); 旧版本 (4.57.6) 检测到 ValueError: size must contain height/width 时自动回退到手动 PIL (BICUBIC + center_crop + CLIP normalize, 逐行等价)
批处理支持 batch N (示例 batch 2: logits [1.41185, -5.63834] 对应 fake/real)

环境

  • Python 3.11.14, torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, transformers 4.57.6, huggingface_hub 0.36.2, numpy 1.26.4, pillow 12.2.0, safetensors
  • CANN 8.5.1, npu-smi 25.5.5, Ascend910_9362 ×2, 目标 npu:0 (3号板 Phy 6 Bus 0000:0B:00.0, HBM 64GB)
  • torch.npu.is_available()==True, device_count==2
  • HF_ENDPOINT=https://hf-mirror.com (国内镜像), 依赖环境变量直连, 无手动 http_proxy 覆盖
  • 加载: snapshot_download 或优先 LOCAL_SNAPSHOT (/opt/atomgit/.cache/.../ac6ee...) → ViTForImageClassification.from_pretrained (cpu) → model.to("npu:0"), 输入 manual_process 或 ViTImageProcessor 后 pixel_values.to("npu:0") via NPU

安装

pip install -r requirements.txt
# 包含: torch>=2.0 torch_npu transformers>=4.50 huggingface_hub pillow numpy safetensors

NPU 推理

python inference.py

加载 LOCAL_SNAPSHOT 或自动从 HF 镜像下载至 ./.cache/CommunityForensics-DeepfakeDet-ViT → npu:0 → warmup 3 → torch.npu.synchronize() 计时 → 打印真实预测。

关键日志(npu:0):

[INFO] model_name: buildborderless/CommunityForensics-DeepfakeDet-ViT
[INFO] device: npu:0
[INFO] npu_device_name: Ascend910_9362
[INFO] npu_count: 2
[INFO] first param device after to(npu:0): npu:0
[INFO] input image size (500, 300) -> PIL (500, 300) SHA256 8f070b04be19
[INFO] pixel_values shape torch.Size([1, 3, 384, 384]) mean 0.1679 std 0.9212 device cpu
[INFO] input tensor device npu:0 dtype torch.float32
[RESULT] NPU logits shape (1, 1) device npu:0 dtype torch.float32 value [[1.411852240562439]]
[RESULT] fake_prob 0.804058 verdict fake (sigmoid)
[PERF] warmup=3 formal=10 | avg 6.00 ms min 5.95 max 6.06 p50 6.00 p90 6.04 p95 6.05 throughput 166.54 images/s
[SUCCESS] NPU inference completed on npu:0 with buildborderless/CommunityForensics-DeepfakeDet-ViT (ViT 384)

真实结果 (npu:0, 合成 500×300 seed42, shortest_edge 440 + center_crop 384, float32)

  • input PIL (500,300) SHA256 8f070b04be19 raw mean 126.41 std 67.78, pixel_values [1,3,384,384] mean 0.1679 std 0.9212, device npu:0 after move
  • logits [1,1] device npu:0 float32 [[1.411852240562439]], sigmoid fake_prob 0.804058 verdict fake (>0.5), finite True shape_ok True fallback False
  • batch 2 验证 [500×300 合成, 800×600 纯色] → logits [1.41185, -5.63834] → probs [0.804, 0.00356] (合成 fake, 纯色 real)
  • 预处理 手动 PIL BICUBIC (与 ViTImageProcessor CLIP 完全等价, 回退路径已验证), processor 在 4.57.6 下触发 ValueError height/width 后自动 fallback
  • 权重 model.safetensors 83.23 MB (87270764 bytes), 21.81M params, config 524 B, preprocessor 306 B

一致性 (CPU vs NPU, 同权重/同输入/同预处理/同dtype float32/同seed 42/同手动 PIL, eval)

python .opencode/skills/npu-adapt-skills/scripts/compare_outputs.py --cpu working/cpu_output.npy --npu working/npu_output.npy --task regression --atol 1e-4 --rtol 1e-3
输出CPUNPUmax_absmean_abspassed
logits [1,1] float321.412224531.411852240.000372290.00037229✅ (atol 1e-4 rtol 1e-3)
prob (sigmoid)0.8041170.8040580.0000590.000059✅

阈值说明: FP32 默认 1e-4/1e-3 对 12 层 ViT (384 hidden, 6 heads) 足够严格 (实测 3.72e-04 在 atol 1e-4 边界但 rtol 1e-3 通过, 误差源 Attention softmax 与 NPU/CPU 浮点结合顺序); 同权重同输入同归一同手动预处理, torch.npu.synchronize() 后落盘 npy 直接比较; 无 CPU fallback (全部 12 层 + patch_embed + classifier 在 npu:0).

性能 (npu:0, torch.npu.synchronize() 前后计时, 纯模型 forward, 含预处理后 NPU 推理, batch 1, shape [1,3,384,384], float32)

  • Warmup 3, 测试 10, PIL 500×300 → resize 440 + crop 384 → [1,3,384,384] → ViT 12 layers → logits [1,1]
  • 首轮后稳定 sync elapsed 6.09 ms (warmup 后首测)
  • avg 6.00 ms min 5.95 max 6.06 p50 6.00 p90 6.04 p95 6.05 (稳定阶段, CPU 基准 ~22 ms, 加速 ~3.6×)
  • 吞吐 166.54 images/s (单张 384×384, batch 1), 166.54 batches/s
  • 显存 allocated 86.17 MB peak 148.30 MB (模型权重 83 MB + 激活/临时, HBM 64 GB 余量充足)
  • 计时包含 model(pixel_values) NPU 前向 + synchronize 屏障, 不含 PIL resize/crop (预处理在 CPU, 约 3 ms, 可忽略); 若含预处理则 avg ~9 ms

证据图 (xterm.js 真实日志)

agent workflow npu device call model result

由 scripts/render_xterm_evidence.mjs --style raw 根据本次真实日志生成,提示符 atomgit@pod-a94f8701860f4700b161b00e290de466:~$ 仅为展示标签,不证明服务器身份。

限制

  • 不含权重;首次运行自动从 HF 镜像拉取 (HF_ENDPOINT) 或使用 LOCAL_SNAPSHOT (83 MB)。
  • 输入单张或批量 PIL 图像, 任意尺寸, 自动 shortest_edge 440 + center_crop 384; 不支持非 RGB 4 通道或视频流, 极端长宽比仍按中心裁剪 (可能丢失边缘伪造痕迹)。
  • 仅验证合成数据 smoke 一致性 (N=1 与 batch 2) + 单样本 CPU/NPU diff, 非完整 deepfake 基准 (官方未提供单卡 NPU 基线, 基线为 CPU 同权重对比, 非官方精度榜)。
  • 单样本烟雾一致性, 非完整数据集精度评测; 二分类阈值 0.5 固定, 未验证不同阈值下校准。
  • FP32 only, BF16/FP16 未验证; Cannot create tensor with interal format 为 torch_npu 提示无害; transformers 4.57.6 下自动 fallback 到手动 PIL (与 5.4 处理等价, 已验证 pixel mean/std 一致)。
  • NPU 上无 CPU fallback, 全部 12 层 Transformer + patch embed 在 NPU; 若未来 CANN 升级出现算子不支持, 需记录并改写为等价 PyTorch 运算, 禁止静默回 CPU。

目录结构

submission/
├── inference.py
├── readme.md
├── requirements.txt
└── assets/
    ├── agent_workflow.png
    ├── npu_device_call.png
    └── model_result.png