(
self,
examples: List[Union[List[int], Dict[str, Any]]]
)
| 177 | return_tensors: str = "pt" |
| 178 | |
| 179 | def __call__( |
| 180 | self, |
| 181 | examples: List[Union[List[int], Dict[str, Any]]] |
| 182 | ) -> Dict[str, Any]: |
| 183 | if not isinstance(examples[0], Dict): |
| 184 | examples = [{'input_ids': example} for example in examples] |
| 185 | |
| 186 | def tensorize(example: Dict[str, Any]) -> Dict[str, Any]: |
| 187 | tensorized = {} |
| 188 | for key in ['input_ids', 'offsets']: |
| 189 | if key not in example: |
| 190 | continue |
| 191 | if isinstance(example[key], List): |
| 192 | tensorized[key] = torch.tensor(example[key], dtype=torch.long) |
| 193 | elif isinstance(example[key], np.ndarray): |
| 194 | tensorized[key] = torch.from_numpy(example[key]) |
| 195 | else: |
| 196 | tensorized[key] = example[key] |
| 197 | return tensorized |
| 198 | |
| 199 | examples = list(map(tensorize, examples)) |
| 200 | |
| 201 | if not self.varlen: |
| 202 | length_of_first = examples[0]['input_ids'].size(0) |
| 203 | # Check if padding is necessary. |
| 204 | if all(example['input_ids'].size(0) == length_of_first for example in examples): |
| 205 | batch = { |
| 206 | 'input_ids': torch.stack([example['input_ids'] for example in examples], dim=0), |
| 207 | } |
| 208 | else: |
| 209 | # If yes, check if we have a `pad_token`. |
| 210 | if self.tokenizer._pad_token is None: |
| 211 | raise ValueError( |
| 212 | f"You are attempting to pad samples but the tokenizer you are using " |
| 213 | f"({self.tokenizer.__class__.__name__}) does not have a pad token." |
| 214 | ) |
| 215 | batch = self.tokenizer.pad(examples, return_tensors=self.return_tensors, return_attention_mask=False) |
| 216 | else: |
| 217 | if len(examples) > 1: |
| 218 | raise ValueError("The batch size must be 1 for variable length inputs.") |
| 219 | batch = { |
| 220 | 'input_ids': torch.cat([example['input_ids'] for example in examples], dim=0).unsqueeze(0) |
| 221 | } |
| 222 | if 'offsets' in examples[0]: |
| 223 | batch['offsets'] = torch.cat([example['offsets'] for example in examples], dim=0).unsqueeze(0) |
| 224 | else: |
| 225 | # determine boundaries by bos/eos positions |
| 226 | if self.tokenizer.add_bos_token: |
| 227 | offsets = [] |
| 228 | if batch['input_ids'][0, 0] != self.tokenizer.bos_token_id: |
| 229 | offsets.append(torch.tensor([0], dtype=torch.long)) |
| 230 | offsets.append(torch.where(batch['input_ids'].eq(self.tokenizer.bos_token_id))[1]) |
| 231 | offsets.append(torch.tensor([len(batch['input_ids'][0])], dtype=torch.long)) |
| 232 | batch['offsets'] = torch.cat(offsets, dim=0) |
| 233 | elif self.tokenizer.add_eos_token: |
| 234 | offsets = [torch.tensor([0], dtype=torch.long)] |
| 235 | offsets.append(torch.where(batch['input_ids'].eq(self.tokenizer.eos_token_id))[1] + 1) |
| 236 | if batch['input_ids'][0, -1] != self.tokenizer.eos_token_id: |
nothing calls this directly
no outgoing calls
no test coverage detected