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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags: []
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Details
|
| 13 |
+
|
| 14 |
+
### Model Description
|
| 15 |
+
|
| 16 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 17 |
+
|
| 18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
| 19 |
+
|
| 20 |
+
- **Developed by:** [More Information Needed]
|
| 21 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 22 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 23 |
+
- **Model type:** [More Information Needed]
|
| 24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 25 |
+
- **License:** [More Information Needed]
|
| 26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 27 |
+
|
| 28 |
+
### Model Sources [optional]
|
| 29 |
+
|
| 30 |
+
<!-- Provide the basic links for the model. -->
|
| 31 |
+
|
| 32 |
+
- **Repository:** [More Information Needed]
|
| 33 |
+
- **Paper [optional]:** [More Information Needed]
|
| 34 |
+
- **Demo [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
## Uses
|
| 37 |
+
|
| 38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 39 |
+
|
| 40 |
+
### Direct Use
|
| 41 |
+
|
| 42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 43 |
+
|
| 44 |
+
[More Information Needed]
|
| 45 |
+
|
| 46 |
+
### Downstream Use [optional]
|
| 47 |
+
|
| 48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 49 |
+
|
| 50 |
+
[More Information Needed]
|
| 51 |
+
|
| 52 |
+
### Out-of-Scope Use
|
| 53 |
+
|
| 54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 55 |
+
|
| 56 |
+
[More Information Needed]
|
| 57 |
+
|
| 58 |
+
## Bias, Risks, and Limitations
|
| 59 |
+
|
| 60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 61 |
+
|
| 62 |
+
[More Information Needed]
|
| 63 |
+
|
| 64 |
+
### Recommendations
|
| 65 |
+
|
| 66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 67 |
+
|
| 68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 69 |
+
|
| 70 |
+
## How to Get Started with the Model
|
| 71 |
+
|
| 72 |
+
Use the code below to get started with the model.
|
| 73 |
+
|
| 74 |
+
[More Information Needed]
|
| 75 |
+
|
| 76 |
+
## Training Details
|
| 77 |
+
|
| 78 |
+
### Training Data
|
| 79 |
+
|
| 80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
### Training Procedure
|
| 85 |
+
|
| 86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 87 |
+
|
| 88 |
+
#### Preprocessing [optional]
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#### Training Hyperparameters
|
| 94 |
+
|
| 95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 96 |
+
|
| 97 |
+
#### Speeds, Sizes, Times [optional]
|
| 98 |
+
|
| 99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 100 |
+
|
| 101 |
+
[More Information Needed]
|
| 102 |
+
|
| 103 |
+
## Evaluation
|
| 104 |
+
|
| 105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 106 |
+
|
| 107 |
+
### Testing Data, Factors & Metrics
|
| 108 |
+
|
| 109 |
+
#### Testing Data
|
| 110 |
+
|
| 111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 112 |
+
|
| 113 |
+
[More Information Needed]
|
| 114 |
+
|
| 115 |
+
#### Factors
|
| 116 |
+
|
| 117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 118 |
+
|
| 119 |
+
[More Information Needed]
|
| 120 |
+
|
| 121 |
+
#### Metrics
|
| 122 |
+
|
| 123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 124 |
+
|
| 125 |
+
[More Information Needed]
|
| 126 |
+
|
| 127 |
+
### Results
|
| 128 |
+
|
| 129 |
+
[More Information Needed]
|
| 130 |
+
|
| 131 |
+
#### Summary
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
## Model Examination [optional]
|
| 136 |
+
|
| 137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 138 |
+
|
| 139 |
+
[More Information Needed]
|
| 140 |
+
|
| 141 |
+
## Environmental Impact
|
| 142 |
+
|
| 143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 144 |
+
|
| 145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 146 |
+
|
| 147 |
+
- **Hardware Type:** [More Information Needed]
|
| 148 |
+
- **Hours used:** [More Information Needed]
|
| 149 |
+
- **Cloud Provider:** [More Information Needed]
|
| 150 |
+
- **Compute Region:** [More Information Needed]
|
| 151 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 152 |
+
|
| 153 |
+
## Technical Specifications [optional]
|
| 154 |
+
|
| 155 |
+
### Model Architecture and Objective
|
| 156 |
+
|
| 157 |
+
[More Information Needed]
|
| 158 |
+
|
| 159 |
+
### Compute Infrastructure
|
| 160 |
+
|
| 161 |
+
[More Information Needed]
|
| 162 |
+
|
| 163 |
+
#### Hardware
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
#### Software
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
## Citation [optional]
|
| 172 |
+
|
| 173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 174 |
+
|
| 175 |
+
**BibTeX:**
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
**APA:**
|
| 180 |
+
|
| 181 |
+
[More Information Needed]
|
| 182 |
+
|
| 183 |
+
## Glossary [optional]
|
| 184 |
+
|
| 185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 186 |
+
|
| 187 |
+
[More Information Needed]
|
| 188 |
+
|
| 189 |
+
## More Information [optional]
|
| 190 |
+
|
| 191 |
+
[More Information Needed]
|
| 192 |
+
|
| 193 |
+
## Model Card Authors [optional]
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## Model Card Contact
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
config.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "constbert/",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"ConstBERT"
|
| 5 |
+
],
|
| 6 |
+
"attention_probs_dropout_prob": 0.1,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoModel": "modeling.ConstBERT"
|
| 9 |
+
},
|
| 10 |
+
"classifier_dropout": null,
|
| 11 |
+
"gradient_checkpointing": false,
|
| 12 |
+
"hidden_act": "gelu",
|
| 13 |
+
"hidden_dropout_prob": 0.1,
|
| 14 |
+
"hidden_size": 768,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"intermediate_size": 3072,
|
| 17 |
+
"layer_norm_eps": 1e-12,
|
| 18 |
+
"max_position_embeddings": 512,
|
| 19 |
+
"model_type": "bert",
|
| 20 |
+
"num_attention_heads": 12,
|
| 21 |
+
"num_hidden_layers": 12,
|
| 22 |
+
"pad_token_id": 0,
|
| 23 |
+
"position_embedding_type": "absolute",
|
| 24 |
+
"torch_dtype": "float32",
|
| 25 |
+
"transformers_version": "4.48.1",
|
| 26 |
+
"type_vocab_size": 2,
|
| 27 |
+
"use_cache": true,
|
| 28 |
+
"vocab_size": 30522
|
| 29 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e63f29e724efa1b9461cdc11af501c0c0fc09ac8c2c334ebf6e5dc4e45e422be
|
| 3 |
+
size 438386000
|
modeling.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from transformers import BertPreTrainedModel, BertModel, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
from transformers import AutoTokenizer
|
| 6 |
+
from constbert.colbert_configuration import ColBERTConfig
|
| 7 |
+
from constbert.tokenization_utils import QueryTokenizer, DocTokenizer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class NullContextManager(object):
|
| 11 |
+
def __init__(self, dummy_resource=None):
|
| 12 |
+
self.dummy_resource = dummy_resource
|
| 13 |
+
def __enter__(self):
|
| 14 |
+
return self.dummy_resource
|
| 15 |
+
def __exit__(self, *args):
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
class MixedPrecisionManager():
|
| 19 |
+
def __init__(self, activated):
|
| 20 |
+
self.activated = activated
|
| 21 |
+
|
| 22 |
+
if self.activated:
|
| 23 |
+
self.scaler = torch.cuda.amp.GradScaler()
|
| 24 |
+
|
| 25 |
+
def context(self):
|
| 26 |
+
return torch.cuda.amp.autocast() if self.activated else NullContextManager()
|
| 27 |
+
|
| 28 |
+
def backward(self, loss):
|
| 29 |
+
if self.activated:
|
| 30 |
+
self.scaler.scale(loss).backward()
|
| 31 |
+
else:
|
| 32 |
+
loss.backward()
|
| 33 |
+
|
| 34 |
+
def step(self, colbert, optimizer, scheduler=None):
|
| 35 |
+
if self.activated:
|
| 36 |
+
self.scaler.unscale_(optimizer)
|
| 37 |
+
torch.nn.utils.clip_grad_norm_(colbert.parameters(), 2.0, error_if_nonfinite=False)
|
| 38 |
+
|
| 39 |
+
self.scaler.step(optimizer)
|
| 40 |
+
self.scaler.update()
|
| 41 |
+
else:
|
| 42 |
+
torch.nn.utils.clip_grad_norm_(colbert.parameters(), 2.0)
|
| 43 |
+
optimizer.step()
|
| 44 |
+
|
| 45 |
+
if scheduler is not None:
|
| 46 |
+
scheduler.step()
|
| 47 |
+
|
| 48 |
+
optimizer.zero_grad()
|
| 49 |
+
|
| 50 |
+
class ConstBERT(BertPreTrainedModel):
|
| 51 |
+
"""
|
| 52 |
+
Shallow wrapper around HuggingFace transformers. All new parameters should be defined at this level.
|
| 53 |
+
|
| 54 |
+
This makes sure `{from,save}_pretrained` and `init_weights` are applied to new parameters correctly.
|
| 55 |
+
"""
|
| 56 |
+
_keys_to_ignore_on_load_unexpected = [r"cls"]
|
| 57 |
+
|
| 58 |
+
def __init__(self, config, colbert_config, verbose:int = 3):
|
| 59 |
+
super().__init__(config)
|
| 60 |
+
|
| 61 |
+
self.config = config
|
| 62 |
+
self.dim = colbert_config.dim
|
| 63 |
+
self.linear = nn.Linear(config.hidden_size, colbert_config.dim, bias=False)
|
| 64 |
+
self.doc_project = nn.Linear(colbert_config.doc_maxlen, 32, bias=False)
|
| 65 |
+
self.query_project = nn.Linear(colbert_config.query_maxlen, 64, bias=False)
|
| 66 |
+
|
| 67 |
+
self.query_tokenizer = QueryTokenizer(colbert_config, verbose=verbose)
|
| 68 |
+
self.doc_tokenizer = DocTokenizer(colbert_config)
|
| 69 |
+
self.amp_manager = MixedPrecisionManager(True)
|
| 70 |
+
|
| 71 |
+
self.raw_tokenizer = AutoTokenizer.from_pretrained(colbert_config.checkpoint)
|
| 72 |
+
self.pad_token = self.raw_tokenizer.pad_token_id
|
| 73 |
+
self.use_gpu = colbert_config.total_visible_gpus > 0
|
| 74 |
+
|
| 75 |
+
setattr(self,self.base_model_prefix, BertModel(config))
|
| 76 |
+
|
| 77 |
+
# if colbert_config.relu:
|
| 78 |
+
# self.score_scaler = nn.Linear(1, 1)
|
| 79 |
+
|
| 80 |
+
self.init_weights()
|
| 81 |
+
|
| 82 |
+
# if colbert_config.relu:
|
| 83 |
+
# self.score_scaler.weight.data.fill_(1.0)
|
| 84 |
+
# self.score_scaler.bias.data.fill_(-8.0)
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def LM(self):
|
| 88 |
+
base_model_prefix = getattr(self, "base_model_prefix")
|
| 89 |
+
return getattr(self, base_model_prefix)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@classmethod
|
| 93 |
+
def from_pretrained(cls, name_or_path):
|
| 94 |
+
colbert_config = ColBERTConfig(name_or_path)
|
| 95 |
+
colbert_config = ColBERTConfig.from_existing(ColBERTConfig.load_from_checkpoint(name_or_path), colbert_config)
|
| 96 |
+
obj = super().from_pretrained(name_or_path, colbert_config=colbert_config)
|
| 97 |
+
obj.base = name_or_path
|
| 98 |
+
|
| 99 |
+
return obj
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def raw_tokenizer_from_pretrained(name_or_path):
|
| 103 |
+
obj = AutoTokenizer.from_pretrained(name_or_path)
|
| 104 |
+
obj.base = name_or_path
|
| 105 |
+
|
| 106 |
+
return obj
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _query(self, input_ids, attention_mask):
|
| 110 |
+
input_ids, attention_mask = input_ids.to(self.device), attention_mask.to(self.device)
|
| 111 |
+
Q = self.bert(input_ids, attention_mask=attention_mask)[0]
|
| 112 |
+
# Q = Q.permute(0, 2, 1) #(64, 128,32)
|
| 113 |
+
# Q = self.query_project(Q) #(64, 128,8)
|
| 114 |
+
# Q = Q.permute(0, 2, 1) #(64,8,128)
|
| 115 |
+
Q = self.linear(Q)
|
| 116 |
+
# mask = torch.ones(Q.shape[0], Q.shape[1], device=self.device).unsqueeze(2).float()
|
| 117 |
+
|
| 118 |
+
mask = torch.tensor(self.mask(input_ids, skiplist=[]), device=self.device).unsqueeze(2).float()
|
| 119 |
+
Q = Q * mask
|
| 120 |
+
|
| 121 |
+
return torch.nn.functional.normalize(Q, p=2, dim=2)
|
| 122 |
+
|
| 123 |
+
def _doc(self, input_ids, attention_mask, keep_dims=True):
|
| 124 |
+
assert keep_dims in [True, False, 'return_mask']
|
| 125 |
+
|
| 126 |
+
input_ids, attention_mask = input_ids.to(self.device), attention_mask.to(self.device)
|
| 127 |
+
D = self.bert(input_ids, attention_mask=attention_mask)[0]
|
| 128 |
+
D = D.permute(0, 2, 1) #(64, 128,180)
|
| 129 |
+
D = self.doc_project(D) #(64, 128,16)
|
| 130 |
+
D = D.permute(0, 2, 1) #(64,16,128)
|
| 131 |
+
D = self.linear(D)
|
| 132 |
+
mask = torch.ones(D.shape[0], D.shape[1], device=self.device).unsqueeze(2).float()
|
| 133 |
+
|
| 134 |
+
# mask = torch.tensor(self.mask(input_ids, skiplist=self.skiplist), device=self.device).unsqueeze(2).float()
|
| 135 |
+
D = D * mask
|
| 136 |
+
D = torch.nn.functional.normalize(D, p=2, dim=2)
|
| 137 |
+
if self.use_gpu:
|
| 138 |
+
D = D.half()
|
| 139 |
+
|
| 140 |
+
if keep_dims is False:
|
| 141 |
+
D, mask = D.cpu(), mask.bool().cpu().squeeze(-1)
|
| 142 |
+
D = [d[mask[idx]] for idx, d in enumerate(D)]
|
| 143 |
+
|
| 144 |
+
elif keep_dims == 'return_mask':
|
| 145 |
+
return D, mask.bool()
|
| 146 |
+
|
| 147 |
+
return D
|
| 148 |
+
|
| 149 |
+
def mask(self, input_ids, skiplist):
|
| 150 |
+
mask = [[(x not in skiplist) and (x != self.pad_token) for x in d] for d in input_ids.cpu().tolist()]
|
| 151 |
+
return mask
|
| 152 |
+
|
| 153 |
+
def query(self, *args, to_cpu=False, **kw_args):
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
with self.amp_manager.context():
|
| 156 |
+
Q = self._query(*args, **kw_args)
|
| 157 |
+
return Q.cpu() if to_cpu else Q
|
| 158 |
+
|
| 159 |
+
def doc(self, *args, to_cpu=False, **kw_args):
|
| 160 |
+
with torch.no_grad():
|
| 161 |
+
with self.amp_manager.context():
|
| 162 |
+
D = self._doc(*args, **kw_args)
|
| 163 |
+
|
| 164 |
+
if to_cpu:
|
| 165 |
+
return (D[0].cpu(), *D[1:]) if isinstance(D, tuple) else D.cpu()
|
| 166 |
+
|
| 167 |
+
return D
|
| 168 |
+
|
| 169 |
+
def queryFromText(self, queries, bsize=None, to_cpu=False, context=None, full_length_search=False):
|
| 170 |
+
if bsize:
|
| 171 |
+
batches = self.query_tokenizer.tensorize(queries, context=context, bsize=bsize, full_length_search=full_length_search)
|
| 172 |
+
batches = [self.query(input_ids, attention_mask, to_cpu=to_cpu) for input_ids, attention_mask in batches]
|
| 173 |
+
return torch.cat(batches)
|
| 174 |
+
|
| 175 |
+
input_ids, attention_mask = self.query_tokenizer.tensorize(queries, context=context, full_length_search=full_length_search)
|
| 176 |
+
return self.query(input_ids, attention_mask)
|
| 177 |
+
|
| 178 |
+
def docFromText(self, docs, bsize=None, keep_dims=True, to_cpu=False, showprogress=False, return_tokens=False):
|
| 179 |
+
assert keep_dims in [True, False, 'flatten']
|
| 180 |
+
|
| 181 |
+
if bsize:
|
| 182 |
+
text_batches, reverse_indices = self.doc_tokenizer.tensorize(docs, bsize=bsize)
|
| 183 |
+
|
| 184 |
+
returned_text = []
|
| 185 |
+
if return_tokens:
|
| 186 |
+
returned_text = [text for batch in text_batches for text in batch[0]]
|
| 187 |
+
returned_text = [returned_text[idx] for idx in reverse_indices.tolist()]
|
| 188 |
+
returned_text = [returned_text]
|
| 189 |
+
|
| 190 |
+
keep_dims_ = 'return_mask' if keep_dims == 'flatten' else keep_dims
|
| 191 |
+
batches = [self.doc(input_ids, attention_mask, keep_dims=keep_dims_, to_cpu=to_cpu)
|
| 192 |
+
for input_ids, attention_mask in tqdm(text_batches, disable=not showprogress)]
|
| 193 |
+
|
| 194 |
+
if keep_dims is True:
|
| 195 |
+
D = _stack_3D_tensors(batches)
|
| 196 |
+
return (D[reverse_indices], *returned_text)
|
| 197 |
+
|
| 198 |
+
elif keep_dims == 'flatten':
|
| 199 |
+
D, mask = [], []
|
| 200 |
+
|
| 201 |
+
for D_, mask_ in batches:
|
| 202 |
+
D.append(D_)
|
| 203 |
+
mask.append(mask_)
|
| 204 |
+
|
| 205 |
+
D, mask = torch.cat(D)[reverse_indices], torch.cat(mask)[reverse_indices]
|
| 206 |
+
|
| 207 |
+
doclens = mask.squeeze(-1).sum(-1).tolist()
|
| 208 |
+
|
| 209 |
+
D = D.view(-1, self.colbert_config.dim)
|
| 210 |
+
D = D[mask.bool().flatten()].cpu()
|
| 211 |
+
|
| 212 |
+
return (D, doclens, *returned_text)
|
| 213 |
+
|
| 214 |
+
assert keep_dims is False
|
| 215 |
+
|
| 216 |
+
D = [d for batch in batches for d in batch]
|
| 217 |
+
return ([D[idx] for idx in reverse_indices.tolist()], *returned_text)
|
| 218 |
+
|
| 219 |
+
input_ids, attention_mask = self.doc_tokenizer.tensorize(docs)
|
| 220 |
+
return self.doc(input_ids, attention_mask, keep_dims=keep_dims, to_cpu=to_cpu)
|
| 221 |
+
|
| 222 |
+
def _stack_3D_tensors(groups):
|
| 223 |
+
bsize = sum([x.size(0) for x in groups])
|
| 224 |
+
maxlen = max([x.size(1) for x in groups])
|
| 225 |
+
hdim = groups[0].size(2)
|
| 226 |
+
|
| 227 |
+
output = torch.zeros(bsize, maxlen, hdim, device=groups[0].device, dtype=groups[0].dtype)
|
| 228 |
+
|
| 229 |
+
offset = 0
|
| 230 |
+
for x in groups:
|
| 231 |
+
endpos = offset + x.size(0)
|
| 232 |
+
output[offset:endpos, :x.size(1)] = x
|
| 233 |
+
offset = endpos
|
| 234 |
+
|
| 235 |
+
return output
|