| 272 | |
| 273 | def get_data_loader(max_hidden_seq_length): |
| 274 | class SquadSeq2SeqDataset(torch.utils.data.Dataset): |
| 275 | def __init__( |
| 276 | self, |
| 277 | dataset_path, |
| 278 | tokenizer, |
| 279 | data_size, |
| 280 | max_hidden_seq_length, |
| 281 | ): |
| 282 | self.max_hidden_seq_length = max_hidden_seq_length |
| 283 | self.tokenizer = tokenizer |
| 284 | self.samples = self._load_and_process(dataset_path, data_size) |
| 285 | |
| 286 | def _load_and_process(self, path, max_samples): |
| 287 | with open(path, "r", encoding="utf-8") as f: |
| 288 | reader = csv.DictReader(f) |
| 289 | rows = list(reader) |
| 290 | if shuffle: |
| 291 | random.shuffle(rows) |
| 292 | samples = [] |
| 293 | for row in rows: |
| 294 | question = row["question"].strip() |
| 295 | context = row["context"].strip() |
| 296 | answer = row["answer"].strip() |
| 297 | if not question or not context or not answer: |
| 298 | continue |
| 299 | input_text = f"question: {question} context: {context}" |
| 300 | target_text = answer |
| 301 | samples.append((input_text, target_text)) |
| 302 | if len(samples) >= max_samples: |
| 303 | break |
| 304 | return samples |
| 305 | |
| 306 | def __len__(self): |
| 307 | return len(self.samples) |
| 308 | |
| 309 | def __getitem__(self, idx): |
| 310 | input_text, target_text = self.samples[idx] |
| 311 | model_input = tokenizer( |
| 312 | input_text, |
| 313 | truncation=True, |
| 314 | padding="max_length", |
| 315 | max_length=self.max_hidden_seq_length, |
| 316 | return_tensors="pt", |
| 317 | ) |
| 318 | label = tokenizer( |
| 319 | target_text, |
| 320 | truncation=True, |
| 321 | padding="max_length", |
| 322 | max_length=64, |
| 323 | return_tensors="pt", |
| 324 | ) |
| 325 | return { |
| 326 | "input_ids": model_input["input_ids"].squeeze(0), |
| 327 | "attention_mask": model_input["attention_mask"] |
| 328 | .reshape(1, 1, -1) |
| 329 | .to(torch.float32), |
| 330 | "decoder_input_ids": torch.tensor([0], dtype=torch.long), |
| 331 | "labels": label["input_ids"].squeeze(0), |