s
stella4528/granite-embedding-small-english-r2-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

granite-embedding-small-english-r2-npu

ibm-granite/granite-embedding-small-english-r2 文本嵌入模型的昇腾 NPU 适配仓库(Model-Agent 大赛)。

模型简介

granite-embedding-small-english-r2 是 IBM Granite Embeddings 系列中的轻量双编码器(bi-encoder)文本嵌入模型:

  • 架构:ModernBERT(12 层、hidden 384、12 注意力头、局部注意力窗口 128 + 全局注意力每 3 层),CLS Pooling
  • 参数量:约 4700 万(47M)
  • 输出:L2 归一化后的 384 维文本向量
  • 上下文长度:最长 8192 token
  • 任务:文本嵌入 / 语义检索 / query-passage 相似度打分(Feature Extraction)
  • 许可:Apache 2.0

官方推荐用途:文本相似度、信息检索、问答召回等场景,可通过余弦相似度比较 query 与 passage 向量。

环境

  • 昇腾 NPU:Ascend 910(CANN 8.5.1)
  • PyTorch 2.9.0 + torch_npu 2.9.0.post1
  • transformers 4.57.x(>= 4.51 即可,ModernBERT 架构)

仓库内容

文件说明
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 实测)

项目值
设备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.8368

query0 与其对应 passage0 相似度最高(0.8973),query1 与 passage1(0.8368),检索排序正确。

NPU 适配说明

  1. 禁用 torch.compile:transformers 的 ModernBERT 实现仅对 mps/cpu 设备自动降级 torch.compile,在 NPU 上会尝试 inductor 编译(写缓存目录、可能触发磁盘配额/兼容问题)。本脚本在 NPU 设备上显式设置 config.reference_compile = False,走 eager 路径,无需 flash_attn。
  2. attention 实现:固定 attn_implementation="eager",不依赖 flash_attn / FlashAttention2,NPU 开箱即用。
  3. CLS Pooling:ModernBERT 无真实 [CLS] 标记,取序列首 token 的 hidden state,与官方 sentence-transformers 的 pooling_mode_cls_token 一致,再做 L2 归一化。
  4. 权重 fp32 加载,CPU 与 NPU 结果一致(相似度矩阵差异 < 1e-4)。

验证

  • CPU 预验证:相似度矩阵与官方 README 示例一致
  • NPU 真机验证:results/npu_result.json(npu:0,Ascend 910,CANN 8.5.1)

参考

  • 原模型:https://huggingface.co/ibm-granite/granite-embedding-small-english-r2
  • 论文:Granite Embedding R2 Models(arXiv:2508.21085)