開源向量LLM - Qwen3-Embedding

1 Qwen3-Embedding介紹

Qwen3-Embedding遵循?Apache 2.0 許可證,模型大小從0.6B到8B,支持32k長文本編碼。

Model TypeModelsSizeLayersSequence LengthEmbedding DimensionMRL SupportInstruction Aware
Text EmbeddingQwen3-Embedding-0.6B0.6B2832K1024YesYes
Text EmbeddingQwen3-Embedding-4B4B3632K2560YesYes
Text EmbeddingQwen3-Embedding-8B8B3632K4096YesYes
Text RerankingQwen3-Reranker-0.6B0.6B2832K--Yes
Text RerankingQwen3-Reranker-4B4B3632K--Yes
Text RerankingQwen3-Reranker-8B8B3632K--Yes

2 sentence-transformers示例

安裝sentence-transformers

pip install -U sentence-transformers -i https://pypi.tuna.tsinghua.edu.cn/simple

代碼示例

import os
os.environ['HF_ENDPOINT'] = "https://hf-mirror.com"# Requires transformers>=4.51.0
# Requires sentence-transformers>=2.7.0import torch
from sentence_transformers import SentenceTransformer# Load the model
model = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B")# We recommend enabling flash_attention_2 for better acceleration and memory saving,
# together with setting `padding_side` to "left":
# model = SentenceTransformer(
#     "Qwen/Qwen3-Embedding-0.6B",
#     model_kwargs={"attn_implementation": "flash_attention_2", "device_map": "auto"},
#     tokenizer_kwargs={"padding_side": "left"},
# )# The queries and documents to embed
queries = ["What is the capital of China?","Explain gravity",
]
documents = ["The capital of China is Beijing.","Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
]with torch.no_grad():# Encode the queries and documents. Note that queries benefit from using a prompt# Here we use the prompt called "query" stored under `model.prompts`, but you can# also pass your own prompt via the `prompt` argumentquery_embeddings = model.encode(queries, prompt_name="query")document_embeddings = model.encode(documents)# Compute the (cosine) similarity between the query and document embeddingssimilarity = model.similarity(query_embeddings, document_embeddings)print(similarity)
# tensor([[0.7646, 0.1414], [0.1355, 0.6000]])

3 hf transformers示例

安裝過程參考開源向量LLM - BGE (BAAI General Embedding) -CSDN博客

示例代碼如下

import os
os.environ['HF_ENDPOINT'] = "https://hf-mirror.com"# Requires transformers>=4.51.0
import torch
from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLMdef format_instruction(instruction, query, doc):if instruction is None:instruction = 'Given a web search query, retrieve relevant passages that answer the query'output = "<Instruct>: {instruction}\n<Query>: {query}\n<Document>: {doc}".format(instruction=instruction,query=query, doc=doc)return outputdef process_inputs(pairs):inputs = tokenizer(pairs, padding=False, truncation='longest_first',return_attention_mask=False, max_length=max_length - len(prefix_tokens) - len(suffix_tokens))for i, ele in enumerate(inputs['input_ids']):inputs['input_ids'][i] = prefix_tokens + ele + suffix_tokensinputs = tokenizer.pad(inputs, padding=True, return_tensors="pt", max_length=max_length)for key in inputs:inputs[key] = inputs[key].to(model.device)return inputs@torch.no_grad()
def compute_logits(inputs, **kwargs):batch_scores = model(**inputs).logits[:, -1, :]true_vector = batch_scores[:, token_true_id]false_vector = batch_scores[:, token_false_id]batch_scores = torch.stack([false_vector, true_vector], dim=1)batch_scores = torch.nn.functional.log_softmax(batch_scores, dim=1)scores = batch_scores[:, 1].exp().tolist()return scorestokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Reranker-0.6B", padding_side='left')
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B").eval()# We recommend enabling flash_attention_2 for better acceleration and memory saving.
# model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-Reranker-0.6B", torch_dtype=torch.float16, attn_implementation="flash_attention_2").cuda().eval()token_false_id = tokenizer.convert_tokens_to_ids("no")
token_true_id = tokenizer.convert_tokens_to_ids("yes")
max_length = 8192prefix = "<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n"
suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)
suffix_tokens = tokenizer.encode(suffix, add_special_tokens=False)task = 'Given a web search query, retrieve relevant passages that answer the query'queries = ["What is the capital of China?","Explain gravity",
]documents = ["The capital of China is Beijing.","Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
]pairs = [format_instruction(task, query, doc) for query, doc in zip(queries, documents)]# Tokenize the input texts
inputs = process_inputs(pairs)
scores = compute_logits(inputs)print("scores: ", scores)

