help me, i am doing review summarisation, using a transformer, i have finetuned it…
- User
help me, i am doing review summarisation, using a transformer, i have finetuned it (instruction fine-tuning on 50 cars), using pegasus large, then using in my application via pipeline,
problem is my model is hallucinating , creating details on it's own which were not mentioned, what to do here?
Assistant
You're facing a hallucination problem in your Pegasus-based review summarization model. Hallucinations occur when the model generates information not present in the input text, often due to insufficient or low-quality training data, overfitting, or aggressive decoding strategies. Here’s a step-by-step plan to mitigate this:
1. Improve Training Data Quality and Quantity
-
Increase the dataset size:
50 car reviews is extremely small for fine-tuning a large model like Pegasus. Aim for at least 1,000–5,000 high-quality, domain-specific reviews with faithful summaries.- Use public datasets (e.g., Amazon Reviews, Yelp) or scrape additional data (ensure compliance with terms of service).
- Focus on extractive summaries (copying phrases directly from the input) to train the model to avoid adding new information.
-
Ensure faithfulness in summaries:
- Manually curate summaries that strictly reflect the input text (no paraphrasing or extrapolation).
- Avoid noisy or overly verbose summaries during training.
-
Data augmentation:
- Use back-translation (translate reviews to another language and back) to generate more training examples while preserving meaning.
- Apply paraphrasing with controlled constraints (e.g., "Do not add new facts").
2. Adjust Fine-Tuning Strategy
-
Use constrained decoding during training:
- Modify the training process to force the model to prioritize copying tokens from the input text. Tools like Pointer-Generator Networks or Copy Mechanisms can help.
- Alternatively, use masked language modeling with a focus on preserving source content.
-
Add a hallucination-aware loss function:
- Train the model to penalize outputs that introduce unverified information. For example:
- Use a fact-checking module (e.g., a pre-trained NLI model) to score generated summaries and adjust the loss accordingly.
- Incorporate entailment losses to ensure the summary is entailed by the input.
- Train the model to penalize outputs that introduce unverified information. For example:
-
Instruction tuning with explicit rules:
- During fine-tuning, include instructions like:
"Generate a summary that does not add any new information. Only use details explicitly mentioned in the review."
- During fine-tuning, include instructions like:
3. Optimize Inference (Pipeline) Settings
If retraining is not feasible, tweak the decoding parameters in your pipeline to reduce hallucination:
Key Parameters to Adjust:
from transformers import PegasusTokenizer, PegasusForConditionalGeneration model = PegasusForConditionalGeneration.from_pretrained("your-finetuned-model") tokenizer = PegasusTokenizer.from_pretrained("your-finetuned-model") # Example input text input_text = "This car has a powerful engine, but the interior is very basic." # Decode with constraints outputs = model.generate( tokenizer(input_text, return_tensors="pt").input_ids, max_length=100, num_beams=4, # Increase beam search for better coherence no_repeat_ngram_size=2, # Prevent repeating phrases early_stopping=True, repetition_penalty=2.0, # Penalize repeated tokens length_penalty=1.0, # Balance between short/long outputs temperature=0.7, # Reduce randomness top_p=0.9, # Nucleus sampling top_k=50, # Limit token selection )Why These Work:
- Beam search (vs. greedy decoding) reduces the chance of generating implausible sequences.
- Repetition penalty discourages the model from repeating or fabricating phrases.
- Lower temperature makes the model more deterministic.
- No-repeat n-gram size prevents repetitive hallucinated phrases.
4. Add Post-Processing Filters
After generating a summary, apply filters to detect and remove hallucinations:
Example: Check for Out-of-Scope Information
def validate_summary(summary, input_text): # Simple check: Ensure all summary claims are in the input for sentence in summary.split("."): if not any(word in input_text.lower() for word in sentence.lower().split()): return False # Likely hallucination return True # Usage generated_summary = "The car has a powerful engine and a luxurious interior." if not validate_summary(generated_summary, input_text): print("Potential hallucination detected!")Advanced Option: Use a Fact-Checking Model
- Integrate a pre-trained NLI (Natural Language Inference) model (e.g.,
roberta-basewith a classifier) to verify if the summary is entailed by the input text. - Example:
from transformers import AutoModelForSequenceClassification, AutoTokenizer nli_model = AutoModelForSequenceClassification.from_pretrained("facebook/bart-large-mnli") nli_tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-mnli") def is_entailed(summary, input_text): inputs = nli_tokenizer(input_text, summary, return_tensors="pt", truncation=True) outputs = nli_model(**inputs) logits = outputs.logits predicted_class = logits.argmax().item() return predicted_class == 2 # 2 = "entailment"
5. Consider Alternative Architectures
If hallucination persists, try these alternatives:
- T5: A more robust model for summarization with better control over output.
- BART: Designed for sequence-to-sequence tasks and may handle hallucination better.
- Retrieval-Augmented Generation (RAG): Use a retriever to fetch relevant parts of the input text during generation.
- Fact-Enforcing Models: Look for models trained with factuality constraints (e.g., Factual Consistency).
6. Evaluate Faithfulness Metrics
Use automated metrics to quantify hallucination:
- FactCC: Measures factual consistency between input and output.
- QAGS: Evaluates whether the summary answers questions about the input.
- ROUGE-L: While not perfect, it can still indicate if the summary is missing key points.
Install FactCC:
pip install factccEvaluate:
from factcc import FactCC factcc = FactCC() score = factcc.score(input_text, generated_summary) print(f"Faithfulness score: {score}")
Summary of Immediate Actions
- Expand and clean your training data (aim for 1,000+ examples).
- Adjust decoding parameters (beam search, repetition penalty, lower temperature).
- Add post-processing filters to reject hallucinated summaries.
- Validate summaries with NLI or FactCC.
- Consider retraining with a more robust model (e.g., T5, BART, or RAG).
If you’re stuck, let me know your specific pipeline code or dataset size, and I’ll tailor advice further!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.