This is a reranker fine tuning script. I am getting "ValueError: zero-size array to reduction operation minimum which has no identity" error at the end of the first epoch possibly during the process of evaluation. Can you tell me what went wrong?
import logging
import torch
from datasets import load_dataset, Dataset, Features, Value
from sentence_transformers import CrossEncoder, CrossEncoderTrainer, CrossEncoderTrainingArguments
from sentence_transformers.cross_encoder.evaluation import CrossEncoderRerankingEvaluator
from sentence_transformers.cross_encoder.losses import CachedMultipleNegativesRankingLoss
def generate_pairs(dataset):
"""
Generator function to yield (query, document, score) pairs from the dataset.
"""
for example in dataset:
# Positive pair
yield {
"query": example['anc'],
"positive": [example['pos']],
"negative": example['neg'][:NEG_SIZE],
}
# 2. Create Datasets using generator for train and test splits
# Split the original dataset first to maintain data distribution
dataset_splits = raw_dataset['train'].train_test_split(test_size=39680, seed=42)
# Create Dataset objects from generators
train_dataset = Dataset.from_generator(
lambda: generate_pairs(dataset_splits['train']),
features=Features({
"query": Value("string"),
"positive": Value("string"),
"negative": Value("string")
})
)
eval_dataset = Dataset.from_generator(
lambda: generate_pairs(dataset_splits['test']),
features=Features({
"query": Value("string"),
"posiive": Value("string"),
"negative": Value("string")
})
)
logger.info(f"Original dataset size: {len(raw_dataset)}")
logger.info(f"Transformed training pairs: {train_dataset.num_rows}")
logger.info(f"Transformed evaluation pairs: {eval_dataset.num_rows}")
# Load a model
model = CrossEncoder(BASE_MODEL_NAME, model_kwargs={"torch_dtype": torch.bfloat16})
# Initialize the evaluator
reranking_evaluator = CrossEncoderRerankingEvaluator(
samples=generate_pairs(dataset_splits['test']),
name="ruri-v3",
batch_size=BATCH_SZ,
show_progress_bar=True,
)
results = reranking_evaluator(model)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
logger.info(f"Training on device: {device}")
training_args = CrossEncoderTrainingArguments(
output_dir=OUTPUT_DIR,
eval_strategy="epoch",
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=BATCH_SZ, # Adjust based on GPU memory
per_device_eval_batch_size=BATCH_SZ,
num_train_epochs=5,
weight_decay=0.01,
load_best_model_at_end=True,
metric_for_best_model="eval_ruri-v3_ndcg@10",
bf16=True,
logging_dir='./logs',
logging_steps=93,
report_to="none",
seed=42
)
reranking_loss = CachedMultipleNegativesRankingLoss(model=model, num_negatives=4, mini_batch_size=32)
# 6. Initialize Trainer
trainer = CrossEncoderTrainer(
model=model,
args=training_args,
train_dataset=train_dataset,
loss=reranking_loss,
evaluator=reranking_evaluator,
)
# 7. Train
logger.info("Starting fine-tuning...")
trainer.train()
evaluator(model)
# 8. Save the Model
logger.info(f"Saving fine-tuned model to {OUTPUT_MODEL_NAME}")
model.save_pretrained(OUTPUT_MODEL_NAME)
logger.info("Fine-tuning complete.")
if name == "main":
main()
Assistant
The error you're encountering, "ValueError: zero-size array to reduction operation minimum which has no identity," typically occurs when a reduction operation (like min, max, or sum) is applied to an empty array or tensor. In your case, this is likely happening during the evaluation phase, specifically with the CrossEncoderRerankingEvaluator, at the end of the first epoch.
What Went Wrong?
Generator Exhaustion Issue:
You're passing a generator (generate_pairs(dataset_splits['test'])) to the CrossEncoderRerankingEvaluator. Generators in Python are lazy iterators and can only be consumed once.
In your script, the evaluator is called twice:
Once explicitly before training with results = reranking_evaluator(model).
Again during training (at the end of each epoch) because you pass evaluator=reranking_evaluator to the CrossEncoderTrainer.
After the first call (results = reranking_evaluator(model)), the generator is fully consumed and becomes empty. When the trainer tries to use the evaluator again (e.g., at the end of the first epoch), it receives no samples, leading to an empty array or tensor. This causes the reduction operation in the evaluator (likely computing metrics like NDCG) to fail.
Data Format Mismatch or Typos:
In the eval_dataset generator, there's a typo in the features: "posiive": Value("string") should be "positive": Value("string"). This might not directly cause the error but could lead to issues with data loading.
The generate_pairs function yields dictionaries with keys "query", "positive", and "negative". However, CrossEncoderRerankingEvaluator and related components in Sentence Transformers often expect InputExample objects (from sentence_transformers.readers.InputExample), which have a specific format (texts and label). Using raw dictionaries might not be handled correctly, potentially contributing to the error.
Evaluation Timing:
The error occurs during evaluation, which involves computing metrics. If the evaluator has no valid samples (due to the exhausted generator), it can't compute statistics, leading to the zero-size array error.
The CachedMultipleNegativesRankingLoss is set up correctly for reranking, but ensure that the data format matches what the loss function expects (e.g., batches with positive and negative pairs).
The line evaluator(model) at the end of the script is redundant and could cause similar issues if the generator is already exhausted.
How to Fix It
To resolve this, you should:
Materialize the generator into a list or use InputExample objects: This ensures the data is not lazy and can be reused multiple times without exhaustion.
Remove the redundant pre-training evaluation call: The line results = reranking_evaluator(model) is unnecessary and is likely the root cause. Let the trainer handle evaluation.
Use InputExample for consistency: Convert your data to InputExample objects, as they are designed for Sentence Transformers workflows.
Fix the typo in the eval dataset features.
Here's a revised version of your script with these fixes. I've switched to using InputExample for both training and evaluation datasets, and removed the problematic pre-training evaluation call. This should make the script more robust and error-free.
Revised Script
python
import logging
import torch
from datasets import load_dataset, Dataset, Features, Value
from sentence_transformers import CrossEncoder, CrossEncoderTrainer, CrossEncoderTrainingArguments
from sentence_transformers.cross_encoder.evaluation import CrossEncoderRerankingEvaluator
from sentence_transformers.cross_encoder.losses import CachedMultipleNegativesRankingLoss
from sentence_transformers.readers import InputExample
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configuration
BASE_MODEL_NAME = "cl-nagoya/ruri-v3-pt-130m"
DATASET_NAME = "cl-nagoya/ruri-v3-dataset-reranker"
OUTPUT_MODEL_NAME = "cl-nagoya/ruri-v3-reranker-130m"
OUTPUT_DIR = "./ruri-v3-reranker-training"
MAX_SEQ_LEN = 1024 # Not used in this script; consider removing if unnecessary
BATCH_SZ = 64
NEG_SIZE = 4
def generate_input_examples(dataset):
"""
Generator function to yield InputExample objects for (query, document) pairs.
"""
for example in dataset:
query = example['anc']
# Positive pair (using label from score.pos)
yield InputExample(texts=[query, example['pos']], label=float(example['score.pos']))
# Negative pairs (using labels from score.neg)
for neg_doc, neg_score in zip(example['neg'][:NEG_SIZE], example['score.neg'][:NEG_SIZE]):
yield InputExample(texts=[query, neg_doc], label=float(neg_score))
def main():
# 1. Load Dataset
raw_dataset = load_dataset(DATASET_NAME)
# 2. Split the dataset
dataset_splits = raw_dataset['train'].train_test_split(test_size=39680, seed=42)
# 3. Generate and materialize InputExamples for train and eval
# Convert generator to list to avoid exhaustion issues
train_examples = list(generate_input_examples(dataset_splits['train']))
eval_examples = list(generate_input_examples(dataset_splits['test']))
logger.info(f"Original dataset size: {len(raw_dataset)}")
logger.info(f"Transformed training pairs: {len(train_examples)}")
logger.info(f"Transformed evaluation pairs: {len(eval_examples)}")
# 4. Load model as a cross-encoder
model = CrossEncoder(BASE_MODEL_NAME, model_kwargs={"torch_dtype": torch.bfloat16})
# 5. Set up evaluator with materialized eval examples
# Use InputExample list for the evaluator
reranking_evaluator = CrossEncoderRerankingEvaluator(
samples=eval_examples, # Pass the list of InputExample objects
name="ruri-v3",
batch_size=BATCH_SZ,
show_progress_bar=True,
)
# 6. Training setup
device = 'cuda' if torch.cuda.is_available() else 'cpu'
logger.info(f"Training on device: {device}")
training_args = CrossEncoderTrainingArguments(
output_dir=OUTPUT_DIR,
eval_strategy="epoch", # Evaluate at the end of each epoch
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=BATCH_SZ, # Adjust based on GPU memory
per_device_eval_batch_size=BATCH_SZ,
num_train_epochs=5,
weight_decay=0.01,
load_best_model_at_end=True,
metric_for_best_model="eval_ruri-v3_ndcg@10", # Ensure this metric is valid
bf16=True,
logging_dir='./logs',
logging_steps=93,
report_to="none",
seed=42
)
# 7. Loss function
reranking_loss = CachedMultipleNegativesRankingLoss(model=model, num_negatives=NEG_SIZE)
# 8. Initialize Trainer
trainer = CrossEncoderTrainer(
model=model,
args=training_args,
train_dataset=train_examples, # Pass the list of InputExamples
loss=reranking_loss,
evaluator=reranking_evaluator, # Pass the evaluator
)
# 9. Train
logger.info("Starting fine-tuning...")
trainer.train()
# 10. Optional: Run evaluator again if needed (e.g., for final metrics)
# This is not necessary but can be used for debugging
logger.info("Running final evaluation...")
eval_result = reranking_evaluator(model)
logger.info(f"Final evaluation results: {eval_result}")
# 11. Save the Model
logger.info(f"Saving fine-tuned model to {OUTPUT_MODEL_NAME}")
model.save_pretrained(OUTPUT_MODEL_NAME)
logger.info("Fine-tuning complete.")
if __name__ == "__main__":
main()
Key Changes and Explanations
Materialized Data with InputExample:
Changed generate_pairs to generate_input_examples to yield InputExample objects, which are standard in Sentence Transformers.
Converted the generator output to lists (train_examples = list(generate_input_examples(...))) before passing to the trainer and evaluator. This ensures the data is fully loaded and can be reused without exhaustion.
Removed Redundant Evaluation Call:
Deleted the line results = reranking_evaluator(model) before training. This was likely consuming the generator and causing it to be empty during subsequent evaluations.
Fixed Typo in Data Features:
Corrected the typo in the eval dataset features (changed "posiive" to "positive" in the original generator, but since we're now using InputExample, this is no longer needed).
Evaluator Setup:
Now passes eval_examples (a list of InputExample) to CrossEncoderRerankingEvaluator. This ensures the evaluator has a fixed, non-lazy dataset to work with.
Added Final Evaluation for Debugging:
Added an optional call to reranking_evaluator(model) at the end of training to compute final metrics. This can help verify that evaluation works correctly.
General Improvements:
Ensured that the loss function (CachedMultipleNegativesRankingLoss) is compatible with the data format. It expects batches with positive and negative pairs, which should now be handled correctly with InputExample.
The metric "eval_ruri-v3_ndcg@10" in training_args assumes you're using NDCG@10 for evaluation. If this metric isn't defined or causes issues, you might need to customize the evaluator or use a different metric.
How to Test and Debug
Run the Script: Try running the revised script. The error should be resolved.
Check Logs: Look at the training logs for any other errors or warnings. The evaluator should now have valid samples.
Verify Dataset Size: Ensure that len(train_examples) and len(eval_examples) are non-zero and reasonable.
Handle Edge Cases: If your dataset has very few or no evaluation samples, the evaluator might still fail. Make sure the test split has data.
Custom Metrics: If "eval_ruri-v3_ndcg@10" is not a standard metric, you may need to define a custom evaluator or use built-in ones like CERerankingEvaluator.
If you still encounter issues, share more details about the error stack trace or your environment (e.g., Python version, library versions). This should fix the problem!