Model reference · open weights
Giga-Retrieval is an open-weight embedding model from ai-sage. Giga-Retrieval-instruct (FP32) weighs 5.1 GB; the smallest configuration that runs it is RTX 3060 12 GB.
For self-hosting, compare this build's requirements below with the GPU you plan to rent.
Summary of the ai-sage/Giga-Retrieval-instruct model card, 2026-10-01
What it is
| Released by | ai-sage |
|---|---|
| Released | 2025-05-29 |
| Parameters | 2.5B |
| VRAM | 5.1 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.46.3 sentence-transformers==3.3.1 datasets langchain_community langchain_huggingface langchain_gigachat
import os
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
# Each query needs to be accompanied by an corresponding instruction describing the task.
task_name_to_instruct = {"example": "Given a question, retrieve passages that answer the question",}
query_prefix = task_name_to_instruct["example"] + "\nquestion: "
queries = [
'are judo throws allowed in wrestling?',
'how to become a radiology technician in michigan?'
]
# No instruction needed for retrieval passages
passage_prefix = ""
passages = [
"Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.",
"Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan."
]
# load model with tokenizer
model = AutoModel.from_pretrained('ai-sage/Giga-Retrieval-instruct', trust_remote_code=True)
# get the embeddings
query_embeddings = model.encode(queries, instruction=query_prefix)
passage_embeddings = model.encode(passages, instruction=passage_prefix)
scores = (query_embeddings @ passage_embeddings.T) * 100
print(scores.tolist())
import torch
from langchain_huggingface import HuggingFaceEmbeddings
# Load model
embeddings = HuggingFaceEmbeddings(
model_name='ai-sage/Giga-Retrieval-instruct',
encode_kwargs={},
model_kwargs={
'device': 'cuda', # or 'cpu'
'trust_remote_code': True,
'model_kwargs': {'torch_dtype': torch.bfloat16},
'prompts': {'query': 'Given a question, retrieve passages that answer the question\nquestion: '}
}
)
# 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). Это помогает модели лучше понять контекст и цель запроса, что положительно сказывается на качестве результатов. Важно отметить, что инструкцию нужно добавлять только перед запросом, а не перед документом.
Для retrieval-задач (например, поиск ответа в тексте) можно использовать инструкцию:
'Дан вопрос, необходимо найти абзац текста с ответом \nвопрос: {query}'.
Такой подход особенно эффективен для задач поиска и извлечения информации, таких как поиск релевантных документов или извлечение ответов из текста.
Примеры инструкций для retrieval-задач:
'Дан вопрос, необходимо найти абзац текста с ответом \nвопрос: {query}''Given the question, find a paragraph with the answer \nquestion: {query}'Использование инструкций позволяет значительно улучшить качество поиска и релевантность результатов, что подтверждается тестами на бенчмарках, таких как RuBQ. Для симметричных задач добавление инструкции перед каждым запросом обеспечивает согласованность и повышает точность модели.
Эта модель инициализирована pretrain моделью GigaChat и дополнительно обучена на смеси английских и русских данных. Однако, поскольку pretrain GigaChat'a делался в основном на русскоязычных данных, мы рекомендуем использовать эту модель только для русского языка.
Да, именно так модель обучалась, иначе вы увидите снижение качества. Определение задачи должно быть инструкцией в одном предложении, которая описывает задачу. Это способ настройки текстовых эмбеддингов для разных сценариев с помощью инструкций на естественном языке.
С другой стороны, добавлять инструкции на сторону документа не требуется.
Разные версии библиотек transformers и pytorch могут вызывать незначительные, но ненулевые различия в результатах.
Использование этой модели для входных данных, содержащих более 4096 токенов, невозможно.
Quoted from the model card on Hugging Face. The full card is behind the Hugging Face link above.