ai-sage_Giga-Embeddings-instruct
ai-sage · View on Hugging Face ↗
Model card
The complete upstream card, rendered from this payload's README.md — the same hash-verified bytes the torrent distributes. Images and off-site links are removed; the original card on Hugging Face carries them.
license: mit language:
- ru
- en pipeline_tag: feature-extraction tags:
- MTEB
- transformers library_name: sentence-transformers
Giga-Embeddings-instruct
- Base Decoder-only LLM: GigaChat-3b
- Pooling Type: Latent-Attention
- Embedding Dimension: 2048
Для получения более подробной информации о технических деталях, пожалуйста, обратитесь к нашей статье.
Использование
Ниже приведен пример кодирования запросов и текстов.
Requirements
pip install -q transformers==4.51.0 sentence-transformers==5.1.1 flash-attn langchain_community langchain_huggingface langchain_gigachat
Transformers
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]]
Sentence Transformers
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]])
LangChain
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-задач (например, поиск ответа в тексте) можно использовать инструкцию:'Дан вопрос, необходимо найти абзац текста с ответом'.
Такой подход особенно эффективен для задач поиска и извлечения информации, таких как поиск релевантных документов или извлечение ответов из текста.
Примеры инструкций для retrieval-задач:
'Дан вопрос, необходимо найти абзац текста с ответом''Given the question, find a paragraph with the answer'
Инструкции необходимо оборачивать в шаблон: f'Instruct: {task_description}\nQuery: {query}'. Использование инструкций позволяет значительно улучшить качество поиска и релевантность результатов, что подтверждается тестами на бенчмарках, таких как RuBQ, MIRACL. Для симметричных задач добавление инструкции перед каждым запросом обеспечивает согласованность и повышает точность модели.
Поддерживаемые языки
Эта модель инициализирована pretrain моделью GigaChat и дополнительно обучена на смеси английских и русских данных.
FAQ
- Нужно ли добавлять инструкции к запросу?
Да, именно так модель обучалась, иначе вы увидите снижение качества. Определение задачи должно быть инструкцией в одном предложении, которая описывает задачу. Это способ настройки текстовых эмбеддингов для разных сценариев с помощью инструкций на естественном языке.
С другой стороны, добавлять инструкции на сторону документа не требуется.
- Почему мои воспроизведённые результаты немного отличаются от указанных в карточке модели?
Разные версии библиотек transformers и pytorch могут вызывать незначительные, но ненулевые различия в результатах.
Ограничения
Использование этой модели для входных данных, содержащих более 4096 токенов, невозможно.
Magnet link
Opens the swarm directly in your torrent client — no file download needed. Copy-paste works too:
magnet:?xt=urn:btih:f39e1de4e0c21b63ddc01a65025f2665bfb32f01&dn=ai-sage_Giga-Embeddings-instructOpen magnet in torrent client · infohash f39e1de4e0c21b63ddc01a65025f2665bfb32f01
Files & hashes
| Path | Size | sha1 | sha256 |
|---|---|---|---|
| 1_Pooling/config.json | 313 B (313 B) | 86b6c4d22acc1b0db64cefcf79aabb80413d4a69 | 2bc529695125f68de57d1fd347e3d2920b993bc635c5f4f09a45e130c102a989 |
| README.md | 9.6 KB (9,864 B) | f71a68861113d34664e9708f3ba1fef6fbfca022 | f35fbf27dfdfc7aa96f12a6a89adf224603421c794aee1a7792c72e5a1b010f9 |
| config.json | 5.8 KB (5,895 B) | 15d0f3b4a2bec4ffbcbb00fdaaac26f20156b245 | 3d29a7884a422634115f3597bf111a898c068b53e2152b214f8ec02f2c0edf53 |
| config_sentence_transformers.json | 283 B (283 B) | 1c0521c4a54ff9e489f141637e1241756d9d174b | 9986c6b1724526135bb80978ae31b52aa650ed1f85149c2ccedc2453f05bce79 |
| configuration_gigarembed.py | 14.1 KB (14,426 B) | 9d4137ccd8e498edffa4564a80a8e777379bfa62 | 0b34786d1c8ee25c2df02d427657a89b2bfad4c4cf8f4858f2007bb223668962 |
| model-00001-of-00003.safetensors | 4.61 GB (4,947,550,528 B) | b8116707b1a296b40072115d23d28c3b9bf10723 | 8f58bbc242e82e65d3564fdf09a378b5fbf545e15bc8291d7a623a8873222f6f |
| model-00002-of-00003.safetensors | 4.57 GB (4,912,107,128 B) | cf475705d58c37924a734f25ba0acf8e80adc993 | fe27f921338efe4e1b41a27f6a1c87ca35d6ae933ebd0458ba09c329b63c9ac9 |
| model-00003-of-00003.safetensors | 3.67 GB (3,938,900,016 B) | dd87d124371431f782b63120b9861a333e24ed9a | 90d75a17597fe2351022a4f8638c2509e624b25b1fc08a3d5c5204ec02d7a14b |
| model.safetensors.index.json | 41.9 KB (42,876 B) | 2ec62d17cee73d82ffe22e4ce38640a763df6999 | 0ea03eb0cad1fbb03a3b964ca0793ed6fa224396f63d5b400b1d80c0c3d430ee |
| modeling_gigarembed.py | 43.1 KB (44,149 B) | 311e14635cce945063410dcb617e8d6c1947c6d7 | d75a06519ffacd39bce2608ceedc56818c072430e1072f26f7aa0b570b3f7ba2 |
| modules.json | 349 B (349 B) | 952a9b81c0bfd99800fabf352f69c7ccd46c5e43 | 84e40c8e006c9b1d6c122e02cba9b02458120b5fb0c87b746c41e0207cf642cf |
| sentence_bert_config.json | 58 B (58 B) | 39d908c9d6d05ec190612fa8e4d2594e1b18351a | 82236913f81b129ce9a63581f29676c37ec71d7ba2ab1839f24dc03827e14aab |
| special_tokens_map.json | 690 B (690 B) | bdb1761a44cf997c99aba88c52a5a8d9a74f3e55 | 7df9ebc543a0f1a8ac54fd979387f97e324f99c8339da718243fd58889ee8060 |
| tokenizer.json | 10.2 MB (10,728,325 B) | 42d93a9fa2b0ffdecac0264534406d360fbbb81a | 0ec0a1cffcc9192f5ee3d7b273673a062918055238bda3d23cfb6d2512e947ff |
| tokenizer_config.json | 47.0 KB (48,144 B) | 85204858eb197a216cb25a03bb1d1794489e1f48 | 3e0e79212f9ff591db2fb29e3820c8fc19d585232274c77dab496e1ba98eaf4c |
Cite this release
- Canonical URL
- https://aiseedbank.org/models/ai-sage_Giga-Embeddings-instruct/
- Slug
- ai-sage_Giga-Embeddings-instruct
- Infohash
- f39e1de4e0c21b63ddc01a65025f2665bfb32f01
- License
- mit
- Signing key fingerprint
- 85a3b32c3712427b
Every file carries a locally computed sha256 — verify a download against the signed sums: ai-sage_Giga-Embeddings-instruct.SHA256SUMS (+ minisign signature).
Provenance
| Upstream repository | ai-sage/Giga-Embeddings-instruct |
|---|---|
| Revision (pinned) | 2cf0fdc97194aaedf10ac0e6bf798834acd31042 |
| Fetched at | 2026-09-03T20:47:57Z |
| License at fetch | mit |
| Snapshot tool | huggingface · seedbank 0.1.0 |
Trackers
- udp://announce.aitorrent.org:6969/announce
- http://announce.aitorrent.org:7070/announce
- udp://announce2.aitorrent.org:6970/announce
- http://announce2.aitorrent.org:7071/announce
- udp://tracker.opentrackr.org:1337/announce
- udp://open.demonii.com:1337/announce
- udp://open.stealth.si:80/announce
- udp://exodus.desync.com:6969/announce
- udp://tracker.torrent.eu.org:451/announce
✓ verified · rehash-vs-hf-metadata at 2026-09-03T20:50:00Z
mit12.86 GB (13,809,453,044 bytes)sentence-transformerssafetensorsgigarembedfeature-extractionMTEBtransformerscustom_codeendpoints_compatible2 languages (ru, en)