gurgutan commited on
Commit
5cce8cb
·
verified ·
1 Parent(s): 64ab343

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +213 -3
README.md CHANGED
@@ -1,3 +1,213 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - ru
5
+ - en
6
+ pipeline_tag: feature-extraction
7
+ tags:
8
+ - MTEB
9
+ - transformers
10
+ library_name: sentence-transformers
11
+ ---
12
+ ## giga-embeddings-instruct-bnb-4bit
13
+
14
+ Модель получена квантизацией [ai-sage/Giga-Embeddings-instruct](https://huggingface.co/ai-sage/Giga-Embeddings-instruct) модулем BitsAndBytes в формат 4bit.
15
+
16
+ - Base Decoder-only LLM: GigaChat-3b
17
+ - Pooling Type: Latent-Attention
18
+ - Embedding Dimension: 2048
19
+
20
+ Для получения более подробной информации о технических деталях, пожалуйста, обратитесь к нашей [статье](https://aclanthology.org/2025.bsnlp-1.3/).
21
+
22
+ ## Использование
23
+
24
+ Ниже приведен пример кодирования запросов и текстов.
25
+
26
+ ### Requirements
27
+
28
+ ```bash
29
+ pip install -q transformers==4.51.0 sentence-transformers==5.1.1 flash-attn langchain_community langchain_huggingface langchain_gigachat
30
+ ```
31
+
32
+ ### Transformers
33
+
34
+ ```python
35
+ import torch
36
+ import torch.nn.functional as F
37
+
38
+ from torch import Tensor
39
+ from transformers import AutoTokenizer, AutoModel
40
+
41
+
42
+ def get_detailed_instruct(task_description: str, query: str) -> str:
43
+ return f'Instruct: {task_description}\nQuery: {query}'
44
+
45
+ # Each query must come with a one-sentence instruction that describes the task
46
+ task = 'Given a web search query, retrieve relevant passages that answer the query'
47
+
48
+ queries = [
49
+ get_detailed_instruct(task, 'What is the capital of Russia?'),
50
+ get_detailed_instruct(task, 'Explain gravity')
51
+ ]
52
+ # No need to add instruction for retrieval documents
53
+ documents = [
54
+ "The capital of Russia is Moscow.",
55
+ "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."
56
+ ]
57
+ input_texts = queries + documents
58
+
59
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving.
60
+ tokenizer = AutoTokenizer.from_pretrained(
61
+ 'ai-sage/Giga-Embeddings-instruct',
62
+ trust_remote_code=True
63
+ )
64
+ model = AutoModel.from_pretrained(
65
+ 'ai-sage/Giga-Embeddings-instruct',
66
+ attn_implementation="flash_attention_2",
67
+ torch_dtype=torch.bfloat16,
68
+ trust_remote_code=True
69
+ )
70
+ model.eval()
71
+ model.cuda()
72
+
73
+ max_length = 4096
74
+
75
+ # Tokenize the input texts
76
+ batch_dict = tokenizer(
77
+ input_texts,
78
+ padding=True,
79
+ truncation=True,
80
+ max_length=max_length,
81
+ return_tensors="pt",
82
+ )
83
+ batch_dict.to(model.device)
84
+ embeddings = model(**batch_dict, return_embeddings=True)
85
+
86
+ scores = (embeddings[:2] @ embeddings[2:].T)
87
+ print(scores.tolist())
88
+ # [[0.58203125, 0.0712890625], [0.06884765625, 0.62109375]]
89
+ ```
90
+
91
+ ### Sentence Transformers
92
+
93
+ ```python
94
+ import torch
95
+
96
+ from sentence_transformers import SentenceTransformer
97
+
98
+ # Load the model
99
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving
100
+ model = SentenceTransformer(
101
+ "ai-sage/Giga-Embeddings-instruct",
102
+ model_kwargs={
103
+ "attn_implementation": "flash_attention_2",
104
+ "torch_dtype": torch.bfloat16,
105
+ "trust_remote_code": "True"
106
+ },
107
+ config_kwargs={
108
+ "trust_remote_code": "True"
109
+ }
110
+ )
111
+ model.max_seq_length = 4096
112
+
113
+ # The queries and documents to embed
114
+ queries = [
115
+ 'What is the capital of Russia?',
116
+ 'Explain gravity'
117
+ ]
118
+ # No need to add instruction for retrieval documents
119
+ documents = [
120
+ "The capital of Russia is Moscow.",
121
+ "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."
122
+ ]
123
+
124
+ # Encode the queries and documents. Note that queries benefit from using a prompt
125
+ query_embeddings = model.encode(queries, prompt='Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: ')
126
+ document_embeddings = model.encode(documents)
127
+
128
+ # Compute the (cosine) similarity between the query and document embeddings
129
+ similarity = model.similarity(query_embeddings, document_embeddings)
130
+ print(similarity)
131
+ # tensor([[0.5846, 0.0702],
132
+ # [0.0691, 0.6207]])
133
+ ```
134
+
135
+ ### LangChain
136
+
137
+ ```python
138
+ import torch
139
+
140
+ from langchain_huggingface import HuggingFaceEmbeddings
141
+
142
+ # Load model
143
+ embeddings = HuggingFaceEmbeddings(
144
+ model_name='ai-sage/Giga-Embeddings-instruct',
145
+ encode_kwargs={},
146
+ model_kwargs={
147
+ 'device': 'cuda',
148
+ 'trust_remote_code': True,
149
+ 'model_kwargs': {'torch_dtype': torch.bfloat16},
150
+ 'prompts': {'query': 'Instruct: Given a question, retrieve passages that answer the question\nQuery: '}
151
+ }
152
+ )
153
+
154
+ # Tokenizer
155
+ embeddings._client.tokenizer.tokenize("Hello world! I am GigaChat")
156
+
157
+ # Query embeddings
158
+ query_embeddings = embeddings.embed_query("Hello world!")
159
+ print(f"Your embeddings: {query_embeddings[0:20]}...")
160
+ print(f"Vector size: {len(query_embeddings)}")
161
+
162
+ # Document embeddings
163
+ documents = ["foo bar", "bar foo"]
164
+ documents_embeddings = embeddings.embed_documents(documents)
165
+ print(f"Vector size: {len(documents_embeddings)} x {len(documents_embeddings[0])}")
166
+ ```
167
+
168
+ ## Инструктивность
169
+
170
+ **Использование инструкций для улучшения качества эмбеддингов**
171
+
172
+ Для достижения более точных результатов при работе с эмбеддингами, особенно в задачах поиска и извлечения информации (retrieval), рекомендуется добавлять инструкцию на естественном языке перед текстовым запросом (query). Это помогает модели лучше понять контекст и цель запроса, что положительно сказывается на качестве результатов. Важно отметить, что инструкцию нужно добавлять только перед запросом, а не перед документом.
173
+
174
+ Для **симметричных задач**, таких как классификация (classification) или семантическое сравнение текстов (semantic text similarity), инструкцию необходимо добавлять перед каждым запросом. Это связано с тем, что такие задачи требуют одинакового контекста для всех входных данных, чтобы модель могла корректно сравнивать или классифицировать их.
175
+
176
+ **Примеры инструкций для симметричных задач:**
177
+ - `"Retrieve semantically similar text"`
178
+ - `"Given a text, retrieve semantically similar text"`
179
+ - `"Дано предложение, необходимо найти его парафраз"`
180
+ - `"Классифицируй отзыв на товар как положительный, отрицательный или нейтральный"`
181
+ - `"Классифицируй чувствительную тему по запросу"`
182
+
183
+ Для **retrieval-задач** (например, поиск ответа в тексте) можно использовать инструкцию:
184
+ `'Дан вопрос, необходимо найти абзац текста с ответом'`.
185
+
186
+ Такой подход особенно эффективен для задач поиска и извлечения информации, таких как поиск релевантных документов или извлечение ответов из текста.
187
+
188
+ **Примеры инструкций для retrieval-задач:**
189
+ - `'Дан вопрос, необходимо найти абзац текста с ответом'`
190
+ - `'Given the question, find a paragraph with the answer'`
191
+
192
+ Инструкции необходимо оборачивать в шаблон: `f'Instruct: {task_description}\nQuery: {query}'`. Использование инструкций позволяет значительно улучшить качество поиска и релевантность результатов, что подтверждается тестами на бенчмарках, таких как RuBQ, MIRACL. Для симметричных задач добавление инструкции перед каждым запросом обеспечивает согласованность и повышает точность модели.
193
+
194
+ ## Поддерживаемые языки
195
+
196
+ Эта модель инициализирована pretrain моделью GigaChat и дополнительно обучена на смеси английских и русских данных.
197
+
198
+ ## FAQ
199
+
200
+ 1. Нужно ли добавлять инструкции к запросу?
201
+
202
+ Да, именно так модель обучалась, иначе вы увидите снижение качества. Определение задачи должно быть инструкцией в одном предложении, которая описывает задачу. Это способ настройки текстовых эмбеддингов для разных сценариев с помощью инструкций на естественном языке.
203
+
204
+ С другой стороны, добавлять инструкции на сторону документа не требуется.
205
+
206
+ 2. Почему мои воспроизведённые результаты немного отличаются от указанных в карточке модели?
207
+
208
+ Разные версии библиотек transformers и pytorch могут вызывать незначительные, но ненулевые различия в результатах.
209
+
210
+
211
+ ## Ограничения
212
+
213
+ Использование этой модели для входны�� данных, содержащих более 4096 токенов, невозможно.