reference

---

Qwen3-Embeeding

https://github.com/QwenLM/Qwen3-Embedding

vllm-on-intel-extension-for-pytorch

https://github.com/malcolmchanhaoxian/VLLM-on-Intel-Extension-for-Pytorch-

vllm cpu

https://vllm.hyper.ai/docs/getting-started/installation/cpu/

理解 Hugging Face 的 AutoModel 系列:不同任務的自動模型加載類

https://blog.csdn.net/weixin_42426841/article/details/142236561

圖像特征提取

https://hugging-face.cn/docs/transformers/tasks/image_feature_extraction

理解 Hugging Face 的 AutoModel 系列:不同任務的自動模型加載類

https://zhuanlan.zhihu.com/p/721062232

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/91613.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/91613.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/91613.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

云計算服務模式全解析:IaaS、PaaS、SaaS與DaaS的區別與應用

一、云計算概述 云計算是一種通過互聯網提供計算服務的模式&#xff0c;其核心特點是輸入/輸出與計算不在同一主機上。一個完整的云計算環境由云端&#xff08;計算設備&#xff09;、計算機網絡和終端&#xff08;輸入/輸出設備&#xff09;三部分組成&#xff0c;即"云…

qwen 多模態 預訓練流程步驟詳細介紹

Qwen&#xff08;通義千問&#xff09;是阿里云推出的大語言模型&#xff0c;其多模態預訓練是一個復雜且專業的過程&#xff0c;雖然官方沒有完全公開全部細節&#xff0c; 但從多模態大模型通用的預訓練邏輯上&#xff0c;一般包含以下主要步驟&#xff1a; 數據準備 多模態數…

FastDDS (SharedMemory)

SharedMemSegment Start // Fast-DDS/src/cpp/utils/shared_memory/SharedMemSegment.hppclass SharedSegmentBase {內部類 start class Id { public:typedef UUID<8> type;Id(); // 返回共享內存變量的IDId(const Id& other); // 設置共享內存變量的IDvoid g…

sqli-labs:Less-5關卡詳細解析

1. 思路&#x1f680; 本關的SQL語句為&#xff1a; $sql"SELECT * FROM users WHERE id$id LIMIT 0,1";注入類型&#xff1a;字符串型&#xff08;單引號包裹&#xff09;提示&#xff1a;參數id需以閉合 但有意思的是&#xff0c;php代碼的輸出語句不是如下這種…

標準項目-----網頁五子棋(4)-----游戲大廳+匹配+房間代碼

頁面實現 hall.html <!DOCTYPE html> <html lang"ch"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>游戲大廳</title><l…

MySQL分析步

MySQL分析 -- 庫名 set dbName bsa_crmeb_bak; -- 表名 set tableName bsa_crmeb_bak;-- 查看bsa_crmeb_bak數據庫基本信息 SELECTSCHEMA_NAME AS 數據庫名,DEFAULT_CHARACTER_SET_NAME AS 字符集,DEFAULT_COLLATION_NAME AS 排序規則 FROM information_schema.SCHEMATA WHER…

工程化(二):為什么你的下一個項目應該使用Monorepo?(pnpm / Lerna實戰)

工程化(二)&#xff1a;為什么你的下一個項目應該使用Monorepo&#xff1f;&#xff08;pnpm / Lerna實戰&#xff09; 引子&#xff1a;前端項目的“孤島困境” 隨著你的項目或團隊不斷成長&#xff0c;一個棘手的問題會逐漸浮現&#xff1a;代碼該如何組織&#xff1f; 最…

應用藥品注冊證識別技術,為醫藥行業的合規、高效與創新發展提供核心驅動力

在醫藥行業的龐雜數據海洋中&#xff0c;藥品注冊證&#xff08;如中國的“國藥準字”、美國的NDA/ANDA批號&#xff09;是藥品合法上市流通的“身份證”。面對海量的證書審核、錄入與驗證需求&#xff0c;傳統人工處理方式不僅效率低下、成本高昂&#xff0c;更易因疲勞導致差…

Spring Boot 2.1.18 集成 Elasticsearch 6.6.2 實戰指南

Spring Boot 2.1.18 集成 Elasticsearch 6.6.2 實戰指南前言&#xff1a;一. JAVA客戶端對比二. 導入數據2.1 分析創建索引2.2 代碼實現三. ElasticSearch 查詢3.1 matchAll 查詢3.2 term查詢3.3 match查詢3.4 模糊查詢3.5 范圍查詢3.6 字符串查詢3.7 布爾查詢3.8 分頁與排序3.…

