all-MiniLM-L6-v2
all-MiniLM-L6-v2是一款开源英文文本编码模型,可将句子、短段落映射为384维语义向量,支持语义搜索、聚类等多种文本处理任务。
这个项目值得继续研究吗?
all-MiniLM-L6-v2是一款开源英文文本编码模型,可将句子、短段落映射为384维语义向量,支持语义搜索、聚类等多种文本处理任务。
- 解决什么问题
- 企业在搭建英文知识库检索、内容聚类、相似文本匹配类应用时,传统关键词匹配无法识别语义关联,召回准确率低,需要轻量高效的工具将文本转化为可计算的语义向量,降低业务落地门槛。
- 适合什么团队
- 需要搭建英文语义检索、内容聚类、相似文本匹配能力的企业业务团队、AI应用开发团队,尤其是对模型运行效率有要求的团队。
- 使用前注意
- 该模型仅支持英文文本处理,输入文本超过256个词片会被自动截断;采用Apache-2.0许可,可自由商用,部署需配套对应运行环境。
本页用于缩短初步筛选时间,不构成技术、采购或法律结论。 正式使用前请在真实业务数据上验证,并以官方说明与许可证为准。
从官方资料看清能力、部署与采用边界
以下内容依据项目公开 README 或模型卡翻译整理,代码、命令和产品名保持原样。
项目导读
项目定位
all-MiniLM-L6-v2是sentence-transformers系列的开源英文文本编码模型,核心能力是将输入的句子、短段落映射为384维的稠密语义向量,是RAG(检索增强生成,大语言模型应用中用于补充外部知识库信息的常用技术方案)、语义搜索等应用的常用基础组件。
核心能力
该模型基于MiniLM架构轻量化设计,适配PyTorch、TensorFlow、ONNX、OpenVINO等多种主流运行框架,可适配不同的部署环境。模型基于超过11亿句覆盖多场景的英文句子对训练完成,训练数据涵盖 Reddit 对话、学术文献、问答社区内容、代码库等多个领域,生成的语义向量可捕捉文本的语义关联,可直接用于语义相似度计算、聚类、信息检索等任务。
典型使用方式
该模型有两种主流使用方式,均可从Hugging Face平台直接调取使用:
- 基于sentence-transformers库使用:安装对应库后仅需少量代码即可完成向量生成,适合快速落地场景:
pip install -U sentence-transformersfrom sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
embeddings = model.encode(sentences)
print(embeddings)- 基于HuggingFace Transformers库使用:无需安装sentence-transformers,自行实现池化逻辑即可调用,适合需要灵活定制处理流程的场景,代码示例如下:
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F
#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
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)
# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
# Normalize embeddings
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)适用业务场景
该模型可支持多种英文文本类业务场景:
- 语义检索:用于英文知识库、帮助中心、文档库的智能检索,基于语义匹配返回相关内容,解决关键词匹配漏召回的问题;
- 内容聚类:对英文客服工单、用户评论、社媒内容等进行自动聚类分类,降低人工标注成本;
- 相似文本匹配:用于重复问答识别、内容去重、相似内容推荐等场景;
- RAG应用召回:作为RAG应用的召回层组件,将用户query和知识库内容转为向量后匹配,提升召回准确率。
使用注意事项
- 语言限制:该模型仅支持英文文本处理,不可直接用于中文等其他语言的向量生成,否则效果无法保障;
- 输入长度限制:默认输入文本超过256个词片会被自动截断,长文本需要提前做分段处理后再生成向量;
- 许可说明:该模型采用Apache-2.0开源许可,企业可自由商用、修改、二次分发,无版权限制。
部署与采用建议
该模型轻量化程度高,普通配置的服务器即可运行,也可转换为ONNX等格式进一步降低资源占用,适合对运行效率要求较高的场景。如果企业有垂直领域的特殊需求,也可基于该模型用自有领域数据集做微调,提升垂直场景的向量生成准确率。
官方资料与来源
- sentence-transformers
- pytorch
- tf
- rust
- onnx
- safetensors
- openvino
- bert
- feature-extraction
- sentence-similarity
- transformers
- en
核对上游原始说明节选
任务类型:sentence-similarity
all-MiniLM-L6-v2
This is a sentence-transformers model: It maps sentences & paragraphs to a 384 dimensional dense vector space and can be used for tasks like clustering or semantic search.
Usage (Sentence-Transformers)
Using this model becomes easy when you have sentence-transformers installed:
pip install -U sentence-transformersThen you can use the model like this:
from sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
embeddings = model.encode(sentences)
print(embeddings)Usage (HuggingFace Transformers)
Without sentence-transformers, you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F
#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
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)
# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# Compute token embeddings
with torch.no_grad():
model_output = model(**encoded_input)
# Perform pooling
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
# Normalize embeddings
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)------
Background
The project aims to train sentence embedding models on very large sentence level datasets using a self-supervised contrastive learning objective. We used the pretrained nreimers/MiniLM-L6-H384-uncased model and fine-tuned in on a 1B sentence pairs dataset. We use a contrastive learning objective: given a sentence from the pair, the model should predict which out of a set of randomly sampled other sentences, was actually paired with it in our dataset.
We developed this model during the Community week using JAX/Flax for NLP & CV, organized by Hugging Face. We developed this model as part of the project: Train the Best Sentence Embedding Model Ever with 1B Training Pairs. We benefited from efficient hardware infrastructure to run the project: 7 TPUs v3-8, as well as intervention from Googles Flax, JAX, and Cloud team member about efficient deep learning frameworks.
Intended uses
Our model is intended to be used as a sentence and short paragraph encoder. Given an input text, it outputs a vector which captures the semantic information. The sentence vector may be used for information retrieval, clustering or sentence similarity tasks.
By default, input text longer than 256 word pieces is truncated.
Training procedure
Pre-training
We use the pretrained nreimers/MiniLM-L6-H384-uncased model. Please refer to the model card for more detailed information about the pre-training procedure.
Fine-tuning
We fine-tune the model using a contrastive objective. Formally, we compute the cosine similarity from each possible sentence pairs from the batch. We then apply the cross entropy loss by comparing with true pairs.
Hyper parameters
We trained our model on a TPU v3-8. We train the model during 100k steps using a batch size of 1024 (128 per TPU core). We use a learning rate warm up of 500. The sequence length was limited to 128 tokens. We used the AdamW optimizer with a 2e-5 learning rate. The full training script is accessible in this current repository: trainscript.py.
Training data
We use the concatenation from multiple datasets to fine-tune our model. The total number of sentence pairs is above 1 billion sentences. We sampled each dataset given a weighted probability which configuration is detailed in the dataconfig.json file.
| Dataset | Paper | Number of training tuples | |--------------------------------------------------------|:----------------------------------------:|:--------------------------:| | Reddit comments (2015-2018) | paper | 726,484,430 | | S2ORC Citation pairs (Abstracts) | paper | 116,288,806 | | WikiAnswers Duplicate question pairs | paper | 77,427,422 | | PAQ (Question, Answer) pairs | paper | 64,371,441 | | S2ORC Citation pairs (Titles) | paper | 52,603,982 | | S2ORC (Title, Abstract) | paper | 41,769,185 | | Stack Exchange (Title, Body) pairs | - | 25,316,456 | | Stack Exchange (Title+Body, Answer) pairs | - | 21,396,559 | | Stack Exchange (Title, Answer) pairs | - | 21,396,559 | | MS MARCO triplets | paper | 9,144,553 | | GOOAQ: Open Question Answering with Diverse Answer Types | paper | 3,012,496 | | Yahoo Answers (Title, Answer) | paper | 1,198,260 | | Code Search | - | 1,151,414 | | COCO Image captions | paper | 828,395| | SPECTER citation triplets | paper | 684,100 | | Yahoo Answers (Question, Answer) | paper | 681,164 | | Yahoo Answers (Title, Question) | paper | 659,896 | | SearchQA | paper | 582,261 | | Eli5 | paper | 325,475 | | Flickr 30k | paper | 317,695 | | Stack Exchange Duplicate questions (titles) | | 304,525 | | AllNLI (SNLI and MultiNLI | paper SNLI, paper MultiNLI | 277,230 | | Stack Exchange Duplicate questions (bodies) | | 250,519 | | Stack Exchange Duplicate questions (titles+bodies) | | 250,460 | | Sentence Compression | paper | 180,000 | | Wikihow | paper | 128,542 | | Altlex | paper | 112,696 | | Quora Question Triplets | - | 103,663 | | Simple Wikipedia | paper | 102,225 | | Natural Questions (NQ) | paper | 100,231 | | SQuAD2.0 | paper | 87,599 | | TriviaQA | - | 73,346 | | Total | | 1,170,060,424 |