SAMViT Base(samvit_base_patch16.sa1b)是基于 Vision Transformer 的图像特征提取模型,源自 Meta 的 Segment Anything Model(SAM),在 SA-1B 数据集上预训练。该模型用于提取图像的高维语义特征(embeddings),可作为视觉任务的通用骨干网络。
本仓库实现了该模型在华为昇腾 Ascend NPU 上的适配和推理。
原始模型地址:
| 组件 | 版本 |
|---|---|
| Python | 3.11.x |
| PyTorch | 2.9.0+cpu |
| torch-npu | 2.9.0.post1 |
| timm | 最新 |
| 昇腾 CANN | 8.5.1 |
| NPU | Ascend910 (64GB HBM) |
该模型基于 PyTorch 框架,昇腾 NPU 通过 torch_npu 实现对 PyTorch 的完整算子兼容。本适配方案无需修改模型代码,只需:
timm.create_model 创建模型(pretrained=False)model.to('npu:0')# 安装依赖
pip install torch torchvision timm pillow numpy safetensors
# 验证 NPU 可用性
python3 -c "import torch; print(torch.npu.is_available())"python3 inference.py --model samvit_base_patch16.sa1b --device cpupython3 inference.py --model samvit_base_patch16.sa1b --device npupython3 compare_cpu_npu.py --model samvit_base_patch16.sa1b| 指标 | 数值 |
|---|---|
| 输入尺寸 | 1×3×1024×1024 |
| 输出尺寸 | 1×256 |
| 平均推理耗时(NPU) | 0.1079s |
| 输出范围 | [-0.5525, 0.8060] |
| 输出均值 | 0.0117 |
| 输出标准差 | 0.1360 |
| 指标 | 数值 |
|---|---|
| 最大绝对误差(Max Absolute Error) | 0.00061904 |
| 平均绝对误差(Mean Absolute Error) | 0.00006378 |
| 余弦相似度(Cosine Similarity) | 0.99999960 |
| 最大差异比率(Max Diff Ratio) | 0.0768% |
| L2 距离 | 0.0016 |
| 设备 | 推理耗时 | 加速比 |
|---|---|---|
| CPU | 26.8504s | 1x |
| NPU (Ascend910) | 0.1072s | 250.58x |
NPU 与 CPU 推理结果误差 < 1%。
以上数据表明,NPU 推理结果与 CPU 推理结果在数值上高度一致,精度满足要求。


import torch
import timm
from PIL import Image
from torchvision import transforms
# 加载模型(从本地权重)
model = timm.create_model('samvit_base_patch16.sa1b', pretrained=False)
state_dict = torch.load('model.safetensors', weights_only=True)
model.load_state_dict(state_dict, strict=False)
model = model.to('npu:0')
model.eval()
# 预处理图像
transform = transforms.Compose([
transforms.Resize((1024, 1024), interpolation=transforms.InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# 推理
img = Image.open('input.jpg').convert('RGB')
input_tensor = transform(img).unsqueeze(0).to('npu:0')
with torch.no_grad():
features = model(input_tensor)
print(features.shape) # (1, 256)支持批量处理多张图像,只需增加 batch 维度:
# batch_size = N
input_batch = torch.stack([transform(img) for img in images]).to('npu:0')
with torch.no_grad():
features_batch = model(input_batch)+NPU:支持昇腾 NPU 推理+CV:计算机视觉模型+昇腾:华为昇腾平台适配+Ascend:Ascend NPU compatible| 属性 | 值 |
|---|---|
| 模型架构 | samvit_base_patch16 |
| 预训练数据集 | SA-1B |
| 特征维度 | 768 → 256 (after pooling) |
| 输入尺寸 | 1024×1024 |
| 参数规模 | ~91M |
| 权重文件大小 | ~358MB |