| 属性 | 内容 |
|---|---|
| 模型名称 | ERNIE-4.5-21B-A3B-Thinking |
| 模型架构 | Ernie4_5_MoeForCausalLM (MoE) |
| 总参数量 | 21B |
| 激活参数量 | ~3B (A3B) |
| 专家数量 | 64 |
| 共享专家 | 2 |
| 激活专家数 (Top-K) | 6 |
| 上下文长度 | 131072 |
| 权重精度 | bfloat16 |
| 权重格式 | safetensors |
ERNIE-4.5 是百度研发的大语言模型,采用 MoE(Mixture-of-Experts)架构,总参数量 21B,每次前向传播激活约 3B 参数,兼顾性能与推理效率。
| 项目 | 版本/型号 |
|---|---|
| 硬件 | Ascend910 |
| CANN | 8.x |
| OS | Linux aarch64 |
| Python | 3.11 |
| PyTorch | 2.x |
| torch_npu | 2.9.0.post1 |
| transformers | 4.57.6 |
模型原始发布为 PaddlePaddle 格式,但权重文件同时提供 safetensors 格式,且 transformers 库已原生支持 Ernie4_5_MoeForCausalLM 架构(trust_remote_code=True)。因此本次适配采用 PyTorch + transformers + torch_npu 路径,规避了 PaddlePaddle 生态中 paddle-custom-npu 安装困难的问题。
在推理脚本顶部引入 transfer_to_npu,自动完成 CUDA → NPU 映射:
import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu由于 device_map="auto" 在纯 NPU 环境下可能错误分配设备,采用先 CPU 加载再显式迁移到 NPU 的策略:
model = AutoModelForCausalLM.from_pretrained(
MODEL_PATH,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
device_map="cpu",
)
model = model.to("npu:0")使用 transformers 原生 generate 接口,支持 chat_template:
messages = [{"role": "user", "content": prompt}]
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
return_tensors="pt",
return_dict=True,
)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=256)模型在 NPU 上成功加载并生成连贯中文文本,推理过程无报错。生成内容符合 ERNIE-4.5 的 thinking 模式特征(模型会在 <think> 标签内展示推理过程)。
| 指标 | 数值 |
|---|---|
| 模型加载时间 (CPU→NPU) | ~101s |
| NPU 显存占用 | 40.74 GB / 61.27 GB |
| 生成长度 | 256 tokens |
| 生成耗时 | 39.87s |
| 推理吞吐 | 6.42 tokens/s |
测试条件:单卡 Ascend910,bf16 精度,batch_size=1,temperature=0.6,top_p=0.95。
transfer_to_npu 格式警告
MoE 路由计算中的 one_hot + permute 会触发 torch_npu 内部格式警告:
Cannot create tensor with interal format while allow_internel_format=False该警告不影响结果正确性,可忽略。
torch.jit.script 被禁用
transfer_to_npu 会自动禁用 torch.jit.script,本模型未使用 JIT 编译,无影响。
PaddlePaddle 原生 NPU 路径阻塞
官方 paddle-custom-npu 包在 PyPI 及华为镜像均无法获取,导致 Paddle 原生路径不可行。本次适配通过 transformers PyTorch 路径完成。
| 文件 | 说明 |
|---|---|
inference_npu.py | 昇腾 NPU 单卡推理脚本 |
logs/ernie_npu_inference_clean.log | 推理完整日志 |
README_ASCEND.md | 本适配报告 |
export ASCEND_RT_VISIBLE_DEVICES=0
python inference_npu.pyERNIE-4.5-21B-A3B-Thinking 模型成功在昇腾 NPU 上完成适配验证。通过 PyTorch + transformers 路径,模型可在单卡 Ascend910 上稳定运行,显存占用约 41GB,推理吞吐约 6.4 tokens/s。该方案无需安装 paddle-custom-npu,降低了昇腾环境部署门槛。