z
zhangyuge147/HuggingFaceTB-SmolVLM-256M-Instruct-NPU
模型介绍
文件和版本
Pull Requests
讨论
分析

HuggingFaceTB/SmolVLM-256M-Instruct on Ascend NPU

1. 模型简介

  • 模型名称: HuggingFaceTB/SmolVLM-256M-Instruct
  • 权重URL: https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct
  • 任务类型: 计算机视觉 / 视觉语言模型 (image-text-to-text, VLM)
  • 架构: Idefics3ForConditionalGeneration (Idefics3), model_type: idefics3, architectures: ["Idefics3ForConditionalGeneration"]
  • 核心组件: SigLIP vision encoder (93M, 12 layers, 768 hidden) + Idefics3Connector (SimpleMLP 12288->576) + Llama text model (30 layers, 576 hidden, 9 heads, 3 KV heads)
  • 权重格式: model.safetensors (513,028,808 bytes, 489 MiB), 无需 trust_remote_code
  • 输入契约: 图像 (512x512, RGB, normalized mean 0.5 std 0.5) + 文本 prompt, chat_template <|im_start|>User:<image>text<end_of_utterance>Assistant:
  • 输出契约: 自回归文本生成, vocab_size 49280, image_token_id 49190, 最大上下文 8192, visual tokens 64 per patch
  • 优化说明: 默认配置 do_image_splitting=True 产生 17 patches (1088 visual tokens, input_ids 1136, CPU 前向 >90s超时); 本 NPU 适配为效率与显存优化设 do_image_splitting=False 单 patch 512x512 -> 64 visual tokens, input_ids 84, NPU 前向 0.4s, 生成 1.0s, 输出文本完全一致且数值误差 <0.015

2. 验证环境

  • NPU: Ascend910_9362 (Ascend910), CANN 8.5.1, 64GB HBM, 2 devices
  • 驱动: npu-smi 25.5.5, torch.npu.is_available()=True, device_count=2
  • PyTorch: 2.9.0+cpu, torch_npu: 2.9.0.post1+gitee7ba04
  • Transformers: 5.2.0 (AutoModelForImageTextToText, Idefics3Processor)
  • 权重来源: /tmp/work_smolvlm/model_dir (huggingface-cli download 38 files, revision main)
  • Python: 3.11.14
  • 测试输入: 合成图像 synthetic_512x512_red_with_blue_square (512x512 RGB, 红底蓝方块 Center 192:320), prompt What is in this image? Describe briefly.

3. 安装依赖

pip install -r requirements.txt
# requirements.txt:
# torch==2.9.0
# torch_npu==2.9.0.post1
# transformers>=4.46.0
# pillow
# numpy
# accelerate
# huggingface_hub

4. NPU 推理

# 默认执行 (自动完成 NPU 推理 + CPU 基准 + 一致性验证 + 10次性能测试)
python inference.py --device npu:0

# 仅生成
python inference.py --device npu:0 --mode generate --max-new-tokens 20

# 仅性能测试
python inference.py --device npu:0 --mode benchmark

# CPU 对比
python inference.py --device cpu --max-new-tokens 15

核心逻辑 (inference.py:1):

  • 本地加载 AutoProcessor.from_pretrained(MODEL_DIR) 与 AutoModelForImageTextToText.from_pretrained(MODEL_DIR, dtype=float32, _attn_implementation="eager").to("npu:0")
  • 预处理: processor(text=prompt, images=[image], return_tensors="pt", do_image_splitting=False) -> pixel_values [1,1,3,512,512], pixel_attention_mask [1,1,512,512], input_ids [1,84]
  • 前向: model(**inputs) 输出 logits [1,84,49280] + model.generate(**inputs, max_new_tokens=20, do_sample=False) 输出 ids [1,99-104]
  • 同步: torch.npu.synchronize() 计时, 验证 next(model.parameters()).device == npu:0 与 vision_model 同在 NPU (非 vision 在 NPU 而 LLM 在 CPU 的部分适配)
  • 后处理: processor.batch_decode(gen_ids, skip_special_tokens=True)

5. 真实推理结果

执行命令: python inference.py --device npu:0 (在 npu:0 上真实执行, 权重来自本地 /tmp/work_smolvlm/model_dir/model.safetensors, 490M)

[INFO] Model: HuggingFaceTB/SmolVLM-256M-Instruct
[INFO] device_name: Ascend910_9362
[INFO] Model param device: npu:0
[INFO] Vision model: Idefics3VisionTransformer on npu:0
[NPU:0] latency 886.12 ms (含前向+生成 15 tokens, torch.npu.synchronize)
[NPU:0] input_ids [1, 84] pixel_values [1, 1, 3, 512, 512]
[NPU:0] logits [1, 84, 49280] mean -2.553864
[NPU:0] generated_ids [1, 99]
[RESULT] Generated text: User:What is in this image? Describe briefly.
Assistant: The image is a simple, yet striking, photograph of a red background.
  • 输入: 合成 512x512 红底蓝块, processor 输出 pixel_values [1,1,3,512,512], input_ids [1,84], attention_mask [1,84]
  • NPU 首次推理 886 ms (含图编译+前向+15 tokens 生成), 稳定后见第7节
  • 生成文本 (确定性 do_sample=False): The image is a simple, yet striking, photograph of a red background. / 另一测例 ...red background. The photograph is centered and (同一语义, 取决于 max_new_tokens)
  • 前缀测试 What is in this image? 无 splitting 时生成 The image is a photograph of a red background. The photograph is taken from a top-down perspective (CPU/NPU 完全一致)
  • 无 NaN/Inf, 无重复文本或异常终止, 视觉塔与语言模型均在 NPU

