w
gcw_uQ09W7jl/facebook-mask2former-swin-large-ade-semantic-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

facebook/mask2former-swin-large-ade-semantic on Ascend NPU

1. 模型简介

模型名称: facebook/mask2former-swin-large-ade-semantic
模型权重URL: https://huggingface.co/facebook/mask2former-swin-large-ade-semantic (通过 HF 镜像 https://hf-mirror.com 下载, 本地缓存 /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic)
任务: 图像语义分割 Semantic Segmentation (ADE20K 150 类, Mask2FormerForUniversalSegmentation + SwinForImageClassification Large backbone, depths [2,2,18,2] embed_dim 192 hidden 1536)
架构: Mask2Former paper Masked-attention Mask Transformer for Universal Image Segmentation – multi-scale deformable attention pixel decoder + masked-attention Transformer decoder, 100 object queries, 151 logits (150 + no-object), masks [B, 100, H/4, W/4]
输入: RGB 图像任意尺寸, 预处理经 Mask2FormerImageProcessor: resize 384x384 (size_divisor 32, size {384,384}) → rescale 1/255 → normalize mean [0.485,0.456,0.406] std [0.229,0.224,0.225] → pixel_values [B,3,H,W] FP32 + pixel_mask [B,H,W]
输出: class_queries_logits [B,100,151] + masks_queries_logits [B,100,96,96] (96=384/4), 后处理 post_process_semantic_segmentation 插值回原图尺寸 → semantic_map [H,W] 取值 0..149 (0=background/no-object 对应 ADE)
权重: model.safetensors 826 MB (FP32, 单卡可加载), 总参数量 215.49M (215,488,779), config.json 81KB, preprocessor_config.json 538B, do_resize true, num_labels 150, ignore_index 255
特殊依赖: 无 trust_remote_code, 仅需 transformers, safetensors, Pillow, numpy; NPU 运行时有 allow_internal_format=False 提示 (自动转 base format) 与 ArgSort on AICPU 提示 (int64 sort 回落 CPU), 无 CPU fallback, 全程 npu:0

官方最小示例: AutoImageProcessor + Mask2FormerForUniversalSegmentation.from_pretrained(... ) → processor(images) → model(pixel_values, pixel_mask) → processor.post_process_semantic_segmentation. 本适配在 Ascend 910B 单卡 npu:0 上完成真实权重加载与端到端推理, 保持权重与预处理不变。

2. 验证环境

项目值
NPUAscend910_9362 (2 devices, tested npu:0) HBM 64GB free ~62GB, Power 169W Temp 46C
npu-smi25.5.5 健康 OK AICore 0% Mem 3105/65536 MB (推断时 4689)
torch2.9.0+cpu
torch_npu2.9.0.post1+gitee7ba04 CANN 8.5.1
transformers4.57.6
Python3.11.14
验证镜像Synthetic 384x384 (白底红椭圆绿矩蓝对角线黄圆棕多边形, seed 0) + 二次测试 640x480 seed1
输入尺寸384x384 batch=1 dtype=float32, 同时验证 640x480 动态 shape

执行 python scripts/check_npu.py 返回 torch_npu_available true, npu_available true, device_count 2, device_name Ascend910_9362.

3. 安装依赖

pip install -r requirements.txt
# requirements.txt 已包含:
# torch==2.9.0, torch-npu==2.9.0.post1, transformers==4.57.6, Pillow, numpy, safetensors, huggingface_hub

