in compute_metrics(eval_pred)
54
55 # Decode the predicted tokens into text
---> 56 decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
57
58 # Replace -100 in the labels as we can't decode them
/usr/local/lib/python3.10/dist-packages/transformers/tokenization_utils_base.py in batch_decode(self, sequences, skip_special_tokens, clean_up_tokenization_spaces, **kwargs)
3974 List[str]: The list of decoded sentences.
3975 """
-> 3976 return [
3977 self.decode(
3978 seq,
/usr/local/lib/python3.10/dist-packages/transformers/models/t5/tokenization_t5.py in _convert_id_to_token(self, index)
404 def _convert_id_to_token(self, index):
405 """Converts an index (integer) in a token (str) using the vocab."""
--> 406 token = self.sp_model.IdToPiece(index)
407 return token
408
/usr/local/lib/python3.10/dist-packages/sentencepiece/init.py in _batched_func(self, arg)
1043 return [_func(self, n) for n in arg]
1044 else:
-> 1045 return _func(self, arg)
1046
1047 setattr(classname, name, _batched_func)
/usr/local/lib/python3.10/dist-packages/sentencepiece/init.py in _func(v, n)
1036 def _func(v, n):
1037 if type(n) is int and (n < 0 or n >= v.piece_size()):
-> 1038 raise IndexError('piece id is out of range.')
1039 return func(v, n)
1040
IndexError: piece id is out of range.
The error you're encountering:
code
IndexError: piece id is out of range.
is due to invalid token IDs (specifically negative token IDs like -100) being passed to the tokenizer's decode function. The SentencePiece tokenizer (used by T5 and other models) expects token IDs to be in the range [0, vocab_size - 1]. Passing negative IDs causes it to raise an IndexError.
Notice that Min token ID in preds: -100, which indicates that preds contains -100 values. These -100 values are typically used in labels to indicate positions that should be ignored during loss computation (e.g., padding), but they should not appear in the model's predictions.
Why This Error Occurs:
Invalid Token IDs: The tokenizer.decode and tokenizer.batch_decode methods expect token IDs within the valid range [0, vocab_size - 1].
Negative Token IDs: Token IDs like -100 are invalid for decoding. Passing them to the tokenizer causes an IndexError.
Solution:
You need to ensure that all token IDs in preds are valid before passing them to the tokenizer for decoding. Here's how you can fix it:
Replace Negative Token IDs in Predictions:
Before decoding, replace any -100 values in preds with the tokenizer's pad_token_id or another valid token ID.
python
preds[preds == -100] = tokenizer.pad_token_id
Ensure Labels Are Handled Correctly:
Similarly, make sure that labels are processed properly. You can replace -100 in labels with the pad_token_id when necessary.
python
labels[labels == -100] = tokenizer.pad_token_id
Update Your compute_metrics Function:
Modify the compute_metrics function to handle the replacement before decoding.
Here's the corrected version of your compute_metrics function:
python
def compute_metrics(eval_pred):
preds, labels = eval_pred
# Replace -100 in predictions and labels
preds[preds == -100] = tokenizer.pad_token_id
labels[labels == -100] = tokenizer.pad_token_id
# Decode the predicted tokens into text
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
# Decode the labels into text
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
# Use the metric to compute Rouge scores or any other metrics
result = metric.compute(predictions=decoded_preds, references=decoded_labels)
# Optional: Format the result to include in logs
result = {k: round(v * 100, 4) for k, v in result.items()}
return result
Note: If you're using a padding token ID other than -100, adjust the replacements accordingly.
Verify the Predictions:
After making the change, you can print the again to ensure that there are no negative token IDs:
Explanation:
By replacing -100 with a valid token ID (like the pad_token_id), you ensure that all token IDs are within the valid range for decoding.
Decoding the pad_token_id will result in an empty string or the special token being skipped if you set skip_special_tokens=True.
Why Use pad_token_id:
The pad_token_id is a valid token in the tokenizer's vocabulary and is used to represent padding in sequences.
Replacing -100 with pad_token_id ensures that padding positions are properly handled during decoding and metric computation.
Additional Tips:
Check Model Outputs: Ensure that the model's output layer doesn't produce negative token IDs. If it does, there might be an issue with the model's architecture or training procedure.
Evaluation vs. Training Labels: Remember that -100 in labels is only used during training for the loss function to ignore certain positions. During evaluation, you should handle these positions appropriately.
Understanding -100 in Labels:
In many PyTorch models, -100 is used in labels to indicate that a particular position should be ignored when calculating the loss (e.g., CrossEntropyLoss ignores targets with -100).
However, the model's predictions should not contain -100. They should only output valid token IDs.
ignore_index (int, optional) – Specifies a target value that is ignored and does not contribute to the input gradient. When size_average is True, the loss is averaged over non-ignored targets.
By ensuring that all token IDs in preds are valid before decoding, you should be able to resolve the IndexError and proceed with evaluating your model.
Let me know if you have any questions or need further assistance!
Dataset releases
Not yet included in a published release.
preds
python
print(f"Min token ID in preds after replacement: {preds.min()}")