Update README.md
Browse files
README.md
CHANGED
|
@@ -55,4 +55,39 @@ print(similarities)
|
|
| 55 |
# [0.6609, 0.7046, 1.0000]])
|
| 56 |
```
|
| 57 |
|
| 58 |
-
Note: In my tests it utilizes more than 24GB (RTX 4090), so an A100 or A6000 would be required for inference.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
# [0.6609, 0.7046, 1.0000]])
|
| 56 |
```
|
| 57 |
|
| 58 |
+
Note: In my tests it utilizes more than 24GB (RTX 4090), so an A100 or A6000 would be required for inference.
|
| 59 |
+
|
| 60 |
+
## Inference (HuggingFace Transformers)
|
| 61 |
+
Without sentence-transformers, you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
from transformers import AutoTokenizer, AutoModel
|
| 65 |
+
import torch
|
| 66 |
+
|
| 67 |
+
#Mean Pooling - Take attention mask into account for correct averaging
|
| 68 |
+
def mean_pooling(model_output, attention_mask):
|
| 69 |
+
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
|
| 70 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 71 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# Sentences we want sentence embeddings for
|
| 75 |
+
sentences = ['This is an example sentence', 'Each sentence is converted']
|
| 76 |
+
|
| 77 |
+
# Load model from HuggingFace Hub
|
| 78 |
+
tokenizer = AutoTokenizer.from_pretrained('ssmits/Qwen2-7B-Instruct-embed-base')
|
| 79 |
+
model = AutoModel.from_pretrained('ssmits/Qwen2-7B-Instruct-embed-base') # device = "cpu" when <= 24 GB VRAM
|
| 80 |
+
|
| 81 |
+
# Tokenize sentences
|
| 82 |
+
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
| 83 |
+
|
| 84 |
+
# Compute token embeddings
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
model_output = model(**encoded_input)
|
| 87 |
+
|
| 88 |
+
# Perform pooling. In this case, mean pooling.
|
| 89 |
+
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
| 90 |
+
|
| 91 |
+
print("Sentence embeddings:")
|
| 92 |
+
print(sentence_embeddings)
|
| 93 |
+
```
|