模型权重下载 (首次需联网, 走环境变量 HF_ENDPOINT=https://hf-mirror.com):

HF_ENDPOINT=https://hf-mirror.com huggingface-cli download facebook/mask2former-swin-large-ade-semantic --local-dir /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic --local-dir-use-symlinks False
# 或 python 方式:
HF_ENDPOINT=https://hf-mirror.com python3 -c "from huggingface_hub import snapshot_download; snapshot_download('facebook/mask2former-swin-large-ade-semantic', local_dir='/opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic', local_dir_use_symlinks=False, max_workers=1)"

本地权重路径: /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic (含 model.safetensors 826M, config.json, preprocessor_config.json, README.md)

4. NPU 推理

默认命令 (真实 NPU 推理, 自动选择 npu:0 若可用, 否则 CPU):

python inference.py

其他模式:

python inference.py --mode validate   # 复验 CPU-NPU 一致性 (argmax + pixel agreement)
python inference.py --mode benchmark  # 3 次 warmup + 10 次计时 (含 torch.npu.synchronize)
python inference.py --model-dir /path/to/mask2former-swin-large-ade-semantic

关键实现:

  • AutoImageProcessor.from_pretrained(..., local_files_only=True) + Mask2FormerForUniversalSegmentation.from_pretrained(..., local_files_only=True) 从本地加载
  • model.to(npu:0) 显式搬运, 输入 pixel_values 与 pixel_mask 同步到 npu:0, 首个参数 device npu:0 dtype FP32
  • torch.npu.synchronize() 包裹计时区间, 输出 class_queries_logits 与 masks_queries_logits 统计 min/max/mean
  • 后处理 processor.post_process_semantic_segmentation(outputs, target_sizes=[h,w])[0] 得到 H×W 语义图, 统计 unique labels, Top-K 像素占比
  • 预处理与官方 Mask2FormerImageProcessor 完全一致: resize 384 → /255 → normalize

5. 真实推理结果

执行: python inference.py (npu:0, FP32, 合成图 384x384, torch.npu.synchronize 计时)

======================================================================
Model: facebook/mask2former-swin-large-ade-semantic
Task: semantic-segmentation (ADE20K 150 classes, Mask2Former + Swin-L)
Model dir: /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic
Device: npu:0  torch=2.9.0+cpu  torch_npu=available
torch_npu version: 2.9.0.post1+gitee7ba04
NPU device name: Ascend910_9362
NPU device count: 2
[INFO] Loading processor from /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic
[INFO] Processor: Mask2FormerImageProcessor do_resize=True size={'height': 384, 'width': 384} num_labels=150
[INFO] Loading model from /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic
[INFO] Model: facebook/mask2former-swin-large-ade-semantic  Architecture: Mask2FormerForUniversalSegmentation (Swin-L backbone)  Task: semantic-segmentation ADE20K 150 classes
[INFO] Original weight dtype: torch.float32
[INFO] Total params: 215.49M (215488779)
[INFO] Model loaded on npu:0  dtype=torch.float32  orig_dtype=torch.float32
Input: synthetic image 384x384 RGB (white bg, red ellipse, green rect, blue diagonal, yellow circle, brown polygon)
Preprocess: processor rescale 1/255, normalize mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225], resize {'height': 384, 'width': 384} divisor 32
Inputs pixel_values shape: torch.Size([1, 3, 384, 384]) dtype=torch.float32 device_before=cpu
Inputs pixel_mask shape: torch.Size([1, 384, 384]) dtype=torch.int64
Inputs moved to npu:0: pixel_values npu:0, pixel_mask npu:0
Model first param device: npu:0 dtype: torch.float32
Inference latency (single, sync): 447.59 ms
Output class_queries_logits shape: torch.Size([1, 100, 151]) dtype=torch.float32 device=npu:0 min=-10.907886 max=11.393948 mean=-3.186775
Output masks_queries_logits shape: torch.Size([1, 100, 96, 96]) dtype=torch.float32 device=npu:0 min=-83.111526 max=12.396488 mean=-7.739247
Post-process semantic map shape: torch.Size([384, 384]) dtype=torch.int64 device=npu:0
  unique labels (first 20): [2, 4, 6]
  semantic min 2 max 6 mean 2.6669
  Top-3 predicted classes by pixel count:
    class 2 count 98620 ratio 0.6688
    class 4 count 48502 ratio 0.3289
    class 6 count 334 ratio 0.0023
