Model reference · open weights
Giga-Embeddings is an open-weight embedding model from ai-sage. Giga-Embeddings-instruct (FP32) weighs 6.9 GB; the smallest configuration that runs it is RTX 3060 12 GB.
Summary of the ai-sage/Giga-Embeddings-instruct model card, 2026-10-01
What it is
| Released by | ai-sage |
|---|---|
| Released | 2024-12-11 |
| Parameters | 3.4B |
| VRAM | 6.9 GB for the weights |
What it runs on
| Card | Runs | Memory |
|---|---|---|
| RTX 3060 12 GB | fits | 11.6 GB |
| RTX 4060 Ti 16 GB | fits | 15.4 GB |
| RTX 3090 24 GB | fits | 23.4 GB |
| RTX 4090 24 GB | fits | 23.4 GB |
| RTX 5090 32 GB | fits | 31.0 GB |
| L40S 48 GB | fits | 44.0 GB |
| A100 80 GB | fits | 78.2 GB |
| H100 80 GB | fits | 78.1 GB |
| RTX PRO 6000 Blackwell 96 GB | fits | 93.8 GB |
| DGX Spark (GB10) 128 GB unified | fits | 107 GB |
| H200 141 GB | fits | 138 GB |
| B200 180 GB | fits | 176 GB |
From the model card
Для получения более подробной информации о технических деталях, пожалуйста, обратитесь к нашей статье.
Ниже приведен пример кодирования запросов и текстов.
pip install -q transformers==4.51.0 sentence-transformers==5.1.1 flash-attn langchain_community langchain_huggingface langchain_gigachat
import torch
import torch.nn.functional as F
from torch import Tensor
from transformers import AutoTokenizer, AutoModel
def get_detailed_instruct(task_description: str, query: str) -> str:
return f'Instruct: {task_description}\nQuery: {query}'
# Each query must come with a one-sentence instruction that describes the task
task = 'Given a web search query, retrieve relevant passages that answer the query'
queries = [
get_detailed_instruct(task, 'What is the capital of Russia?'),
get_detailed_instruct(task, 'Explain gravity')
]
# No need to add instruction for retrieval documents
documents = [
"The capital of Russia is Moscow.",
"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."
]
input_texts = queries + documents
# We recommend enabling flash_attention_2 for better acceleration and memory saving.
tokenizer = AutoTokenizer.from_pretrained(
'ai-sage/Giga-Embeddings-instruct',
trust_remote_code=True
)
model = AutoModel.from_pretrained(
'ai-sage/Giga-Embeddings-instruct',
attn_implementation="flash_attention_2",
torch_dtype=torch.bfloat16,
trust_remote_code=True
)
model.eval()
model.cuda()
max_length = 4096
# Tokenize the input texts
batch_dict = tokenizer(
input_texts,
padding=True,
truncation=True,
max_length=max_length,
return_tensors="pt",
)
batch_dict.to(model.device)
embeddings = model(**batch_dict, return_embeddings=True)
scores = (embeddings[:2] @ embeddings[2:].T)
print(scores.tolist())
# [[0.58203125, 0.0712890625], [0.06884765625, 0.62109375]]
import torch
from sentence_transformers import SentenceTransformer
# Load the model
# We recommend enabling flash_attention_2 for better acceleration and memory saving
model = SentenceTransformer(
"ai-sage/Giga-Embeddings-instruct",
model_kwargs={
"attn_implementation": "flash_attention_2",
"torch_dtype": torch.bfloat16,
"trust_remote_code": "True"
},
config_kwargs={
"trust_remote_code": "True"
}
)
model.max_seq_length = 4096
# The queries and documents to embed
queries = [
'What is the capital of Russia?',
'Explain gravity'
]
# No need to add instruction for retrieval documents
documents = [
"The capital of Russia is Moscow.",
"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."
]
# Encode the queries and documents. Note that queries benefit from using a prompt
query_embeddings = model.encode(queries, prompt='Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: ')
document_embeddings = model.encode(documents)
# Compute the (cosine) similarity between the query and document embeddings
similarity = model.similarity(query_embeddings, document_embeddings)
print(similarity)
# tensor([[0.5846, 0.0702],
# [0.0691, 0.6207]])
import torch
from langchain_huggingface import HuggingFaceEmbeddings
# Load model
embeddings = HuggingFaceEmbeddings(
model_name='ai-sage/Giga-Embeddings-instruct',
encode_kwargs={},
model_kwargs={
'device': 'cuda',
'trust_remote_code': True,
'model_kwargs': {'torch_dtype': torch.bfloat16},
'prompts': {'query': 'Instruct: Given a question, retrieve passages that answer the question\nQuery: '}
}
)
# Tokenizer
embeddings._client.tokenizer.tokenize("Hello world! I am GigaChat")
# Query embeddings
query_embeddings = embeddings.embed_query("Hello world!")
print(f"Your embeddings: {query_embeddings[0:20]}...")
print(f"Vector size: {len(query_embeddings)}")
# Document embeddings
documents = ["foo bar", "bar foo"]
documents_embeddings = embeddings.embed_documents(documents)
print(f"Vector size: {len(documents_embeddings)} x {len(documents_embeddings[0])}")
Использование инструкций для улучшения качества эмбеддингов
Для достижения более точных результатов при работе с эмбеддингами, особенно в задачах поиска и извлечения информации (retrieval), рекомендуется добавлять инструкцию на естественном языке перед текстовым запросом (query). Это помогает модели лучше понять контекст и цель запроса, что положительно сказывается на качестве результатов. Важно отметить, что инструкцию нужно добавлять только перед запросом, а не перед документом.
Для симметричных задач, таких как классификация (classification) или семантическое сравнение текстов (semantic text similarity), инструкцию необходимо добавлять перед каждым запросом. Это связано с тем, что такие задачи требуют одинакового контекста для всех входных данных, чтобы модель могла корректно сравнивать или классифицировать их.
Примеры инструкций для симметричных задач:
"Retrieve semantically similar text""Given a text, retrieve semantically similar text""Дано предложение, необходимо найти его парафраз""Классифицируй отзыв на товар как положительный, отрицательный или нейтральный""Классифицируй чувствительную тему по запросу"Для retrieval-задач (например, поиск ответа в тексте) можно использовать инструкцию:
'Дан вопрос, необходимо найти абзац текста с ответом'.
Такой подход особенно эффективен для задач поиска и извлечения информации, таких как поиск релевантны
Quoted from the model card on Hugging Face. The full card is behind the Hugging Face link above.