Here’s a recipe for “interrupting” a Hugging Face generate() whenever the model emits a specific token‐sequence (e.g. "</answer>"). We’ll do it by:
- Tokenizing your stop‐string into a list of token‐IDs.
- Creating a custom
StoppingCriteria that watches the growing input_ids and returns True as soon as the last tokens match your stop‐IDs.
- Passing that into
model.generate(..., stopping_criteria=…).
from transformers import StoppingCriteria, StoppingCriteriaList
class StopOnString(StoppingCriteria):
"""
A StoppingCriteria that stops generation when the last tokens
exactly match `stop_token_ids`.
"""
def __init__(self, stop_token_ids):
super().__init__()
self.stop_token_ids = stop_token_ids
def __call__(self, input_ids, scores, **kwargs):
# input_ids is a tensor of shape (batch_size, cur_len)
# we only support batch_size == 1 here:
seq = input_ids[0].tolist()
if len(seq) < len(self.stop_token_ids):
return False
# compare the tail of seq against stop_token_ids
if seq[-len(self.stop_token_ids):] == self.stop_token_ids:
return True
return False
# 1) tokenize your stop string
stop_str = "</answer>"
stop_token_ids = tokenizer.encode(stop_str, add_special_tokens=False)
# 2) wrap it in a StoppingCriteriaList
stop_criteria = StoppingCriteriaList([StopOnString(stop_token_ids)])
# 3) call generate() with stopping_criteria
generated_ids = model.generate(
**model_inputs,
max_new_tokens=16384,
temperature=1.0,
do_sample=True,
stopping_criteria=stop_criteria,
)
output = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
print(output)
What happens under the hood?
- At every decoding step, your
StopOnString is invoked.
- As soon as the last N tokens of the sequence match the N tokens of
"</answer>", it returns True → generation halts.
Alternative: Post‐process the full generation
If you don’t mind generating the full batch and then chopping, you can simply
raw = tokenizer.decode(
generated_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=False
)
# split on the sentinel and keep the first part
trimmed = raw.split("</answer>")[0]
print(trimmed)
This is easier but wastes compute if the stop‐string appears early.
🎉 With the stopping‐criteria approach you get an early stop as soon as the model “spits out” your sentinel.