First commit
Browse files- .gitattributes +1 -0
- README.md +145 -0
- model/conan_api_client.py +66 -0
- model/config.json +40 -0
- model/modeling_conan.py +435 -0
- src/mteb_res_v2.png +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
src/mteb_res_v2.png filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,3 +1,148 @@
|
|
1 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
license: apache-2.0
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
tags:
|
3 |
+
- mteb
|
4 |
+
- sentence-transformers
|
5 |
+
- transformers
|
6 |
+
- sentence-similarity
|
7 |
+
language:
|
8 |
+
- en
|
9 |
+
- zh
|
10 |
license: apache-2.0
|
11 |
---
|
12 |
+
|
13 |
+
# Conan-Embedding-v2
|
14 |
+
|
15 |
+
## What's New?
|
16 |
+
|
17 |
+
- **Performance**
|
18 |
+
|
19 |
+
Conan-Embedding-v2 has now achieved SOTA performance on the MTEB leaderboard for both Chinese and English.
|
20 |
+
|
21 |
+
- **Cross-lingual Retrieval between Chinese and English**
|
22 |
+
|
23 |
+
Conan-Embedding-v2 supports cross-lingual retrieval between Chinese and English samples.
|
24 |
+
|
25 |
+
- **Longer Context Support**
|
26 |
+
|
27 |
+
Conan-Embedding-v2 now supports a context length of 32,768 tokens.
|
28 |
+
|
29 |
+
- **Conan 1.4B Large Model Trained from Scratch**
|
30 |
+
|
31 |
+
A vocabulary and large language model trained from scratch, with a pre-trained model and vocabulary more tailored to the Embedding scenario, delivering stronger performance.
|
32 |
+
|
33 |
+
The Conan-1.4B base model will be open-sourced. Community workers can train their own Embedding models based on the Conan-1.4B base model.
|
34 |
+
|
35 |
+
|
36 |
+
## Performance
|
37 |
+
|
38 |
+
Performance of Conan-Embedding-v2 on MTEB for Chinese and English
|
39 |
+
|
40 |
+

