from datasets import load_dataset
from transformers import Trainer, TrainingArguments, DataCollatorForSeq2Seq
def preprocess_for_question_generation(examples):
if examples["answer"] is None or examples["context"] is None:
return None
code
if not isinstance(examples["answer"], list) or not isinstance(examples["context"], list):
return None
if len(examples["answer"]) != len(examples["context"]):
return None
prepared_input_texts = []
for context, answer in zip(examples["context"], examples["answer"]):
if "prepend" in examples:
input_format = f"answer: {answer} context: {context}"
elif "highlight" in examples:
input_format = f"<hl> {answer} <hl> {context}"
elif "answer_extraction" in examples:
sentences = context.split(".")
highlighted_sentences = []
for sentence in sentences:
if any(ans.lower() in sentence.lower() for ans in examples["answer"]):
highlighted_sentences.append(f"<hl> {sentence} <hl>")
input_format = " ".join(highlighted_sentences)
else:
return None
prepared_input_texts.append(input_format)
tokenized_inputs = tokenizer(
prepared_input_texts,
max_length=128,
padding="max_length",
truncation=True,
return_tensors="pt"
)
if "question" in examples:
tokenized_questions = tokenizer(
examples["question"],
max_length=64,
padding="max_length",
truncation=True,
return_tensors="pt"
)
tokenized_inputs["labels"] = tokenized_questions["input_ids"].clone()
return tokenized_inputs
File /opt/conda/lib/python3.10/site-packages/transformers/trainer.py:1928, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
1925 rng_to_sync = True
1927 step = -1
-> 1928 for step, inputs in enumerate(epoch_iterator):
1929 total_batched_samples += 1
1931 if self.args.include_num_input_tokens_seen:
File /opt/conda/lib/python3.10/site-packages/accelerate/data_loader.py:452, in DataLoaderShard.iter(self)
450 # We iterate one batch ahead to check when we are at the end
451 try:
--> 452 current_batch = next(dataloader_iter)
453 except StopIteration:
454 yield
File /opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py:630, in _BaseDataLoaderIter.next(self)
627 if self._sampler_iter is None:
628 # TODO(https://github.com/pytorch/pytorch/issues/76750)
629 self._reset() # type: ignore[call-arg]
--> 630 data = self._next_data()
631 self._num_yielded += 1
632 if self._dataset_kind == _DatasetKind.Iterable and
633 self._IterableDataset_len_called is not None and
634 self._num_yielded > self._IterableDataset_len_called:
File /opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py:674, in _SingleProcessDataLoaderIter._next_data(self)
672 def _next_data(self):
673 index = self._next_index() # may raise StopIteration
--> 674 data = self._dataset_fetcher.fetch(index) # may raise StopIteration
675 if self._pin_memory:
676 data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)
File /opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:51, in _MapDatasetFetcher.fetch(self, possibly_batched_index)
49 data = self.dataset.getitems(possibly_batched_index)
50 else:
---> 51 data = [self.dataset[idx] for idx in possibly_batched_index]
52 else:
53 data = self.dataset[possibly_batched_index]
File /opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:51, in (.0)
49 data = self.dataset.getitems(possibly_batched_index)
50 else:
---> 51 data = [self.dataset[idx] for idx in possibly_batched_index]
52 else:
53 data = self.dataset[possibly_batched_index]
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:1764, in Dataset.getitem(self, key)
1762 def getitem(self, key): # noqa: F811
1763 """Can be used to index columns (by string names) or rows (by integer index or iterable of indices or bools)."""
-> 1764 return self._getitem(
1765 key,
1766 )
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:1748, in Dataset._getitem(self, key, decoded, **kwargs)
1746 format_kwargs = format_kwargs if format_kwargs is not None else {}
1747 formatter = get_formatter(format_type, features=self.features, decoded=decoded, **format_kwargs)
-> 1748 pa_subtable = query_table(self._data, key, indices=self._indices if self._indices is not None else None)
1749 formatted_output = format_table(
1750 pa_subtable, key, formatter=formatter, format_columns=format_columns, output_all_columns=output_all_columns
1751 )
1752 return formatted_output
File /opt/conda/lib/python3.10/site-packages/datasets/formatting/formatting.py:486, in query_table(table, key, indices)
484 else:
485 size = indices.num_rows if indices is not None else table.num_rows
--> 486 _check_valid_index_key(key, size)
487 # Query the main table
488 if indices is None:
File /opt/conda/lib/python3.10/site-packages/datasets/formatting/formatting.py:429, in _check_valid_index_key(key, size)
427 if isinstance(key, int):
428 if (key < 0 and key + size < 0) or (key >= size):
--> 429 raise IndexError(f"Invalid key: {key} is out of bounds for size {size}")
430 return
431 elif isinstance(key, slice):
IndexError: Invalid key: 32037 is out of bounds for size 0
The IndexError you're encountering (Invalid key: 32037 is out of bounds for size 0) usually happens when you try to access an index in a dataset that doesn't exist. This can occur if your dataset is not properly loaded or if during processing, the dataset becomes empty or not correctly batched. There could be several reasons leading to this; let's address some potential issues and solutions to check:
Ensure Dataset is Loaded Correctly: Before processing the data, confirm that your datasets (both train_dataset and val_dataset) are loaded correctly and not empty. You can print the length or a few samples from both datasets to verify they're loaded as expected.
Batch Mismatch in Dataset and DataLoader: The error snippet does not show how train_dataset and val_dataset are created. Ensure the datasets processed through preprocess_for_question_generation should return a batch of examples rather than a single example or an incorrectly structured batch. When mapping the preprocessing function over the dataset, setting batched=True is correct, but confirm the function preprocess_for_question_generation handles batched input properly. It seems it does, considering your batch processing loop, but ensure the final return value matches expected formatting for the model training.
Check Preprocessing Function's Return Values: The preprocessing function must return properly formatted tokenized inputs for all batches. Any case where it returns None could lead to issues. Although the logic inside preprocess_for_question_generation seems to handle certain conditions, ensure that under no condition (especially edge cases) does it return None when batched=True.
Tokenization and Model Compatibility: Make sure tokenizer and model are correctly initialized and are compatible with each other. This usually doesn’t cause the specific IndexError you are facing but can lead to other issues during training.
Solutions:
Verify Dataset: Ensure that the dataset is not empty or incorrectly manipulated before passing it into the Trainer. You can add debug prints to check sizes:
Test Preprocessing Independently: Test your preprocessing function with a small subset of data before applying it to the entire dataset. This way, you can catch if the return format goes awry:
python
sample_dataset = train_dataset.select(range(10)) # Select a small subset for testing
processed_sample = sample_dataset.map(preprocess_for_question_generation, batched=True)
print("Processed sample size:", processed_sample.num_rows)
Error Handling in Preprocessing: Adjust your preprocessing function to handle edge cases more gracefully. Instead of returning None, consider returning an appropriately formatted empty batch or skipping such instances.
Review Custom Preprocessing Logic: Specifically consider how your logic alters input sizes or structures. If there’s any route that significantly changes dataset size or expected structure, identify and correct it.
If after these checks the issue persists, you may want to look deeper into how the batches are being generated and fed into the model, confirming that the expected sizes and structures align perfectly with what your model expects during training.