ibm-granite/granite-embedding-small-english-r2 文本嵌入模型的昇腾 NPU 适配仓库(Model-Agent 大赛)。
granite-embedding-small-english-r2 是 IBM Granite Embeddings 系列中的轻量双编码器(bi-encoder)文本嵌入模型:
官方推荐用途:文本相似度、信息检索、问答召回等场景,可通过余弦相似度比较 query 与 passage 向量。
| 文件 | 说明 |
|---|---|
inference.py | 推理脚本(必选):文本编码 + query-passage 相似度打分 |
readme.md | 本文档(必选) |
requirements.txt | 环境依赖清单(推荐) |
model.safetensors | 模型权重(约 91 MiB,Git LFS) |
config.json / tokenizer*.json / modules.json / 1_Pooling/ | 模型配置与 tokenizer(sentence-transformers 兼容布局) |
results/ | NPU 实测结果(npu_result.json / npu_smi.txt / model_sha256.txt) |
pip install -r requirements.txt依赖:torch、torch_npu、transformers>=4.51、safetensors、numpy、huggingface_hub。
权重已随仓(仓库根目录),直接运行即可:
# 默认用例:官方示例 query-passage 相似度打分(自动选择 npu:0)
python3 inference.py
# 指定设备
python3 inference.py --device npu:0
python3 inference.py --device cpu
# 自定义 query / passage
python3 inference.py \
--query "Who made the song My achy breaky heart?" \
--passage "Achy Breaky Heart is a country song written by Don Von Tress."
# 单条文本编码(输出 384 维向量)
python3 inference.py --text "summit define" --output result.json
# 批量编码(每行一条)
python3 inference.py --file texts.txt
# 指定本地权重目录(权重不在脚本同目录时)
python3 inference.py --weights-dir /path/to/model_dir --text "hello"results/npu_result.json:embedding 维度、L2 范数、finite 检查、余弦相似度矩阵、耗时results/embeddings.npy:归一化向量(N x 384)results/inference_evidence.txt / model_sha256.txt / npu_smi.txt:验证证据| 项目 | 值 |
|---|---|
| 设备 | npu:0(Ascend 910) |
| 输出维度 | 384 |
| finite 检查 | 通过 |
| L2 范数 | 1.0(已归一化) |
| 加载耗时 | 3.94 s |
| 4 条文本推理耗时 | 0.19 s |
| 单条延迟 | 48.7 ms |
query-passage 余弦相似度矩阵(官方示例):
query0 vs passage0/passage1: 0.8973 / 0.6578
query1 vs passage0/passage1: 0.7112 / 0.8368query0 与其对应 passage0 相似度最高(0.8973),query1 与 passage1(0.8368),检索排序正确。
config.reference_compile = False,走 eager 路径,无需 flash_attn。attn_implementation="eager",不依赖 flash_attn / FlashAttention2,NPU 开箱即用。[CLS] 标记,取序列首 token 的 hidden state,与官方 sentence-transformers 的 pooling_mode_cls_token 一致,再做 L2 归一化。results/npu_result.json(npu:0,Ascend 910,CANN 8.5.1)