|
41 |
+
|
42 |
+
**English**
|
43 |
+
|
44 |
+
| Embedding TaskMertric | Class. Acc. (12) | Clust V-Meas. (11) | PairClass AP (3) | Rerank MAP (4) | Retri nDCG @ 10 (15) | STS Spear. (12) | SummSpear. (1) | Avg.(56) |
|
45 |
+
|:-----------------------:|:----------------:|:------------------:|:----------------:|:--------------:|:--------------------:|:---------------:|:--------------:|:---------:|
|
46 |
+
| bge-multilingual-gemma2 | 88.08 | 54.65 | 85.97 | 59.72 | 59.24 | 83.88 | 31.20 | 69.88 |
|
47 |
+
| e5-mistral-7b-instruct | 79.89 | 51.44 | 88.42 | 49.78 | 57.62 | 84.32 | **36.57** | 67.98 |
|
48 |
+
| gte-Qwen2-7B-instruct | 86.58 | 56.92 | 85.90 | **61.42** | 59.11 | 83.06 | 31.35 | 69.95 |
|
49 |
+
| stella-en-1.5B-v5 | 87.63 | 57.69 | 88.07 | 61.21 | 61.01 | 84.51 | 31.49 | 71.19 |
|
50 |
+
| bge-en-icl | 88.95 | 57.89 | 88.14 | 59.86 | 62.16 | 84.24 | 30.77 | 71.67 |
|
51 |
+
| NV-Embed-v2 | **90.37** | 58.46 | 88.67 | 60.65 | 62.65 | 84.31 | 30.70 | 72.31 |
|
52 |
+
| **Conan-embedding-v2** | 90.15 | **60.86** | **93.47** | 60.89 | **66.40** | **85.73** | 28.08 | **74.22** |
|
53 |
+
|
54 |
+
**Chinese**
|
55 |
+
|
56 |
+
| Embedding TaskMertric | Class.Acc. (9) | ClustV-Meas. (4) | PairClassAP (2) | RerankMAP (4) | RetrinDCG @ 10 (8) | STSSpear. (8) | Avg.(35) |
|
57 |
+
|:-----------------------:|:--------------:|:----------------:|:---------------:|:-------------:|:------------------:|:-------------:|:---------:|
|
58 |
+
| e5-mistral-7b-instruct | 72.96 | 52.30 | 72.19 | 61.86 | 61.75 | 48.34 | 59.92 |
|
59 |
+
| gte-Qwen2-1.5B-instruct | 72.53 | 54.61 | 86.91 | 68.21 | 71.86 | 60.05 | 67.12 |
|
60 |
+
| bge-multilingual-gemma2 | 75.31 | 59.30 | 86.67 | 68.28 | 73.73 | 55.19 | 67.64 |
|
61 |
+
| gte-Qwen2-7B-instruct | 75.77 | 66.06 | 87.48 | 68.92 | 75.71 | 65.20 | 71.62 |
|
62 |
+
| xiaobu-embedding-v2 | 76.53 | 65.17 | 91.87 | 72.58 | 76.50 | 64.18 | 72.36 |
|
63 |
+
| Conan-embedding-v1 | **76.77** | 66.33 | 91.66 | 72.76 | 76.67 | 63.67 | 72.50 |
|
64 |
+
| **Conan-embedding-v2** | 76.47 | **68.84** | **92.44** | **74.41** | **78.31** | **65.48** | **74.24** |
|
65 |
+
|
66 |
+
|
67 |
+
## Model Detail
|
68 |
+
|
69 |
+
### Model Structure
|
70 |
+
|
71 |
+
**Conan-Embedding-v2 Structure:**
|
72 |
+
|
73 |
+
```
|
74 |
+
SentenceTransformer(
|
75 |
+
(0): Transformer({
|
76 |
+
'max_seq_length': 32768,
|
77 |
+
'do_lower_case': False
|
78 |
+
}) with Transformer model: ConanEmbedModel,
|
79 |
+
(1): Pooling({
|
80 |
+
'word_embedding_dimension': 3584,
|
81 |
+
'pooling_mode_cls_token': False,
|
82 |
+
'pooling_mode_mean_tokens': True,
|
83 |
+
'pooling_mode_max_tokens': False,
|
84 |
+
'pooling_mode_mean_sqrt_len_tokens': False,
|
85 |
+
'pooling_mode_weightedmean_tokens': False,
|
86 |
+
'pooling_mode_lasttoken': False,
|
87 |
+
'include_prompt': True
|
88 |
+
}),
|
89 |
+
(2): Dense({
|
90 |
+
'in_features': 3584,
|
91 |
+
'out_features': 3584,
|
92 |
+
'bias': True,
|
93 |
+
'activation_function': 'torch.nn.modules.linear.Identity'
|
94 |
+
})
|
95 |
+
)
|
96 |
+
```
|
97 |
+
|
98 |
+
**Key Specifications of Conan-1.4B (Transformer):**
|
99 |
+
|
100 |
+
- Number of Parameters (Non-Dense-Layer): 1.48B
|
101 |
+
|
102 |
+
- Vocabulary Size: 150,000
|
103 |
+
|
104 |
+
- Number of Layers: 8
|
105 |
+
|
106 |
+
- Hidden Layer Dimension: 3584
|
107 |
+
|
108 |
+
- Number of Attention Heads (GOA): 32 for Q and 8 for KV
|
109 |
+
|
110 |
+
- Intermediate Dimension of FFN Layer: 8192
|
111 |
+
|
112 |
+
- Maximum Context Window: 32,768 Tokens
|
113 |
+
|
114 |
+
For more model details, please refer to ```model/modeling_conan.py``` and ```config.json```, or stay tuned for the upcoming open-source release of Conan-1.4B Base Model.
|
115 |
+
|
116 |
+
### Tokenizer
|
117 |
+
|
118 |
+
We trained the Tokenizer on a large-scale multilingual dataset to build a standard BBPE(Byte-level Byte Pair Encoding) tokenizer with a vocabulary size of 150,000.
|
119 |
+
|
120 |
+
## Technical Report
|
121 |
+
|
122 |
+
We will soon release our technical report.
|
123 |
+
|
124 |
+
## Using Conan-Embedding-v2
|
125 |
+
|
126 |
+
Use ```/model/conan_api_client.py``` to access our test API. A sample call is as follows:
|
127 |
+
|
128 |
+
```
|
129 |
+
from modeling_conan import ConanClient
|
130 |
+
|
131 |
+
AK = os.getenv("CONAN_AK")
|
132 |
+
SK = os.getenv("CONAN_SK")
|
133 |
+
client = ConanClient(ak=AK, sk=SK, url="https://ai.om.qq.com/api/conan/v2")
|
134 |
+
res = client.embed("Hello!")
|
135 |
+
print(res)
|
136 |
+
|
137 |
+
```
|
138 |
+
|
139 |
+
This is a temporary calling solution. Please contact us to obtain an access token.
|
140 |
+
|
141 |
+
In the future, we will provide high-performance, cost-effective, and reliable Embedding services on Tencent Cloud.
|
142 |
+
|
143 |
+
|
144 |
+
---
|
145 |
+
|
146 |
+
**About**
|
147 |
+
|
148 |
+
Created by the Tencent BAC Group. All rights reserved.
|
model/conan_api_client.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import hashlib
|
3 |
+
import random
|
4 |
+
import string
|
5 |
+
import time
|
6 |
+
import requests
|
7 |
+
import json
|
8 |
+
|
9 |
+
class ConanClient:
|
10 |
+
def __init__(self, ak, sk, url, timeout=30):
|
11 |
+
"""
|
12 |
+
Initialize the Client
|
13 |
+
|
14 |
+
Args:
|
15 |
+
ak: Access Key
|
16 |
+
sk: Secret Key
|
17 |
+
url: Server URL
|
18 |
+
timeout: Request timeout in seconds (default: 30)
|
19 |
+
"""
|
20 |
+
self.ak = ak
|
21 |
+
self.sk = sk
|
22 |
+
self.url = url
|
23 |
+
self.timeout = timeout
|
24 |
+
|
25 |
+
def __random_password(self, size=40, chars=None):
|
26 |
+
if chars is None:
|
27 |
+
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
|
28 |
+
random_chars = random.SystemRandom().choice
|
29 |
+
return "".join(random_chars(chars) for _ in range(size))
|
30 |
+
|
31 |
+
def __signature(self, random_str, time_stamp):
|
32 |
+
params_str = "%s:%d:%s:%s" % (self.ak, time_stamp, random_str, self.sk)
|
33 |
+
encoded_params_str = params_str.encode("utf-8")
|
34 |
+
return hashlib.md5(encoded_params_str).hexdigest()
|
35 |
+
|
36 |
+
def get_signature(self):
|
37 |
+
timestamp = int(time.time())
|
38 |
+
random_str = self.__random_password(20)
|
39 |
+
sig = self.__signature(random_str, timestamp)
|
40 |
+
params = {
|
41 |
+
"timestamp": timestamp,
|
42 |
+
"random": random_str,
|
43 |
+
"app_id": self.ak,
|
44 |
+
"sign": sig,
|
45 |
+
}
|
46 |
+
return params
|
47 |
+
|
48 |
+
def embed(self, text):
|
49 |
+
"""
|
50 |
+
Embed text using the server
|
51 |
+
|
52 |
+
Args:
|
53 |
+
text: The input text to embed
|
54 |
+
|
55 |
+
Returns:
|
56 |
+
requests.Response object
|
57 |
+
"""
|
58 |
+
params = self.get_signature()
|
59 |
+
params["body"] = text
|
60 |
+
params["content_id"] = f"test_{int(time.time())}"
|
61 |
+
|
62 |
+
headers = {"Content-Type": "application/json"}
|
63 |
+
|
64 |
+
rsp = requests.post(self.url, data=json.dumps(params), timeout=self.timeout, headers=headers)
|
65 |
+
result = json.loads(rsp.text)
|
66 |
+
return result
|
model/config.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "Conan-embedding-v2",
|
3 |
+
"add_eos": true,
|
4 |
+
"add_pad_token": true,
|
5 |
+
"architectures": [
|
6 |
+
"ConanEmbedModel"
|
7 |
+
],
|
8 |
+
"attention_bias": false,
|
9 |
+
"attention_dropout": 0.0,
|
10 |
+
"auto_map": {
|
11 |
+
"AutoConfig": "configuration_conan.ConanEmbedConfig",
|
12 |
+
"AutoModel": "modeling_conan.ConanEmbedModel"
|
13 |
+
},
|
14 |
+
"bos_token_id": 0,
|
15 |
+
"do_dir": true,
|
16 |
+
"eos_token_id": 1,
|
17 |
+
"hidden_act": "silu",
|
18 |
+
"hidden_size": 3584,
|
19 |
+
"initializer_range": 0.02,
|
20 |
+
"intermediate_size": 8192,
|
21 |
+
"is_mask_instruction": true,
|
22 |
+
"mask_type": "b",
|
23 |
+
"max_position_embeddings": 32768,
|
24 |
+
"mlp_bias": false,
|
25 |
+
"model_type": "Conan-embedding-v2",
|
26 |
+
"num_attention_heads": 32,
|
27 |
+
"num_hidden_layers": 8,
|
28 |
+
"num_key_value_heads": 8,
|
29 |
+
"pad_token_id": 2,
|
30 |
+
"padding_side": "right",
|
31 |
+
"pretraining_tp": 1,
|
32 |
+
"rms_norm_eps": 1e-05,
|
33 |
+
"rope_scaling": null,
|
34 |
+
"rope_theta": 1000000.0,
|
35 |
+
"sentence_pooling_method": "mean",
|
36 |
+
"torch_dtype": "bfloat16",
|
37 |
+
"transformers_version": "4.41.2",
|
38 |
+
"use_cache": true,
|
39 |
+
"vocab_size": 150000
|
40 |
+
}
|
model/modeling_conan.py
ADDED
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union, Mapping, Optional, Tuple, TypedDict, Dict, List
|
2 |
+
from functools import partial
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
from transformers import AutoModel, PreTrainedTokenizerFast, BatchEncoding, DataCollatorWithPadding
|
7 |
+
from transformers.models.auto import AutoTokenizer
|
8 |
+
from transformers.models.llama.modeling_llama import LLAMA_INPUTS_DOCSTRING
|
9 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
10 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
|
11 |
+
from transformers import LlamaModel
|
12 |
+
from transformers.cache_utils import Cache, DynamicCache
|
13 |
+
from transformers.utils import (
|
14 |
+
add_start_docstrings_to_model_forward,
|
15 |
+
logging,
|
16 |
+
)
|
17 |
+
from tqdm.auto import tqdm
|
18 |
+
from datasets import Dataset
|
19 |
+
from torch.utils.data import DataLoader
|
20 |
+
from .configuration_conan import ConanEmbedConfig
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
|
25 |
+
class ConanEmbedFeatures(TypedDict):
|
26 |
+
input_dict: torch.Tensor
|
27 |
+
attention_mask: torch.Tensor
|
28 |
+
pool_mask: torch.Tensor
|
29 |
+
|
30 |
+
|
31 |
+
def _move_to_device(maybe_tensor, device: torch.device):
|
32 |
+
if torch.is_tensor(maybe_tensor):
|
33 |
+
return maybe_tensor.to(device, non_blocking=device.type == "cuda")
|
34 |
+
elif isinstance(maybe_tensor, dict):
|
35 |
+
return {key: _move_to_device(value, device) for key, value in maybe_tensor.items()}
|
36 |
+
elif isinstance(maybe_tensor, list):
|
37 |
+
return [_move_to_device(x, device) for x in maybe_tensor]
|
38 |
+
elif isinstance(maybe_tensor, tuple):
|
39 |
+
return tuple([_move_to_device(x, device) for x in maybe_tensor])
|
40 |
+
elif isinstance(maybe_tensor, Mapping):
|
41 |
+
return type(maybe_tensor)({k: _move_to_device(v, device) for k, v in maybe_tensor.items()})
|
42 |
+
else:
|
43 |
+
return maybe_tensor
|
44 |
+
|
45 |
+
|
46 |
+
def move_to_device(sample, device: torch.device):
|
47 |
+
if device.type == "cpu":
|
48 |
+
return sample
|
49 |
+
|
50 |
+
if len(sample) == 0:
|
51 |
+
return {}
|
52 |
+
return _move_to_device(sample, device)
|
53 |
+
|
54 |
+
|
55 |
+
def input_transform_func(
|
56 |
+
tokenizer: PreTrainedTokenizerFast,
|
57 |
+
examples: Dict[str, List],
|
58 |
+
always_add_eos: bool,
|
59 |
+
max_length: int,
|
60 |
+
instruction: str,
|
61 |
+
) -> BatchEncoding:
|
62 |
+
if always_add_eos:
|
63 |
+
examples["input_texts"] = [
|
64 |
+
instruction + input_example + tokenizer.eos_token for input_example in examples["input_texts"]
|
65 |
+
]
|
66 |
+
print(examples["input_texts"])
|
67 |
+
batch_dict = tokenizer(
|
68 |
+
examples["input_texts"],
|
69 |
+
max_length=max_length,
|
70 |
+
padding=True,
|
71 |
+
return_token_type_ids=False,
|
72 |
+
return_tensors="pt",
|
73 |
+
truncation=True,
|
74 |
+
)
|
75 |
+
print(examples["input_texts"])
|
76 |
+
return batch_dict
|
77 |
+
|
78 |
+
|
79 |
+
class ConanEmbedModel(LlamaModel):
|
80 |
+
config_class = ConanEmbedConfig
|
81 |
+
|
82 |
+
def __init__(self, config: ConanEmbedConfig) -> None:
|
83 |
+
"""
|
84 |
+
Initialize the model with a given configuration.
|
85 |
+
|
86 |
+
Args:
|
87 |
+
config (ConanEmbedConfig): The configuration for the model.
|
88 |
+
"""
|
89 |
+
super().__init__(config)
|
90 |
+
for layer in self.layers:
|
91 |
+
layer.self_attn.is_causal = not config.do_dir
|
92 |
+
self._attn_implementation = "eager"
|
93 |
+
self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path)
|
94 |
+
self.padding_side = config.padding_side
|
95 |
+
self.is_mask_instruction = config.is_mask_instruction
|
96 |
+
self.add_eos = config.add_eos
|
97 |
+
self.mask_type = config.mask_type
|
98 |
+
self.sentence_pooling_method = config.sentence_pooling_method
|
99 |
+
if config.add_pad_token and self.tokenizer is not None:
|
100 |
+
self.add_pad_token()
|
101 |
+
|
102 |
+
def add_pad_token(self):
|
103 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
104 |
+
self.tokenizer.padding_side = self.padding_side
|
105 |
+
|
106 |
+
def _sentence_embedding(self, last_hidden_state, attention_mask=None):
|
107 |
+
"""Use the pooling method to get the sentence embedding.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
last_hidden_state (torch.Tensor): The model output's last hidden state.
|
111 |
+
attention_mask (torch.Tensor): Mask out padding tokens during pooling.
|
112 |
+
|
113 |
+
Raises:
|
114 |
+
NotImplementedError: Specified pooling method not implemented.
|
115 |
+
|
116 |
+
Returns:
|
117 |
+
torch.Tensor: The sentence embeddings.
|
118 |
+
"""
|
119 |
+
if self.sentence_pooling_method == "cls":
|
120 |
+
return last_hidden_state[:, 0]
|
121 |
+
elif self.sentence_pooling_method == "mean":
|
122 |
+
s = torch.sum(last_hidden_state, dim=1)
|
123 |
+
# d = attention_mask.sum(dim=1, keepdim=True).float()
|
124 |
+
return s
|
125 |
+
elif self.sentence_pooling_method == "last_token":
|
126 |
+
left_padding = attention_mask[:, -1].sum() == attention_mask.shape[0]
|
127 |
+
if left_padding:
|
128 |
+
return last_hidden_state[:, -1]
|
129 |
+
else:
|
130 |
+
sequence_lengths = attention_mask.sum(dim=1) - 1
|
131 |
+
batch_size = last_hidden_state.shape[0]
|
132 |
+
return last_hidden_state[
|
133 |
+
torch.arange(batch_size, device=last_hidden_state.device),
|
134 |
+
sequence_lengths,
|
135 |
+
]
|
136 |
+
else:
|
137 |
+
raise NotImplementedError(f"pooling method {self.sentence_pooling_method} not implemented")
|
138 |
+
|
139 |
+
def prepare_kwargs_from_batch(
|
140 |
+
self,
|
141 |
+
batch_dict: Dict[str, torch.Tensor],
|
142 |
+
instruction_lens: int,
|
143 |
+
device: torch.device,
|
144 |
+
) -> ConanEmbedFeatures:
|
145 |
+
"""
|
146 |
+
Prepare the batch dictionary for encoding.
|
147 |
+
|
148 |
+
Args:
|
149 |
+
batch_dict: A dictionary containing the input_ids and attention_mask.
|
150 |
+
instruction_lens: The length of the instruction.
|
151 |
+
device: The device to move the data to.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
A ConanEmbedFeatures object with the prepared input_ids and attention_mask.
|
155 |
+
"""
|
156 |
+
batch_dict = move_to_device(batch_dict, device)
|
157 |
+
attention_mask = batch_dict["attention_mask"].clone() if "attention_mask" in batch_dict else None
|
158 |
+
if (
|
159 |
+
attention_mask is not None
|
160 |
+
and self.padding_side == "right"
|
161 |
+
and self.is_mask_instruction
|
162 |
+
and instruction_lens > 0
|
163 |
+
):
|
164 |
+
# Mask out the instruction tokens for mean-pooling
|
165 |
+
attention_mask[:, :instruction_lens] = 0
|
166 |
+
features: ConanEmbedFeatures = {
|
167 |
+
"input_ids": torch.tensor(batch_dict.get("input_ids").to(batch_dict.get("input_ids")).long()),
|
168 |
+
"attention_mask": batch_dict["attention_mask"],
|
169 |
+
}
|
170 |
+
return features
|
171 |
+
|
172 |
+
@torch.no_grad()
|
173 |
+
def _do_encode(
|
174 |
+
self,
|
175 |
+
prompts: List[str],
|
176 |
+
batch_size: int = 1,
|
177 |
+
instruction: str = "",
|
178 |
+
max_length: int = 4096,
|
179 |
+
num_workers: int = 32,
|
180 |
+
return_numpy: bool = False,
|
181 |
+
) -> Union[torch.FloatTensor, np.ndarray]:
|
182 |
+
"""
|
183 |
+
Encode a list of prompts using the model.
|
184 |
+
|
185 |
+
Args:
|
186 |
+
prompts: A list of prompts to encode.
|
187 |
+
batch_size: The batch size to use for encoding. Defaults to 1.
|
188 |
+
instruction: An instruction to prepend to the prompts. Defaults to "".
|
189 |
+
max_length: The maximum length of the input_ids. Defaults to 4096.
|
190 |
+
num_workers: The number of workers to use for encoding. Defaults to 32.
|
191 |
+
return_numpy: Whether to return the output as a numpy array or a torch tensor. Defaults to False.
|
192 |
+
|
193 |
+
Returns:
|
194 |
+
A tensor or numpy array of shape (len(prompts), hidden_size) containing the encoded prompts.
|
195 |
+
"""
|
196 |
+
dataset: Dataset = Dataset.from_dict({"input_texts": prompts})
|
197 |
+
dataset.set_transform(
|
198 |
+
partial(
|
199 |
+
input_transform_func,
|
200 |
+
self.tokenizer,
|
201 |
+
always_add_eos=True,
|
202 |
+
max_length=max_length,
|
203 |
+
instruction=instruction,
|
204 |
+
)
|
205 |
+
)
|
206 |
+
|
207 |
+
data_collator = DataCollatorWithPadding(self.tokenizer)
|
208 |
+
data_loader = DataLoader(
|
209 |
+
dataset,
|
210 |
+
batch_size=batch_size,
|
211 |
+
shuffle=False,
|
212 |
+
drop_last=False,
|
213 |
+
num_workers=num_workers,
|
214 |
+
collate_fn=data_collator,
|
215 |
+
pin_memory=True,
|
216 |
+
)
|
217 |
+
|
218 |
+
if self.padding_side == "right" and self.is_mask_instruction and len(instruction) > 0:
|
219 |
+
instruction_lens = len(self.tokenizer.tokenize(instruction))
|
220 |
+
else:
|
221 |
+
instruction_lens = 0
|
222 |
+
|
223 |
+
encoded_embeds: List[torch.Tensor] = []
|
224 |
+
device = next(self.parameters()).device
|
225 |
+
for batch_dict in tqdm(data_loader, desc="encoding", mininterval=10):
|
226 |
+
features = self.prepare_kwargs_from_batch(batch_dict, instruction_lens, device=device)
|
227 |
+
embeds = self(**features)["sentence_embeddings"].squeeze(1)
|
228 |
+
encoded_embeds.append(embeds)
|
229 |
+
encoded_embeds = torch.cat(encoded_embeds, axis=0)
|
230 |
+
if return_numpy:
|
231 |
+
encoded_embeds = encoded_embeds.cpu().detach().numpy()
|
232 |
+
return encoded_embeds
|
233 |
+
|
234 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
235 |
+
def forward(
|
236 |
+
self,
|
237 |
+
input_ids: torch.LongTensor,
|
238 |
+
attention_mask: Optional[torch.Tensor] = None,
|
239 |
+
position_ids: Optional[torch.LongTensor] = None,
|
240 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
241 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
242 |
+
use_cache: Optional[bool] = None,
|
243 |
+
output_attentions: Optional[bool] = None,
|
244 |
+
output_hidden_states: Optional[bool] = None,
|
245 |
+
return_dict: Optional[bool] = None,
|
246 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
247 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
|
248 |
+
"""
|
249 |
+
Args:
|
250 |
+
input_ids: a tensor of shape (batch_size, sequence_length)
|
251 |
+
attention_mask: a tensor of shape (batch_size, sequence_length)
|
252 |
+
position_ids: a tensor of shape (batch_size, sequence_length)
|
253 |
+
past_key_values: a list of tensors of shape (batch_size, key_length, hidden_size)
|
254 |
+
inputs_embeds: a tensor of shape (batch_size, sequence_length, hidden_size)
|
255 |
+
use_cache: a boolean indicating whether to use the cache
|
256 |
+
output_attentions: a boolean indicating whether to output the attention weights
|
257 |
+
output_hidden_states: a boolean indicating whether to output the hidden states
|
258 |
+
return_dict: a boolean indicating whether to return a dictionary
|
259 |
+
|
260 |
+
Returns:
|
261 |
+
a tuple of length 4 containing the last hidden state, the cache, the hidden states,
|
262 |
+
and the attention weights
|
263 |
+
or a BaseModelOutputWithPast object
|
264 |
+
"""
|
265 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
266 |
+
output_hidden_states = (
|
267 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
268 |
+
)
|
269 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
270 |
+
|
271 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
272 |
+
|
273 |
+
# retrieve input_ids and inputs_embeds
|
274 |
+
if input_ids is not None and inputs_embeds is not None:
|
275 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
276 |
+
elif input_ids is not None:
|
277 |
+
batch_size, seq_length = input_ids.shape
|
278 |
+
elif inputs_embeds is not None:
|
279 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
280 |
+
else:
|
281 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
282 |
+
|
283 |
+
if self.gradient_checkpointing and self.training:
|
284 |
+
if use_cache:
|
285 |
+
logger.warning_once(
|
286 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
287 |
+
)
|
288 |
+
use_cache = False
|
289 |
+
|
290 |
+
past_key_values_length = 0
|
291 |
+
|
292 |
+
if use_cache:
|
293 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
294 |
+
if use_legacy_cache:
|
295 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
296 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
297 |
+
|
298 |
+
if position_ids is None:
|
299 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
300 |
+
position_ids = torch.arange(
|
301 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
302 |
+
)
|
303 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
304 |
+
else:
|
305 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
306 |
+
|
307 |
+
if inputs_embeds is None:
|
308 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
309 |
+
|
310 |
+
if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
|
311 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
312 |
+
if is_padding_right:
|
313 |
+
raise ValueError(
|
314 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
315 |
+
" this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
|
316 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
317 |
+
)
|
318 |
+
|
319 |
+
if self._attn_implementation == "flash_attention_2":
|
320 |
+
# 2d mask is passed through the layers
|
321 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
322 |
+
elif self._attn_implementation == "sdpa" and not output_attentions:
|
323 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
324 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
325 |
+
attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
|
326 |
+
else:
|
327 |
+
# 4d mask is passed through the layers
|
328 |
+
attention_mask = _prepare_4d_attention_mask(
|
329 |
+
attention_mask,
|
330 |
+
inputs_embeds.dtype,
|
331 |
+
)
|
332 |
+
|
333 |
+
hidden_states = inputs_embeds
|
334 |
+
|
335 |
+
# decoder layers
|
336 |
+
all_hidden_states = () if output_hidden_states else None
|
337 |
+
all_self_attns = () if output_attentions else None
|
338 |
+
next_decoder_cache = None
|
339 |
+
|
340 |
+
for decoder_layer in self.layers:
|
341 |
+
if output_hidden_states:
|
342 |
+
all_hidden_states += (hidden_states,)
|
343 |
+
|
344 |
+
if self.gradient_checkpointing and self.training:
|
345 |
+
layer_outputs = self._gradient_checkpointing_func(
|
346 |
+
decoder_layer.__call__,
|
347 |
+
hidden_states,
|
348 |
+
attention_mask,
|
349 |
+
position_ids,
|
350 |
+
past_key_values,
|
351 |
+
output_attentions,
|
352 |
+
use_cache,
|
353 |
+
)
|
354 |
+
else:
|
355 |
+
layer_outputs = decoder_layer(
|
356 |
+
hidden_states,
|
357 |
+
attention_mask=attention_mask,
|
358 |
+
position_ids=position_ids,
|
359 |
+
past_key_value=past_key_values,
|
360 |
+
output_attentions=output_attentions,
|
361 |
+
use_cache=use_cache,
|
362 |
+
)
|
363 |
+
|
364 |
+
hidden_states = layer_outputs[0]
|
365 |
+
|
366 |
+
if use_cache:
|
367 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
368 |
+
|
369 |
+
if output_attentions:
|
370 |
+
all_self_attns += (layer_outputs[1],)
|
371 |
+
|
372 |
+
hidden_states = self.norm(hidden_states)
|
373 |
+
|
374 |
+
# add hidden states from the last decoder layer
|
375 |
+
if output_hidden_states:
|
376 |
+
all_hidden_states += (hidden_states,)
|
377 |
+
|
378 |
+
next_cache = None
|
379 |
+
if use_cache:
|
380 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
381 |
+
|
382 |
+
if not return_dict:
|
383 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
384 |
+
|
385 |
+
return BaseModelOutputWithPast(
|
386 |
+
last_hidden_state=hidden_states,
|
387 |
+
past_key_values=next_cache,
|
388 |
+
hidden_states=all_hidden_states,
|
389 |
+
attentions=all_self_attns,
|
390 |
+
)
|
391 |
+
|
392 |
+
@torch.no_grad()
|
393 |
+
def encode(
|
394 |
+
self,
|
395 |
+
prompts: List[str],
|
396 |
+
instruction: str = "",
|
397 |
+
max_length: int = 4096,
|
398 |
+
) -> Dict[str, torch.Tensor]:
|
399 |
+
"""
|
400 |
+
Encode a list of prompts and an instruction using the model.
|
401 |
+
|
402 |
+
Args:
|
403 |
+
prompts: A list of prompts to encode.
|
404 |
+
instruction: An instruction to prepend to the prompts. Defaults to "".
|
405 |
+
max_length: The maximum length of the input_ids. Defaults to 4096.
|
406 |
+
|
407 |
+
Returns:
|
408 |
+
A dictionary containing the sentence embeddings with key "sentence_embeddings".
|
409 |
+
"""
|
410 |
+
if self.padding_side == "right" and self.is_mask_instruction and len(instruction) > 0:
|
411 |
+
instruction_lens = len(self.tokenizer.tokenize(instruction))
|
412 |
+
else:
|
413 |
+
instruction_lens = 0
|
414 |
+
|
415 |
+
device = next(self.parameters()).device
|
416 |
+
batch_dict = input_transform_func(
|
417 |
+
self.tokenizer,
|
418 |
+
{"input_texts": [prompt for prompt in prompts]},
|
419 |
+
always_add_eos=False,
|
420 |
+
max_length=max_length,
|
421 |
+
instruction=instruction,
|
422 |
+
)
|
423 |
+
|
424 |
+
features: ConanEmbedFeatures = self.prepare_kwargs_from_batch(batch_dict, instruction_lens, device=device)
|
425 |
+
outputs = self(**features)
|
426 |
+
|
427 |
+
embeds = self._sentence_embedding(outputs.last_hidden_state)
|
428 |
+
return {"sentence_embeddings": embeds}
|
429 |
+
|
430 |
+
|
431 |
+
# AutoModel Register
|
432 |
+
AutoModel.register(ConanEmbedConfig, ConanEmbedModel)
|
433 |
+
|
434 |
+
# Register for auto class
|
435 |
+
ConanEmbedModel.register_for_auto_class("AutoModel")
|
src/mteb_res_v2.png
ADDED
![]() |
Git LFS Details
|