轻量级文本嵌入模型 - EmbeddingGemma
Gemma 3n是谷歌利用利用MatFormer架构打造的轻量化端侧大模型,借由嵌套式结构实现了低内存消耗设计。其中embeddinggemma轻量级文本嵌入模型,gemma3n:e2b为轻量级文本生成模型,适合低延迟、高吞吐量场景,例如智能手机、物联网设备的实时文本处理。
1 model download
1.1 gemma 3n
gemma模型信息如下
embeddinggemma
https://huggingface.co/google/embeddinggemma-300m
https://huggingface.co/collections/google/embeddinggemma-68b9ae3a72a82f0562a80dc4
Gemma 3n
其4b量化版和Qwen3-4B功能差不多,但响应速度要快很多,而且gemma 3n是多模态模型。
https://huggingface.co/collections/google/gemma-3n-685065323f5984ef315c93f4
https://www.modelscope.cn/models/google/gemma-3n-E4B
1.2 gemma下载
ollama下载embeddinggemma模型,为简化操作,这里采用docker版本的ollama。
假设docker已经安装,linux安装docker参考
https://blog.csdn.net/liliang199/article/details/150067330
参考 https://hub.docker.com/r/ollama/ollama,docker启动ollama
docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
bash进入ollama docker容器,提供在容器中操作ollama的bash界面
docker exec -it ollama bash
以下是ollama下载指令
ollama pull embeddinggemma
ollama pull gemma3n:e2bollama pull embeddinggemma:300m
gemma3n:e2b由于模型比较大,可能下载会中断,可以直接从国内源下载,比如modelscope
ollama pull modelscope.cn/ggml-org/gemma-3n-E2B-it-GGUF
2 环境准备
python环境安装,这里采用conda方式
conda create -n gemma python=3.12
conda activate gemma
conda install ninja
conda install -c conda-forge gcc=12 gxx=12
pip install uv -i https://pypi.tuna.tsinghua.edu.cn/simpl
3 安装embeddinggemma
embeddinggemma rag demo见如下git项目。
https://github.com/jimmyliao/lab-embeddinggemma
git clone embeddinggemma项目,如果git clone失败,可以尝试直接下载zip包方式
git clone https://github.com/jimmyliao/lab-embeddinggemma.git
安装embeddinggemma
cd lab-embeddinggemma
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
4 测试embeddinggemma
4.1 embedding测试
测试程序如下
import requests
import jsondef get_embedding(prompt: str, model: str = "embeddinggemma:latest", url: str = "http://localhost:11434/api/embeddings"):"""Fetches an embedding vector for a given prompt from the Ollama API.Args:prompt (str): The text prompt to get the embedding for.model (str): The Ollama model to use for embedding.url (str): The URL of the Ollama embeddings API endpoint.Returns:list: The embedding vector if successful, None otherwise."""payload = {"model": model,"prompt": prompt}try:response = requests.post(url, data=json.dumps(payload))response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)response_data = response.json()embedding_vector = response_data.get("embedding")if embedding_vector:return embedding_vectorelse:print("Error: 'embedding' field not found in the response.")return Noneexcept requests.exceptions.HTTPError as http_err:print(f"HTTP error occurred: {http_err} - Response: {http_err.response.text}")except requests.exceptions.ConnectionError as conn_err:print(f"Connection error occurred: {conn_err} - Is Ollama server running at {url}?")except requests.exceptions.Timeout as timeout_err:print(f"Timeout error occurred: {timeout_err}")except requests.exceptions.RequestException as req_err:print(f"An unexpected request error occurred: {req_err}")except json.JSONDecodeError as json_err:print(f"Failed to decode JSON response: {json_err} - Response text: {response.text}")return None
运行如下命令
python main.py
输出如下
成功取得嵌入向量!
向量前 5 維: [-0.15188363194465637, 0.016393350437283516, 0.02211342193186283, 0.001807519467547536, -0.02730322815477848]
向量總維度: 768
4.2 rag测试
示例程序如下
import numpy as np
import requests
import json
from embedding_utils import get_embeddingdef cosine_similarity(vec1, vec2):return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))def generate_response_with_ollama(query: str, context_sentences: list[str], llm_model: str = "gemma3n:e2b", ollama_url: str = "http://localhost:11434/api/generate"):context = "\n".join(context_sentences)prompt = f"根據以下提供的上下文來回答問題。如果答案不在上下文中,請說明你不知道。\n\n上下文:\n{context}\n\n問題: {query}\n答案:"payload = {"model": llm_model,"prompt": prompt,"stream": False # For simplicity, we'll get the full response at once}try:response = requests.post(ollama_url, data=json.dumps(payload))response.raise_for_status()response_data = response.json()return response_data.get("response", "")except requests.exceptions.RequestException as e:print(f"生成回應時發生錯誤: {e}")return ""# 從 intro_embeddinggemma.txt 讀取中文內容
with open("intro_embeddinggemma.txt", "r", encoding="utf-8") as f:chinese_text = f.read()# 將文本分割成句子或段落作為知識庫
corpus_sentences = []
paragraphs = chinese_text.split('\n')
for para in paragraphs:if not para.strip():continue# Split by common Chinese sentence-ending punctuationsentences_in_para = []temp_sentences = para.split('。')for s in temp_sentences:sentences_in_para.extend(s.split('!'))final_sentences = []for s in sentences_in_para:final_sentences.extend(s.split('?'))for s in final_sentences:s_stripped = s.strip()if s_stripped:corpus_sentences.append(s_stripped)print("正在為知識庫中的句子生成嵌入向量...")
corpus_embeddings = []
for i, sentence in enumerate(corpus_sentences):print(f"處理句子 {i+1}/{len(corpus_sentences)}: {sentence[:20]}...")embedding = get_embedding(sentence)if embedding:corpus_embeddings.append((sentence, np.array(embedding)))else:print(f"警告: 無法為句子 '{sentence[:30]}...' 獲取嵌入向量")print("知識庫嵌入完成。")# 定義查詢
queries = ["EmbeddingGemma 支援幾種語言","EmbeddingGemma 與 Gemma3n 的關聯是什麼","EmbeddingGemma 的主要功能是什麼"
]for query in queries:print(f"\n--- 處理查詢: {query} ---")query_embedding = get_embedding(query)if query_embedding is None:print("錯誤: 無法為查詢獲取嵌入向量。")continuequery_embedding = np.array(query_embedding)similarities = []for sentence, sentence_embedding in corpus_embeddings:sim = cosine_similarity(query_embedding, sentence_embedding)similarities.append((sim, sentence))similarities.sort(key=lambda x: x[0], reverse=True)print("最相關的句子:")retrieved_sentences = []for sim, sentence in similarities[:3]: # 顯示前3個最相關的句子print(f" 相似度: {sim:.4f} - {sentence}")retrieved_sentences.append(sentence)# 增強生成部分print("\n正在生成回應...")generated_response = generate_response_with_ollama(query, retrieved_sentences)print(f"生成的回應:\n{generated_response}")
运行如下命令
python lang_test.py
输出:
正在為知識庫中的句子生成嵌入向量...
處理句子 1/16: EmbeddingGemma 模型總覽...
處理句子 2/16: EmbeddingGemma 是以 Ge...
處理句子 3/16: 這項技術經過最佳化,適用於手機、筆電和平...
處理句子 4/16: 模型會產生文字的數值表示法,用於資訊檢索...
處理句子 5/16: EmbeddingGemma 包含下列重...
處理句子 6/16: 支援多種語言:可理解多種語言的資料,並以...
處理句子 7/16: 彈性輸出尺寸:使用 Matryoshka...
處理句子 8/16: 2K 權杖內容:提供大量輸入內容,可直接...
處理句子 9/16: 節省儲存空間:透過量化在 RAM 不到 ...
處理句子 10/16: 低延遲:在 EdgeTPU 上生成嵌入內...
處理句子 11/16: 離線安全:直接在硬體上生成文件嵌入內容,...
處理句子 12/16: 提示: 使用 Gemma 3n 部署 E...
處理句子 13/16: 如要開始使用,請參閱快速入門 RAG 筆...
處理句子 14/16: 在 Hugging Face 上取得 在...
處理句子 15/16: 與其他 Gemma 模型一樣,Embed...
處理句子 16/16: source: https://ai.g...
知識庫嵌入完成。--- 處理查詢: EmbeddingGemma 支援幾種語言 ---
最相關的句子:
相似度: 0.8919 - EmbeddingGemma 模型總覽
相似度: 0.8065 - EmbeddingGemma 包含下列重要功能:
相似度: 0.7408 - source: https://ai.google.dev/gemma/docs/embeddinggemma?hl=zh-tw正在生成回應...
生成的回應:
根據提供的上下文,EmbebedingGemma 模型支援 **不清楚** 幾種語言。 上下文只提到它包含 "重要功能",沒有具體說明支援哪些語言。 網址 `https://ai.google.dev/gemma/docs/embeddinggemma?hl=zh-tw` 應該是關於 EmbeddingGemma 的官方文件,其中可能包含語言支援資訊,但上下文沒有提供連結的內容。因此,我**不知道** EmbeddingGemma 支援幾種語言。
--- 處理查詢: EmbeddingGemma 與 Gemma3n 的關聯是什麼 ---
最相關的句子:
相似度: 0.8640 - EmbeddingGemma 模型總覽
相似度: 0.7804 - EmbeddingGemma 包含下列重要功能:
相似度: 0.7604 - EmbeddingGemma 是以 Gemma 3 為基礎的 3.08 億參數多語言文字嵌入模型正在生成回應...
生成的回應:
EmbbeddingGemma 是以 Gemma 3 為基礎的 3.08 億參數多語言文字嵌入模型。因此,EmbbeddingGemma 與 Gemma3n 的關聯是:**EmbbeddingGemma 是以 Gemma 3 為基礎的。**
更具體地說,EmbbeddingGemma 建立在 Gemma 3 的基礎上。
--- 處理查詢: EmbeddingGemma 的主要功能是什麼 ---
最相關的句子:
相似度: 0.9185 - EmbeddingGemma 包含下列重要功能:
相似度: 0.8369 - EmbeddingGemma 模型總覽
相似度: 0.6750 - 2K 權杖內容:提供大量輸入內容,可直接在硬體上處理文字資料和文件正在生成回應...
生成的回應:
EmbbeddingGemma 包含下列重要功能:提供大量輸入內容,可直接在硬體上處理文字資料和文件。因此,EmbbeddingGemma 的主要功能是 **提供大量輸入內容,可直接在硬體上處理文字資料和文件**。
附件
问题1: ollama pull超时,并超过最大重试次数退出。
ollama Error: max retries exceeded: Get " ..... : net/http: TLS handshak
解决方案: 重启ollama
ps aux | grep ollama # 找到ollama进程kill
nohup ollama serve > ollama.log &
问题2: embeddinggemma缺乏embedding tag,导致模型运行报错。
this model does not support embeddings
方案: upgrad ollama,或者使用docker版本的ollama,docker 版一般会使用使用最新的ollama。
https://hub.docker.com/r/ollama/ollama
https://docs.ollama.com/docker
reference
---
Gemma 3n
https://ai.google.dev/gemma/docs/gemma-3n
embeddinggema
https://github.com/jimmyliao/lab-embeddinggemma
embeddinggemma-300m
https://huggingface.co/google/embeddinggemma-300m
Docker安装Ollama及使用Ollama部署大模型
https://zhuanlan.zhihu.com/p/1902057589019251082
ollama/ollama
https://hub.docker.com/r/ollama/ollama
docker ollama
https://docs.ollama.com/docker
Ollma通过国内源实现模型本地化部署
https://blog.csdn.net/Water_Jack/article/details/147600755