g
gcw_coj3XaOd/BAAI_bge-base-en-v1.5
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

BAAI/bge-base-en-v1.5 - 昇腾 NPU 推理部署

1. 模型简介

模型名称: BAAI/bge-base-en-v1.5

模型链接: HuggingFace | AtomGit 镜像

模型描述: BGE (BAAI General Embedding) base English v1.5 是一个基于 BERT 的句子嵌入模型,用于生成 768 维的文本向量表示,适用于检索、语义匹配、聚类等 NLP 任务。

模型架构: BERT-base (12-layer Transformer encoder)

参数规模: ~110M (109,482,240)

输入规格:

  • 类型: text (token IDs)
  • Shape: [batch_size, max_seq_len] (max 512 tokens)
  • Tokenizer: BertTokenizer (WordPiece)

输出规格:

  • 类型: float32 tensor
  • Shape: [batch_size, 768] (L2-normalized sentence embedding)

2. 环境依赖

依赖项版本要求说明
Python>= 3.10推荐 3.11
torch>= 2.1.0PyTorch 框架
torch_npu>= 2.1.0昇腾 NPU 后端
transformers>= 4.30.0HuggingFace Transformers
sentencepiece>= 0.1.99Tokenizer 依赖
safetensors>= 0.3.0安全权重加载
昇腾驱动CANN 8.0+推荐 CANN 8.5.1

安装命令:

pip install torch torch_npu transformers sentencepiece safetensors numpy

3. 推理步骤

3.1 环境准备

# 检查 NPU 设备
npu-smi info

# 验证 torch_npu
python3 -c "import torch_npu; print(torch.npu.device_count(), torch.npu.get_device_name(0))"

3.2 模型下载

方式一:HuggingFace(推荐)

huggingface-cli download BAAI/bge-base-en-v1.5 --local-dir /path/to/model

方式二:AtomGit 镜像(HuggingFace 下载慢时使用)

git clone https://ai.gitcode.com/BAAI/bge-base-en-v1.5.git /path/to/model

3.3 运行推理

# 交互式推理
python inference.py --model-path /path/to/model

# 批量推理(性能测试)
python inference.py --model-path /path/to/model --benchmark --batch-size 64

# 指定 NPU 设备
python inference.py --model-path /path/to/model --device npu:0

3.4 推理参数说明

参数类型默认值说明
--model-pathstr必填模型 checkpoint 路径
--devicestrnpu:0NPU 设备
--max-lengthint512最大序列长度
--batch-sizeint32批量推理大小
--benchmarkflagFalse运行性能测试

4. 推理成功日志

4.1 单条推理日志

[模型] BAAI/bge-base-en-v1.5
[设备] Ascend910_9362 (npu:0)
[输入] "The quick brown fox jumps over the lazy dog."
[输出] shape=[1, 768], dtype=float32, norm=1.000000
[耗时] ~1.5ms per sentence
[状态] SUCCESS

4.2 批量推理日志

[基准测试] 32次推理统计:
  总耗时: 0.19s
  吞吐量: 168.4 texts/s
  平均: 5.9ms
  最小: 3.1ms
  最大: 8.2ms

5. 测试样例及输出结果

样例 1:单条句子嵌入

运行命令:

python3 -c "
import torch, torch_npu, torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer

device = torch.device('npu:0')
tokenizer = AutoTokenizer.from_pretrained('/path/to/model')
model = AutoModel.from_pretrained('/path/to/model').to(device).eval()

text = 'Machine learning is transforming the world.'
encoded = tokenizer(text, return_tensors='pt')
input_ids = encoded['input_ids'].to(device)
attention_mask = encoded['attention_mask'].to(device)

with torch.no_grad():
    out = model(input_ids=input_ids, attention_mask=attention_mask)
    emb = F.normalize(out.pooler_output, p=2, dim=1).cpu()

print(f'Embedding: shape={emb.shape}, norm={emb[0].norm().item():.6f}')
print(f'First 8 values: {emb[0, :8].tolist()}')
"

输出:

Embedding: shape=torch.Size([1, 768]), norm=1.000000
First 8 values: [-0.044708, -0.025020, 0.026026, 0.052109, 0.006168, -0.031924, 0.042203, 0.009470]

样例 2:批量句子相似度

运行命令:

python3 inference.py --model-path /path/to/model --benchmark --batch-size 32

输出:

================================================================
Benchmark Results:
  Texts processed: 32
  Total time: 0.1935s
  Throughput: 165.4 texts/s
  Embedding shape: torch.Size([32, 768])
  Embedding norms: [1.0, 1.0, 1.0, ...]
================================================================

样例 3:语义搜索

运行命令:

python3 -c "
import torch, torch.nn.functional as F
from inference import encode_texts, load_model

model, tokenizer, device = load_model('/path/to/model')

query = 'How do I learn machine learning?'
docs = [
    'Machine learning is a subset of AI.',
    'Python programming tutorial.',
    'Weather forecast for today.',
]
embs = encode_texts(model, tokenizer, [query] + docs, device)
sims = torch.mm(embs[0:1], embs[1:].t())[0]
for i, s in enumerate(sims.tolist()):
    print(f'doc{i+1}: {s:.4f}')
"

输出:

doc1: 0.9767  <-- ML doc correctly matched highest
doc2: 0.9652
doc3: 0.9146

6. Agent适配截图

6.1 Agent 完整适配工作流

Agent 适配流程

6.2 NPU 硬件设备调用日志

NPU 设备调用

6.3 模型适配结果

模型适配结果


7. 精度评测

测试数据: 自建 6 条英文句子(不同领域)

评测指标:

指标结果说明
NPU vs CPU Cosine Sim (min)0.99999750float32 精度损失极小
NPU vs CPU Cosine Sim (mean)0.99999833平均精度极高
Max Absolute Diff4.36e-04acceptable for float32
嵌入范数1.000000L2 归一化正确

评测命令:

python3 inference_full.py

实际输出:

NPU vs CPU cosine similarity: min=0.99999750, mean=0.99999833, max=0.99999887
Max absolute difference: 4.35545109e-04
[PASS] Step 9: Accuracy verified - NPU matches CPU (cosine sim > 0.9999)

8. NPU 配置说明

  • NPU 设备: 2x Ascend910_9362
  • 使用的 NPU 卡数: 1 (npu:0)
  • 显存占用: ~3349 MB HBM
  • CANN 版本: 8.5.1
  • PyTorch 版本: 2.9.0+cpu (with torch_npu 2.9.0.post1)
  • 推理吞吐量: 31 texts/s (batch=3, seq_len19)

9. 已知问题

无。BERT-base 为标准架构,所有算子均在昇腾 NPU 上原生支持。