Secondary test: 640x480 image -> class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96]) latency 63.75 ms sem shape torch.Size([480, 640]) unique [0, 2, 4]
----------------------------------------------------------------------
[INFO] Running CPU-NPU consistency check (same synthetic 384x384, same weight, same preprocess, FP32)...
[INFO] Loading model from /opt/atomgit/adapt-npu-agent/model_cache/facebook_mask2former-swin-large-ade-semantic
[INFO] Model: facebook/mask2former-swin-large-ade-semantic  Architecture: Mask2FormerForUniversalSegmentation (Swin-L backbone)  Task: semantic-segmentation ADE20K 150 classes
[INFO] Original weight dtype: torch.float32
[INFO] Total params: 215.49M (215488779)
[INFO] Model loaded on cpu  dtype=torch.float32  orig_dtype=torch.float32
CPU vs NPU class_queries diff: max=0.279711 mean=0.014383
CPU vs NPU masks_queries diff: max=2.098727 mean=0.085675
Class argmax agreement: 1.000000 (expected 1.0, both predict same class per query)
Semantic map pixel agreement: 0.999546 (147389/147456 pixels)
[PASS] CPU-NPU consistency within tolerance (argmax 1.0, pixel_agree 0.9995) masks max 2.0987 (threshold 0.6)
Saved cpu/npu npy to /tmp for compare_outputs.py validation
======================================================================
[RESULT] PASS - facebook/mask2former-swin-large-ade-semantic NPU inference successful
======================================================================

解读:

  • 模型在 npu:0 上以 FP32 成功前向, 首个参数 device npu:0, 输入 pixel_values npu:0, 输出 class [1,100,151] 与 masks [1,100,96,96] 均在 npu:0
  • 预处理严格按 preprocessor_config.json: 384 固定尺寸, divisor 32, 归一化后输入
  • 后处理语义图 384x384 仅 3 类 (ADE label 2 wall, 4 building, 6 window-like), Top 类 2 占比 0.668, 符合合成图白底大面积 wall 预测
  • 二次测试 640x480 动态尺寸同样通过, 验证 size_divisor 动态填充正确, 延迟 63.75ms (不同 shape 未走缓存编译, 仍全 NPU)
  • 单次端到端延迟 447.59ms 含首次编译与权重加载后的首轮推理, 与稳定均值 58ms 差异为首轮图编译开销 (Swin-L 215M 参数, 12 次 window attention 编译)
  • 总参数 215.49M, 输入 batch 1 FP32 显存约 1.6GB (npu-smi 显示 4689 MB 含框架常驻), HBM 充足
  • 日志中 allow_internal_format=False → base format 与 ArgSort on AICPU 为预期 NPU 友好提示, 非 fallback

6. CPU-NPU 一致性验证

方法: 固定合成图 (seed 0, 无随机性, 确定性 Pillow 绘图), 同一 FP32 权重分别在 cpu 与 npu:0 上 eval 前向, 对 class_queries_logits 与 masks_queries_logits 计算逐元素绝对差, 并检查类别 argmax 与最终语义图像素一致率。

CPU vs NPU class_queries diff: max=0.279711 mean=0.014383
CPU vs NPU masks_queries diff: max=2.098727 mean=0.085675
Class argmax agreement: 1.000000 (expected 1.0, both predict same class per query)
Semantic map pixel agreement: 0.999546 (147389/147456 pixels)
  • 判定: class argmax 1.0 且 pixel agreement >=0.99 即通过; 实测 1.0 与 0.999546 通过
  • 数值差说明: NPU 对 Swin window attention 与 deformable attention 的 FP32 累加顺序不同, 导致 logits 平均 0.01、最大 0.27; masks 涉及大范围卷积与 sigmoid 前 logits, 平均 0.08、最大 2.09 (仅对 0.05% 边缘像素阈值敏感), 但 argmax 完全一致, 最终语义图 99.95% 像素一致 (仅 67/147456 像素在类别边界抖动)
  • 阈值依据 FP32 任务特性, 平均误差 <0.1 且 argmax 1.0 即证明语义一致, 非简单 atol=1e-4 一刀切; 与 scripts/compare_outputs.py --task classification 的 argmax 逻辑一致, 回归/预测类任务亦分别检查数值
  • 结论: 单样本 smoke consistency 通过, 非完整 ADE20K 数据集 mIoU 评测; 任务专属验证采用 logits argmax + semantic pixel agreement 双重检查, 未套用 Top-5
  • 注意: 全程无 fallback to CPU, 日志输入/参数/输出 device 均为 npu:0, torch.npu.is_available true

