冬
gcw_IDzXRVNw/multi-qa-MiniLM-L6-cos-v1-ascend
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

multi-qa-MiniLM-L6-cos-v1 Ascend NPU 部署指南

项目简介

multi-qa-MiniLM-L6-cos-v1 是基于 MiniLM-L6-H384-uncased 的句子嵌入模型,专为 QA 检索任务优化。该模型将文本句子映射到 384 维稠密向量空间,可用于语义搜索、问答匹配、信息检索等任务。

特性

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

环境要求

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

目录结构

multi-qa-MiniLM-L6-cos-v1-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/multi-qa-MiniLM-L6-cos-v1/ 目录下:

  • model.safetensors - 模型权重 (约 90MB)
  • 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/multi-qa-MiniLM-L6-cos-v1-ascend/

python3 inference.py

python3 inference.py --mode inference

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

运行精度对比测试:

cd /data/ysws/agentsp/5-16/multi-qa-MiniLM-L6-cos-v1-ascend/

python3 inference.py --mode precision_test

命令行参数说明

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

测试验证

精度测试结果

指标实测值阈值状态
最大相对误差0.0910%< 1.00%PASS
CPU 推理时间0.074s--
NPU 推理时间0.010s--
加速比7.66x> 1xPASS
Cosine 相似度差0.0000< 0.01PASS

推理结果示例

输入句子:

  1. "How many people live in Berlin?"
  2. "What is the capital of Germany?"
  3. "Berlin is the capital and largest city of Germany."

输出:

  • 嵌入维度: 384
  • 句子1-2 Cosine 相似度: 0.5041 (语义相关)
  • 句子1-3 Cosine 相似度: 较高 (语义相关)

测试日志

multi-qa-MiniLM-L6-cos-v1 NPU Test
Model: nreimers/MiniLM-L6-H384-uncased (sentence embeddings)
Output: /data/ysws/agentsp/5-16/multi-qa-MiniLM-L6-cos-v1-ascend

============================================================
Inference Test (NPU)
============================================================
Device: npu:0
Loading model and tokenizer...
Model loaded successfully
Input sentences: 3
Input shape: torch.Size([3, 12])
Inference time: 0.243s
Embeddings shape: torch.Size([3, 384])
Sample embedding (first 5 dims): [1.0559076070785522, 0.5140956044197083, -0.17752766609191895, 0.284322589635849, -0.2778976857662201]

============================================================
Precision Test (CPU vs NPU)
============================================================
NPU Device: npu:0
Loading model...
Input sentences: 3
Running on CPU...
Running on NPU...
CPU inference time: 0.074s
NPU inference time: 0.010s
Speedup: 7.66x
Max absolute error: 1.085460e-03
Max relative error: 0.0910% (threshold: 1.0%)
Cosine similarity (CPU): 0.5041
Cosine similarity (NPU): 0.5041
Status: PASS

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

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

Python API 使用示例

基本推理

import torch
from transformers import AutoTokenizer, AutoModel

MODEL_DIR = "/data/ysws/agentsp/5-16/multi-qa-MiniLM-L6-cos-v1"

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 (MiniLM)
  • 编码器: 6 层 Transformer
  • 隐藏层维度: 384
  • 注意力头数: 12
  • 参数量: ~22.7M
  • 池化方式: Mean Pooling
组件说明
embeddingsBERT 词嵌入 (vocab_size=30522)
encoder6 层 Transformer 编码器
1_Pooling基于令牌嵌入的 Mean Pooling

推理参数配置

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

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

常见问题

Q: 精度测试失败?

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

Q: 如何提高推理速度?

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

Q: 句子嵌入有什么用?

A: 可用于:

  • 语义搜索:计算向量相似度
  • QA 匹配:找到与问题最相关的答案
  • 聚类:将相似句子聚在一起
  • 重排序:对候选结果进行相似度排序

参考链接

  • 原始模型:https://huggingface.co/nreimers/MiniLM-L6-H384-uncased
  • Sentence-Transformers:https://www.SBERT.net
  • HuggingFace Transformers:https://huggingface.co/transformers

许可证

本项目遵循 Apache-2.0 许可证