To make the model stop generating when it encounters a specific string like "</answer>", you can use the stopping_criteria parameter in the generate method. Here's how you can modify your code:
from transformers import StoppingCriteria, StoppingCriteriaList
# Define custom stopping criteria
class StopOnTokens(StoppingCriteria):
def __init__(self, stop_string, tokenizer):
super().__init__()
self.stop_string = stop_string
self.tokenizer = tokenizer
# Precompute the stop token IDs
self.stop_token_ids = self.tokenizer.encode(stop_string, add_special_tokens=False)
# We'll look for sequences that match the stop string
self.stop_length = len(self.stop_token_ids)
def __call__(self, input_ids, scores, **kwargs):
# Check if the last generated tokens match the stop string
if input_ids.shape[1] < self.stop_length:
return False
for i in range(self.stop_length):
if input_ids[0, -self.stop_length + i] != self.stop_token_ids[i]:
return False
return True
# Create the stopping criteria instance
stop_criteria = StopOnTokens("</answer>", tokenizer)
# Use it in generation
generated_ids = model.generate(
**model_inputs,
max_new_tokens=16384,
temperature=1.0,
do_sample=True,
stopping_criteria=StoppingCriteriaList([stop_criteria])
)
Alternatively, if you're using a recent version of the Transformers library (4.25.0+), you can use the simpler stopping_strings approach:
generated_ids = model.generate(
**model_inputs,
max_new_tokens=16384,
temperature=1.0,
do_sample=True,
stopping_strings=["</answer>"]
)
Note that:
- The custom
StoppingCriteria approach gives you more control and works with all versions
- The stopping string will be included in the output (the generation stops after producing it)
- Make sure your tokenizer is the same one used by the model
- For very long stop strings, the custom approach might need adjustment to handle multi-token sequences properly
If you want the stop string to be excluded from the output, you'll need to manually truncate the generated text after generation.