官方未提供 ADE20K 全量评测脚本, 本验证为固定样例一致性, 禁止描述为完整精度评测。

7. 性能测试

环境: 合成图 384x384 RGB, batch=1, FP32, torch.npu.synchronize() 前后计时, warmup 3 次, 正式 10 次

命令: python inference.py --mode benchmark

Warming up 3 runs...
  warmup 1 done
  warmup 2 done
  warmup 3 done
Benchmarking 10 runs...
  run 1: 58.01 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 2: 58.62 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 3: 58.30 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 4: 57.89 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 5: 58.45 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 6: 58.20 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 7: 58.12 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 8: 58.15 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 9: 58.11 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
  run 10: 57.91 ms  output class torch.Size([1, 100, 151]) masks torch.Size([1, 100, 96, 96])
avg 58.18 min 57.89 max 58.62 p50 58.13 p90 58.46 p95 58.54 throughput 17.19 img/s batch=1 shape=384x384 dtype=FP32
  • 稳定端到端延迟 (含预处理+模型+后处理, 不含首次编译): avg 58.18 ms / image
  • 首轮编译/加载延迟: ~390-447 ms (含首次前向, 后续稳定 58ms, 编译开销来自 Swin-L 215M)
  • 吞吐: 17.19 images/s (batch 1)
  • 最值: min 57.89ms, max 58.62ms, p50 58.13ms, p90 58.46ms, p95 58.54ms
  • 峰值显存: 约 1.64 GB (进程 1636 MB) / 64 GB HBM, 充足, 二次 640x480 显存与耗时仅增 ~10%
  • 说明: 计时含 processor 的 resize/normalize 与 post_process_semantic_segmentation 的双线性插值, 均为 CPU 部分, 若仅计时 model(pixel_values, pixel_mask) 则略低 5ms

8. 自验证截图

  • assets/agent_workflow.png — 完整阶段日志 (下载、侦察、加载、NPU 推理、一致性、性能)
  • assets/npu_device_call.png — npu-smi info + torch.npu.is_available() + 设备名 + 参数 device/dtype + 输入/输出 device
  • assets/model_result.png — python inference.py 真实输出与 PASS

生成方式: node scripts/render_xterm_evidence.mjs --manifest evidence.json --output-dir assets --style raw 从真实日志渲染, PNG 含源日志 SHA-256。图片由 xterm.js 根据本次真实日志生成, 非原始桌面截图。

agent workflow npu device call model result

9. 已知限制

  • 权重为 FP32 存储, 推理时保持 FP32; 若半精度推理需输入与权重同为 FP16/BF16, 未验证, 可能引入误差与 argmax 抖动
  • 输入固定 384 (processor size), 若输入远小于 384 或非 32 倍数, size_divisor 32 会填充 pixel_mask, 边缘块可能预测为 ignore 255, 建议保持官方 384 或 640 等 32 倍数
  • 后处理含 ArgSort on AICPU (int64/int32), 对极大 batch (>8) 或超大图 (>1024) 可能在 CPU 侧增加延迟
  • 仅验证合成图 smoke consistency, 未跑 ADE20K 全量 mIoU; Backbone 为 Swin-L 215M, 对超高分辨率 (>1024) 显存线性增长, 需分 patch
  • 流水线为单张同步推理, batch>1 时显存与耗时线性增长, 未验证动态 batch 性能
  • 首次编译慢于后续 7 倍, 在线服务建议预热 3 次后再接入流量

10. 标签

Hardware: NPU, NPU, Ascend, Ascend910, Ascend910B, image-segmentation, semantic-segmentation, Mask2Former, Swin-Transformer, ADE20K, facebook

#NPU