zhichao-geng
commited on
Commit
•
3a11c29
1
Parent(s):
00aa333
Update README.md
Browse files
README.md
CHANGED
@@ -1,3 +1,149 @@
|
|
1 |
-
---
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language: en
|
3 |
+
license: apache-2.0
|
4 |
+
tags:
|
5 |
+
- learned sparse
|
6 |
+
- opensearch
|
7 |
+
- transformers
|
8 |
+
- retrieval
|
9 |
+
- passage-retrieval
|
10 |
+
- document-expansion
|
11 |
+
- bag-of-words
|
12 |
+
---
|
13 |
+
|
14 |
+
# opensearch-neural-sparse-encoding-doc-v2-distill
|
15 |
+
This is a learned sparse retrieval model. It encodes the documents to 30522 dimensional **sparse vectors**. For queries, it just use a tokenizer and a weight look-up table to generate sparse vectors. The non-zero dimension index means the corresponding token in the vocabulary, and the weight means the importance of the token. And the similarity score is the inner product of query/document sparse vectors. In the real-world use case, the search performance of opensearch-neural-sparse-encoding-v1 is comparable to BM25.
|
16 |
+
|
17 |
+
This model is trained on MS MARCO dataset.
|
18 |
+
|
19 |
+
OpenSearch neural sparse feature supports learned sparse retrieval with lucene inverted index. Link: https://opensearch.org/docs/latest/query-dsl/specialized/neural-sparse/. The indexing and search can be performed with OpenSearch high-level API.
|
20 |
+
|
21 |
+
## Select the model
|
22 |
+
The model should be selected considering search relevance, model inference and retrieval efficiency(FLOPS). We benchmark models' **zero-shot performance** on a subset of BEIR benchmark: TrecCovid,NFCorpus,NQ,HotpotQA,FiQA,ArguAna,Touche,DBPedia,SCIDOCS,FEVER,Climate FEVER,SciFact,Quora.
|
23 |
+
|
24 |
+
Overall, the v2 series of models have better search relevance, efficiency and inference speed than the v1 series. The specific advantages and disadvantages may vary across different datasets.
|
25 |
+
|
26 |
+
| Model | Inference-free for Retrieval | Model Parameters | AVG NDCG@10 | AVG FLOPS |
|
27 |
+
|-------|------------------------------|------------------|-------------|-----------|
|
28 |
+
| [opensearch-neural-sparse-encoding-v1](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v1) | | 133M | 0.524 | 11.4 |
|
29 |
+
| [opensearch-neural-sparse-encoding-v2-distill](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v2-distill) | | 67M | 0.528 | 8.3 |
|
30 |
+
| [opensearch-neural-sparse-encoding-doc-v1](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v1) | ✔️ | 133M | 0.490 | 2.3 |
|
31 |
+
| [opensearch-neural-sparse-encoding-doc-v2-distill](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill) | ✔️ | 67M | 0.504 | 1.8 |
|
32 |
+
|
33 |
+
|
34 |
+
## Usage (HuggingFace)
|
35 |
+
This model is supposed to run inside OpenSearch cluster. But you can also use it outside the cluster, with HuggingFace models API.
|
36 |
+
|
37 |
+
```python
|
38 |
+
import json
|
39 |
+
import itertools
|
40 |
+
import torch
|
41 |
+
|
42 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
43 |
+
|
44 |
+
|
45 |
+
# get sparse vector from dense vectors with shape batch_size * seq_len * vocab_size
|
46 |
+
def get_sparse_vector(feature, output):
|
47 |
+
values, _ = torch.max(output*feature["attention_mask"].unsqueeze(-1), dim=1)
|
48 |
+
values = torch.log(1 + torch.relu(values))
|
49 |
+
values[:,special_token_ids] = 0
|
50 |
+
return values
|
51 |
+
|
52 |
+
# transform the sparse vector to a dict of (token, weight)
|
53 |
+
def transform_sparse_vector_to_dict(sparse_vector):
|
54 |
+
sample_indices,token_indices=torch.nonzero(sparse_vector,as_tuple=True)
|
55 |
+
non_zero_values = sparse_vector[(sample_indices,token_indices)].tolist()
|
56 |
+
number_of_tokens_for_each_sample = torch.bincount(sample_indices).cpu().tolist()
|
57 |
+
tokens = [transform_sparse_vector_to_dict.id_to_token[_id] for _id in token_indices.tolist()]
|
58 |
+
|
59 |
+
output = []
|
60 |
+
end_idxs = list(itertools.accumulate([0]+number_of_tokens_for_each_sample))
|
61 |
+
for i in range(len(end_idxs)-1):
|
62 |
+
token_strings = tokens[end_idxs[i]:end_idxs[i+1]]
|
63 |
+
weights = non_zero_values[end_idxs[i]:end_idxs[i+1]]
|
64 |
+
output.append(dict(zip(token_strings, weights)))
|
65 |
+
return output
|
66 |
+
|
67 |
+
# download the idf file from model hub. idf is used to give weights for query tokens
|
68 |
+
def get_tokenizer_idf(tokenizer):
|
69 |
+
from huggingface_hub import hf_hub_download
|
70 |
+
local_cached_path = hf_hub_download(repo_id="opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill", filename="idf.json")
|
71 |
+
with open(local_cached_path) as f:
|
72 |
+
idf = json.load(f)
|
73 |
+
idf_vector = [0]*tokenizer.vocab_size
|
74 |
+
for token,weight in idf.items():
|
75 |
+
_id = tokenizer._convert_token_to_id_with_added_voc(token)
|
76 |
+
idf_vector[_id]=weight
|
77 |
+
return torch.tensor(idf_vector)
|
78 |
+
|
79 |
+
# load the model
|
80 |
+
model = AutoModelForMaskedLM.from_pretrained("opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill")
|
81 |
+
tokenizer = AutoTokenizer.from_pretrained("opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill")
|
82 |
+
idf = get_tokenizer_idf(tokenizer)
|
83 |
+
|
84 |
+
# set the special tokens and id_to_token transform for post-process
|
85 |
+
special_token_ids = [tokenizer.vocab[token] for token in tokenizer.special_tokens_map.values()]
|
86 |
+
get_sparse_vector.special_token_ids = special_token_ids
|
87 |
+
id_to_token = ["" for i in range(tokenizer.vocab_size)]
|
88 |
+
for token, _id in tokenizer.vocab.items():
|
89 |
+
id_to_token[_id] = token
|
90 |
+
transform_sparse_vector_to_dict.id_to_token = id_to_token
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
query = "What's the weather in ny now?"
|
95 |
+
document = "Currently New York is rainy."
|
96 |
+
|
97 |
+
# encode the query
|
98 |
+
feature_query = tokenizer([query], padding=True, truncation=True, return_tensors='pt', return_token_type_ids=False)
|
99 |
+
input_ids = feature_query["input_ids"]
|
100 |
+
batch_size = input_ids.shape[0]
|
101 |
+
query_vector = torch.zeros(batch_size, tokenizer.vocab_size)
|
102 |
+
query_vector[torch.arange(batch_size).unsqueeze(-1), input_ids] = 1
|
103 |
+
query_sparse_vector = query_vector*idf
|
104 |
+
|
105 |
+
# encode the document
|
106 |
+
feature_document = tokenizer([document], padding=True, truncation=True, return_tensors='pt', return_token_type_ids=False)
|
107 |
+
output = model(**feature_document)[0]
|
108 |
+
document_sparse_vector = get_sparse_vector(feature_document, output)
|
109 |
+
|
110 |
+
|
111 |
+
# get similarity score
|
112 |
+
sim_score = torch.matmul(query_sparse_vector[0],document_sparse_vector[0])
|
113 |
+
print(sim_score) # tensor(12.8465, grad_fn=<DotBackward0>)
|
114 |
+
|
115 |
+
|
116 |
+
query_token_weight = transform_sparse_vector_to_dict(query_sparse_vector)[0]
|
117 |
+
document_query_token_weight = transform_sparse_vector_to_dict(document_sparse_vector)[0]
|
118 |
+
for token in sorted(query_token_weight, key=lambda x:query_token_weight[x], reverse=True):
|
119 |
+
if token in document_query_token_weight:
|
120 |
+
print("score in query: %.4f, score in document: %.4f, token: %s"%(query_token_weight[token],document_query_token_weight[token],token))
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
# result:
|
125 |
+
# score in query: 5.7729, score in document: 1.4109, token: ny
|
126 |
+
# score in query: 4.5684, score in document: 1.4673, token: weather
|
127 |
+
# score in query: 3.5895, score in document: 0.7473, token: now
|
128 |
+
```
|
129 |
+
|
130 |
+
The above code sample shows an example of neural sparse search. Although there is no overlap token in original query and document, but this model performs a good match.
|
131 |
+
|
132 |
+
## Detailed Search Relevance
|
133 |
+
|
134 |
+
| Dataset | [opensearch-neural-sparse-encoding-v1](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v1) | [opensearch-neural-sparse-encoding-v2-distill](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v2-distill) | [opensearch-neural-sparse-encoding-doc-v1](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v1) | [opensearch-neural-sparse-encoding-doc-v2-distill](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill) |
|
135 |
+
|---------|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------|------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
|
136 |
+
| Trec Covid | 0.771 | 0.775 | 0.707 | 0.690 |
|
137 |
+
| NFCorpus | 0.360 | 0.347 | 0.352 | 0.343 |
|
138 |
+
| NQ | 0.553 | 0.561 | 0.521 | 0.528 |
|
139 |
+
| HotpotQA | 0.697 | 0.685 | 0.677 | 0.675 |
|
140 |
+
| FiQA | 0.376 | 0.374 | 0.344 | 0.357 |
|
141 |
+
| ArguAna | 0.508 | 0.551 | 0.461 | 0.496 |
|
142 |
+
| Touche | 0.278 | 0.278 | 0.294 | 0.287 |
|
143 |
+
| DBPedia | 0.447 | 0.435 | 0.412 | 0.418 |
|
144 |
+
| SCIDOCS | 0.164 | 0.173 | 0.154 | 0.166 |
|
145 |
+
| FEVER | 0.821 | 0.849 | 0.743 | 0.818 |
|
146 |
+
| Climate FEVER | 0.263 | 0.249 | 0.202 | 0.224 |
|
147 |
+
| SciFact | 0.723 | 0.722 | 0.716 | 0.715 |
|
148 |
+
| Quora | 0.856 | 0.863 | 0.788 | 0.841 |
|
149 |
+
| **Average** | **0.524** | **0.528** | **0.490** | **0.504** |
|