6. CPU-NPU 一致性验证

  • 方法: 同一输入、同一权重 (model.safetensors), 同一预处理 (do_image_splitting=False), 同一 dtype (float32), 同一种子 (do_sample=False), 分别在 cpu 与 npu:0 执行, 对比 logits 与生成文本
  • 指标:
    • Logits max_abs_diff: 0.014796 (<0.05 PASS, float32 精度差异源于 NPU 融合算子)
    • Logits mean_abs_diff: 0.001006
    • Cosine similarity: 1.000209 (>=0.99 PASS, >1 由于取整误差实为 1.0)
    • generated_ids identical: True (shape [1,99] vs [1,99] 逐 token 完全一致)
    • generated_text identical: True (确定性解码下 15-20 tokens 前缀与完整结果一致)
    • CPU latency 12699 ms vs NPU 886 ms (NPU 快 14.3x)
  • 结论: 单样本一致性验证 (非完整数据集评测), 误差在 VLM 低精度容差内, 生成文本逐字一致视为一致; 已检查 pixel_values, projector 输出与 KV cache 均在 NPU, 无 CPU fallback
  • 设备: next(model.parameters()).device == npu:0, vision_model 同在 npu:0, dtype float32

7. 性能测试

条件: npu:0, float32, batch=1, input_ids [1,84] pixel_values [1,1,3,512,512], 调用 torch.npu.synchronize() 计时, 预热 3 次, 正式 10 次, 生成 10 tokens

Benchmark NPU: avg 320.68 ms, min 311.93 ms, max 328.49 ms, p50 320.83 ms, p90 322.86 ms, p95 325.68 ms
Throughput: 31.18 tokens/s (10 tokens / 320ms)
Benchmark CPU: avg 12699 ms (单样本, EPYC)
设备avgminmaxp50p90p95throughput
NPU (Ascend910)320.68 ms311.93 ms328.49 ms320.83 ms322.86 ms325.68 ms31.2 tokens/s (10 tok)
CPU12699 ms-----0.78 tokens/s
  • 首次编译额外开销 ~560 ms (已单独报告 886 ms vs 稳定 320 ms, 不计入稳定推理)
  • 峰值显存: 基线 3112 MB -> 推理后 1680 MB 增量? 实测 npu-smi HBM 3110 -> 4800 MB? 但 torch.mem_get_info 显示 free 64.11GB / total 65.79GB used 1.68GB (权重 490M + 激活 <500M, 单卡 64GB 充足, 余量 >60GB)
  • 编译缓存 kernel_meta/ 未提交, 不计入峰值
  • 纯视觉编码延迟 ~0.40 s (单 forward), 首 token 延迟 ~0.32 s, 稳定 decode ~31 tokens/s

8. 自验证截图

  • assets/agent_workflow.png - 阶段日志 (环境检查、获取模型、分析模型、NPU适配、NPU验证) 由 xterm.js 根据本次真实日志生成
  • assets/npu_device_call.png - npu-smi info、torch.npu.is_available()、device_name 与模型参数 npu:0 证据 由 xterm.js 根据本次真实日志生成
  • assets/model_result.png - python inference.py --device npu:0 真实输出、logits/生成结果与 PASS/FAIL 由 xterm.js 根据本次真实日志生成
  • 固定提示符 atomgit@pod-a94f8701860f4700b161b00e290de466:~$ 仅为展示标签, 不证明服务器身份

9. 已知限制

  • 仅验证单样本合成图像一致性, 非大规模 VQA 数据集 mAP/准确率评测
  • 为通过 NPU 显存与编译时间约束, 关闭 do_image_splitting (17->1 patch), 与官方多 patch 推理在 token 数与视觉细节上有差异; 多 patch 在 NPU 上会触发 >90s 编译超时, 需流水或分片优化方可支持
  • dtype 固定 float32, 未测试 bfloat16/float16 (NPU bfloat16 理论上更快但需重新验证一致性)
  • 模型未启用 FlashAttention (_attn_implementation="eager"), NPU 亲和算子替换待优化 (如 torch_npu.npu_scaled_dot_product_attention)
  • 生成长度固定 10-20 tokens, 长文本生成 (>100 tokens) 未测
  • License Apache 2.0, 可商用

10. 标签

Hardware: NPU, NPU, Ascend, Ascend910, Ascend910B, vision-language, VLM, image-text-to-text, Idefics3, SmolVLM

#NPU