|
17 | 17 | ============== |
18 | 18 | Pretrained BERT encoder from Hugging Face. |
19 | 19 | """ |
20 | | -from typing import Dict, Optional |
| 20 | +from typing import Dict, List, Optional |
21 | 21 |
|
22 | 22 | import torch |
23 | 23 | from transformers import BertConfig, BertModel, BertTokenizerFast |
@@ -115,6 +115,23 @@ def freeze_embeddings(self) -> None: |
115 | 115 | for param in self.model.embeddings.parameters(): |
116 | 116 | param.requires_grad = False |
117 | 117 |
|
| 118 | + def build_inputs_with_special_tokens( |
| 119 | + self, token_ids_0: List[int], token_ids_1: List[int] |
| 120 | + ) -> List[int]: |
| 121 | + """Concatenate ids from two sequences. |
| 122 | +
|
| 123 | + Returns: |
| 124 | + List[int]: an encoded sequence. |
| 125 | + """ |
| 126 | + return ( |
| 127 | + [self.tokenizer.cls_token_id] |
| 128 | + + token_ids_0 |
| 129 | + + [self.tokenizer.sep_token_id] |
| 130 | + + token_ids_1 |
| 131 | + + [self.tokenizer.sep_token_id] |
| 132 | + ) |
| 133 | + |
| 134 | + |
118 | 135 | def layerwise_lr(self, lr: float, decay: float): |
119 | 136 | """Calculates the learning rate for each layer by applying a small decay. |
120 | 137 |
|
@@ -168,15 +185,23 @@ def forward( |
168 | 185 | Dict[str, torch.Tensor]: dictionary with 'sentemb', 'wordemb', 'all_layers' |
169 | 186 | and 'attention_mask'. |
170 | 187 | """ |
171 | | - last_hidden_states, pooler_output, all_layers = self.model( |
| 188 | + output = self.model( |
172 | 189 | input_ids=input_ids, |
173 | 190 | token_type_ids=token_type_ids, |
174 | 191 | attention_mask=attention_mask, |
175 | 192 | output_hidden_states=True, |
176 | 193 | return_dict=False, |
177 | 194 | ) |
| 195 | + |
| 196 | + if len(output) == 2: |
| 197 | + last_hidden_states, all_layers = output |
| 198 | + sentemb = last_hidden_states[:, 0, :] |
| 199 | + else: |
| 200 | + last_hidden_states, pooler_output, all_layers = output |
| 201 | + sentemb = pooler_output if pooler_output is not None else last_hidden_states[:, 0, :] |
| 202 | + |
178 | 203 | return { |
179 | | - "sentemb": pooler_output, |
| 204 | + "sentemb": sentemb, |
180 | 205 | "wordemb": last_hidden_states, |
181 | 206 | "all_layers": all_layers, |
182 | 207 | "attention_mask": attention_mask, |
|
0 commit comments