-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
huggingface.py
318 lines (270 loc) · 11.3 KB
/
huggingface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import asyncio
from typing import TYPE_CHECKING, Any, List, Optional, Sequence
from llama_index.legacy.bridge.pydantic import Field, PrivateAttr
from llama_index.legacy.callbacks import CallbackManager
from llama_index.legacy.core.embeddings.base import (
DEFAULT_EMBED_BATCH_SIZE,
BaseEmbedding,
Embedding,
)
from llama_index.legacy.embeddings.huggingface_utils import (
DEFAULT_HUGGINGFACE_EMBEDDING_MODEL,
format_query,
format_text,
get_pooling_mode,
)
from llama_index.legacy.embeddings.pooling import Pooling
from llama_index.legacy.llms.huggingface import HuggingFaceInferenceAPI
from llama_index.legacy.utils import get_cache_dir, infer_torch_device
if TYPE_CHECKING:
import torch
DEFAULT_HUGGINGFACE_LENGTH = 512
class HuggingFaceEmbedding(BaseEmbedding):
tokenizer_name: str = Field(description="Tokenizer name from HuggingFace.")
max_length: int = Field(
default=DEFAULT_HUGGINGFACE_LENGTH, description="Maximum length of input.", gt=0
)
pooling: Pooling = Field(default=None, description="Pooling strategy.")
normalize: bool = Field(default=True, description="Normalize embeddings or not.")
query_instruction: Optional[str] = Field(
description="Instruction to prepend to query text."
)
text_instruction: Optional[str] = Field(
description="Instruction to prepend to text."
)
cache_folder: Optional[str] = Field(
description="Cache folder for huggingface files."
)
_model: Any = PrivateAttr()
_tokenizer: Any = PrivateAttr()
_device: str = PrivateAttr()
def __init__(
self,
model_name: Optional[str] = None,
tokenizer_name: Optional[str] = None,
pooling: Optional[str] = None,
max_length: Optional[int] = None,
query_instruction: Optional[str] = None,
text_instruction: Optional[str] = None,
normalize: bool = True,
model: Optional[Any] = None,
tokenizer: Optional[Any] = None,
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
cache_folder: Optional[str] = None,
trust_remote_code: bool = False,
device: Optional[str] = None,
callback_manager: Optional[CallbackManager] = None,
):
try:
from transformers import AutoModel, AutoTokenizer
except ImportError:
raise ImportError(
"HuggingFaceEmbedding requires transformers to be installed.\n"
"Please install transformers with `pip install transformers`."
)
self._device = device or infer_torch_device()
cache_folder = cache_folder or get_cache_dir()
if model is None: # Use model_name with AutoModel
model_name = (
model_name
if model_name is not None
else DEFAULT_HUGGINGFACE_EMBEDDING_MODEL
)
model = AutoModel.from_pretrained(
model_name, cache_dir=cache_folder, trust_remote_code=trust_remote_code
)
elif model_name is None: # Extract model_name from model
model_name = model.name_or_path
self._model = model.to(self._device)
if tokenizer is None: # Use tokenizer_name with AutoTokenizer
tokenizer_name = (
model_name or tokenizer_name or DEFAULT_HUGGINGFACE_EMBEDDING_MODEL
)
tokenizer = AutoTokenizer.from_pretrained(
tokenizer_name, cache_dir=cache_folder
)
elif tokenizer_name is None: # Extract tokenizer_name from model
tokenizer_name = tokenizer.name_or_path
self._tokenizer = tokenizer
if max_length is None:
try:
max_length = int(self._model.config.max_position_embeddings)
except AttributeError as exc:
raise ValueError(
"Unable to find max_length from model config. Please specify max_length."
) from exc
if not pooling:
pooling = get_pooling_mode(model_name)
try:
pooling = Pooling(pooling)
except ValueError as exc:
raise NotImplementedError(
f"Pooling {pooling} unsupported, please pick one in"
f" {[p.value for p in Pooling]}."
) from exc
super().__init__(
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
model_name=model_name,
tokenizer_name=tokenizer_name,
max_length=max_length,
pooling=pooling,
normalize=normalize,
query_instruction=query_instruction,
text_instruction=text_instruction,
)
@classmethod
def class_name(cls) -> str:
return "HuggingFaceEmbedding"
def _mean_pooling(
self, token_embeddings: "torch.Tensor", attention_mask: "torch.Tensor"
) -> "torch.Tensor":
"""Mean Pooling - Take attention mask into account for correct averaging."""
input_mask_expanded = (
attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
)
numerator = (token_embeddings * input_mask_expanded).sum(1)
return numerator / input_mask_expanded.sum(1).clamp(min=1e-9)
def _embed(self, sentences: List[str]) -> List[List[float]]:
"""Embed sentences."""
encoded_input = self._tokenizer(
sentences,
padding=True,
max_length=self.max_length,
truncation=True,
return_tensors="pt",
)
# pop token_type_ids
encoded_input.pop("token_type_ids", None)
# move tokenizer inputs to device
encoded_input = {
key: val.to(self._device) for key, val in encoded_input.items()
}
model_output = self._model(**encoded_input)
if self.pooling == Pooling.CLS:
context_layer: "torch.Tensor" = model_output[0]
embeddings = self.pooling.cls_pooling(context_layer)
else:
embeddings = self._mean_pooling(
token_embeddings=model_output[0],
attention_mask=encoded_input["attention_mask"],
)
if self.normalize:
import torch
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
return embeddings.tolist()
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
query = format_query(query, self.model_name, self.query_instruction)
return self._embed([query])[0]
async def _aget_query_embedding(self, query: str) -> List[float]:
"""Get query embedding async."""
return self._get_query_embedding(query)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Get text embedding async."""
return self._get_text_embedding(text)
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
text = format_text(text, self.model_name, self.text_instruction)
return self._embed([text])[0]
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
texts = [
format_text(text, self.model_name, self.text_instruction) for text in texts
]
return self._embed(texts)
class HuggingFaceInferenceAPIEmbedding(HuggingFaceInferenceAPI, BaseEmbedding): # type: ignore[misc]
"""
Wrapper on the Hugging Face's Inference API for embeddings.
Overview of the design:
- Uses the feature extraction task: https://huggingface.co/tasks/feature-extraction
"""
pooling: Optional[Pooling] = Field(
default=Pooling.CLS,
description=(
"Optional pooling technique to use with embeddings capability, if"
" the model's raw output needs pooling."
),
)
query_instruction: Optional[str] = Field(
default=None,
description=(
"Instruction to prepend during query embedding."
" Use of None means infer the instruction based on the model."
" Use of empty string will defeat instruction prepending entirely."
),
)
text_instruction: Optional[str] = Field(
default=None,
description=(
"Instruction to prepend during text embedding."
" Use of None means infer the instruction based on the model."
" Use of empty string will defeat instruction prepending entirely."
),
)
@classmethod
def class_name(cls) -> str:
return "HuggingFaceInferenceAPIEmbedding"
async def _async_embed_single(self, text: str) -> Embedding:
embedding = await self._async_client.feature_extraction(text)
if len(embedding.shape) == 1:
return embedding.tolist()
embedding = embedding.squeeze(axis=0)
if len(embedding.shape) == 1: # Some models pool internally
return embedding.tolist()
try:
return self.pooling(embedding).tolist() # type: ignore[misc]
except TypeError as exc:
raise ValueError(
f"Pooling is required for {self.model_name} because it returned"
" a > 1-D value, please specify pooling as not None."
) from exc
async def _async_embed_bulk(self, texts: Sequence[str]) -> List[Embedding]:
"""
Embed a sequence of text, in parallel and asynchronously.
NOTE: this uses an externally created asyncio event loop.
"""
tasks = [self._async_embed_single(text) for text in texts]
return await asyncio.gather(*tasks)
def _get_query_embedding(self, query: str) -> Embedding:
"""
Embed the input query synchronously.
NOTE: a new asyncio event loop is created internally for this.
"""
return asyncio.run(self._aget_query_embedding(query))
def _get_text_embedding(self, text: str) -> Embedding:
"""
Embed the text query synchronously.
NOTE: a new asyncio event loop is created internally for this.
"""
return asyncio.run(self._aget_text_embedding(text))
def _get_text_embeddings(self, texts: List[str]) -> List[Embedding]:
"""
Embed the input sequence of text synchronously and in parallel.
NOTE: a new asyncio event loop is created internally for this.
"""
loop = asyncio.new_event_loop()
try:
tasks = [
loop.create_task(self._aget_text_embedding(text)) for text in texts
]
loop.run_until_complete(asyncio.wait(tasks))
finally:
loop.close()
return [task.result() for task in tasks]
async def _aget_query_embedding(self, query: str) -> Embedding:
return await self._async_embed_single(
text=format_query(query, self.model_name, self.query_instruction)
)
async def _aget_text_embedding(self, text: str) -> Embedding:
return await self._async_embed_single(
text=format_text(text, self.model_name, self.text_instruction)
)
async def _aget_text_embeddings(self, texts: List[str]) -> List[Embedding]:
return await self._async_embed_bulk(
texts=[
format_text(text, self.model_name, self.text_instruction)
for text in texts
]
)
HuggingFaceInferenceAPIEmbeddings = HuggingFaceInferenceAPIEmbedding