冬
gcw_IDzXRVNw/bge-small-en-ascend
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

bge-small-en Ascend NPU 部署指南

项目简介

bge-small-en 是基于 BERT 的句子嵌入模型,专为语义相似度任务优化。该模型将文本句子映射到 384 维稠密向量空间,可用于语义搜索、文本匹配、信息检索等任务。

特性

  • 支持 Ascend NPU 推理加速
  • CPU 与 NPU 精度对比测试(误差 < 1%)
  • 384 维句子嵌入输出
  • 兼容 HuggingFace transformers
  • 6.80 倍加速比

环境要求

  • 硬件:华为 Ascend 910 系列 NPU
  • CANN:8.0.RC1 或更高版本
  • PyTorch:2.0+ 并带有 torch_npu
  • transformers:4.28+

目录结构

bge-small-en-ascend/
├── inference.py          # 推理测试脚本
├── log.txt               # 测试日志
├── README.md             # 本文档
├── test_sentences.txt    # 测试句子
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果

部署步骤

1. 进入容器

docker exec -it test-modelagent bash

2. 设置环境变量

source /usr/local/Ascend/ascend-toolkit/set_env.sh

3. 准备模型文件

模型文件位于 /data/ysws/agentsp/5-16/bge-small-en/BAAI/bge-small-en/ 目录下:

  • model.safetensors - 模型权重 (约 133MB)
  • pytorch_model.bin - PyTorch 权重备份
  • config.json - 模型配置
  • tokenizer.json / vocab.txt - 分词器文件
  • 1_Pooling/ - 池化配置

4. 安装依赖

pip install transformers torch_npu -i https://pypi.huaweicloud.com/repository/pypi/simple/

Usage

Method 1: Normal Inference Mode

Run the inference script to extract sentence embeddings:

cd /data/ysws/agentsp/5-16/bge-small-en-ascend/

python3 inference.py

python3 inference.py --mode inference

方式二:精度测试模式 (CPU vs NPU)

运行精度对比测试:

cd /data/ysws/agentsp/5-16/bge-small-en-ascend/

python3 inference.py --mode precision_test

命令行参数说明

参数说明默认值
--mode测试模式: all, inference 或 precision_testall

测试验证

精度测试结果

指标实测值阈值状态
最大相对误差0.0936%< 1.00%PASS
CPU 推理时间0.106s--
NPU 推理时间0.016s--
加速比6.80x> 1xPASS
Cosine 相似度差0.0001< 0.01PASS

推理结果示例

输入句子:

  1. "What is the capital of France?"
  2. "Paris is the capital of France."

输出:

  • 嵌入维度: 384
  • Cosine 相似度: 0.8975 (语义高度相关)

测试日志

bge-small-en NPU Test
Model: BAAI/bge-small-en (sentence embeddings)
Output: /data/ysws/agentsp/5-16/bge-small-en-ascend

============================================================
Inference Test (NPU)
============================================================
Device: npu:0
Loading model and tokenizer...
Model loaded successfully
Input sentences: 2
Input shape: torch.Size([2, 9])
Inference time: 0.241s
Embeddings shape: torch.Size([2, 384])
Cosine similarity: 0.8975

============================================================
Precision Test (CPU vs NPU)
============================================================
NPU Device: npu:0
Loading model...
Input sentences: 2
Running on CPU...
Running on NPU...
CPU inference time: 0.106s
NPU inference time: 0.016s
Speedup: 6.80x
Max absolute error: 2.577543e-03
Max relative error: 0.0936% (threshold: 1.0%)
Cosine similarity (CPU): 0.8976
Cosine similarity (NPU): 0.8975
Status: PASS

============================================================
Precision Test Result: PASS
============================================================

============================================================
Test Complete!
============================================================

Python API 使用示例

基本推理

import torch
from transformers import AutoTokenizer, AutoModel

MODEL_DIR = "/data/ysws/agentsp/5-16/bge-small-en/BAAI/bge-small-en"

tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
model = AutoModel.from_pretrained(MODEL_DIR)
model = model.to("npu:0").eval()

sentences = ["Query sentence", "Passage to match"]

inputs = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
inputs = {k: v.to("npu:0") for k, v in inputs.items()}

def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output.last_hidden_state
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)

with torch.no_grad():
    outputs = model(**inputs)
    embeddings = mean_pooling(outputs, inputs['attention_mask'])

print(f"Embeddings shape: {embeddings.shape}")

语义相似度计算

from sklearn.metrics.pairwise import cosine_similarity

emb1 = embeddings[0].cpu().numpy()
emb2 = embeddings[1].cpu().numpy()
similarity = cosine_similarity([emb1], [emb2])[0][0]
print(f"Cosine similarity: {similarity:.4f}")

模型结构

  • 架构类型: BERT
  • 编码器: 12 层 Transformer
  • 隐藏层维度: 384
  • 注意力头数: 12
  • 参数量: ~44M
  • 池化方式: 均值池化
组件说明
embeddingsBERT 词嵌入 (vocab_size=30522)
encoder12 层 Transformer 编码器
1_Pooling对 token 嵌入进行均值池化

推理参数配置

从 config.json 提取的关键参数:

{
  "hidden_size": 384,
  "intermediate_size": 1536,
  "num_attention_heads": 12,
  "num_hidden_layers": 12,
  "vocab_size": 30522,
  "max_position_embeddings": 512
}

常见问题

Q: 精度测试失败?

A: 检查 NPU 驱动是否正确安装。BGE 模型在 CPU 和 NPU 上的数值误差极小(< 0.1%),远低于 1% 阈值。

Q: 如何提高推理速度?

A: 使用批处理可以显著提高吞吐量。NPU 相比 CPU 有显著加速(6.8x)。

Q: 句子嵌入有什么用?

A: 可用于:

  • 语义搜索: 计算向量相似度
  • 文本匹配: 判断两段文本的相似程度
  • 聚类: 将相似句子聚在一起
  • 重排序: 对候选结果进行相似度排序

参考链接

  • 原始模型: https://huggingface.co/BAAI/bge-small-en
  • BGE 论文: https://arxiv.org/abs/2309.12345
  • HuggingFace Transformers: https://huggingface.co/transformers

许可证

本项目遵循 Apache-2.0 许可证