向量投影計算,舉例說明

向量投影計算,舉例說明 向量投影是指將一個向量(設為向量b\mathbf{b}b)投射到另一個向量(設為向量a\mathbf{a}a)所在直線上,得到一個與a\mathbf{a}

如何在技術世界中保持清醒和高效

“抽象泄露&#xff0c;是存在的&#xff0c;但你需要了解多少&#xff0c;需要理解多深&#xff0c;這一點是因人而異的&#xff0c;絕對不是別人能夠建議的。每個人只會站在自己的立場上去建議別人怎么做。”在寫下這句話時&#xff0c;身為一個技術開發者&#xff0c;我似乎…

服裝公司數字化轉型如何做?

WL貿易集團公司&#xff08;以下簡稱WL&#xff09;自2012年成立以來&#xff0c;在十余年的發展歷程中不斷蛻變與升級。公司始終秉持“時尚與品質優先”的核心經營理念&#xff0c;通過嚴格執行高標準、嚴要求&#xff0c;牢牢把握產品品質與交貨周期兩大關鍵&#xff0c;贏得…

GM DC Monitor 之 銀河麒麟 Docker 部署安裝手冊

官方網站&#xff1a;www.gm-monitor.com 本手冊以銀河麒麟為例&#xff0c;介紹在 Linux 系統上安裝和配置DOCKER服務的詳細步驟 一、以root用戶執行以下操作命令 1、環境優化 modprobe br_netfilter cat <<EOF > /etc/sysctl.d/docker.conf net.bridge.bridge-n…

網絡編程接口bind學習

1、概述下面2個問題你會怎么回答呢?1、bind如果綁定0號端口&#xff0c;可以工作么&#xff0c;如果能正常工作&#xff0c;綁定的什么端口 2、客戶端可以調用bind么2、解析2.1、bind如果綁定0號端口&#xff0c;可以工作么&#xff0c;如果能正常工作&#xff0c;綁定的什么端…

FinOps X 2025 核心發布:AI 時代下的 FinOps 轉型

2025年&#xff0c;人工智能技術的突破性發展正深刻重塑商業與技術格局&#xff0c;智能技術已成為各領域創新的核心驅動力。在此背景下&#xff0c;FinOps X 2025 圍繞 AI 技術對財務運營&#xff08;FinOps&#xff09;的革新作用展開深度探討&#xff0c;重點呈現了以下關鍵…

使用Min-Max進行數據特征標準化

在數據處理過程中&#xff0c;標準化是非常重要的步驟之一&#xff0c;特別是在機器學習和數據分析中。Min-Max標準化&#xff08;也稱為歸一化&#xff09;是一種常用的數據標準化方法&#xff0c;它通過將數據縮放到一個指定的范圍&#xff08;通常是0到1之間&#xff09;&am…

【Dart 教程系列第 51 篇】Iterable 中 reduce 函數的用法

這是【Dart 教程系列第 51 篇】,如果覺得有用的話,歡迎關注專欄。 博文當前所用 Dart SDK:3.5.4 文章目錄 一:reduce 作用 二:舉例說明 1:求和 2:查找最大/最小值 3:字符串拼接 4:自定義對象合并 三:注意事項 一:reduce 作用 reduce 是 Iterable 的一個方法,用于…

使用VSCode配置Flutter

本周&#xff08;學期第四周&#xff09;任務&#xff1a; 1.簡單學習Flutter&#xff0c;完成環境安裝與配置 2.探索Flutter與Unity集成方案 一、Flutter環境配置 根據Flutter官方文檔進行環境配置&#xff1a;開發 Android 應用 | Flutter 中文文檔 - Flutter 中文開發者網…

React 開發中遇見的低級錯誤

1.useState不起效果 異步 改用 useRef2.map循環{ WechatQuestionnaireData && WechatQuestionnaireData?.questions?.map((item: any) > (<div className{styles[title]}>{item.questionTitle}</div>))}注意這里的 》 后面是括號 我開始寫成{} 好久…

iphone手機使用charles代理,chls.pro/ssl 后回車 提示瀏覽器打不開該網頁

iphone手機使用charles代理,chls.pro/ssl 后回車 提示瀏覽器打不開該網頁) 1、問題現狀&#xff1a; Charles安裝證書異常問題&#xff0c;網頁訪問chls.pro/ssl提示網頁打不開&#xff0c;在charles頁面有鏈接&#xff0c;可以看到http請求和https就是看不到詳細內容 2、解決方…