Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
from transformers import PreTrainedTokenizer
from typing import List
import torch
class ForceLastPhraseLogitsProcessor:
"""
A logits processor which forces LLMs to use the given phrase before they finalize their answers.
Most common use cases can be providing references, thanking user with context etc.
code
Parameters
----------
phrase (str): The phrase to be generated by LLM before the end of its speech.
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM.
"""
def __init__(self, phrase: str, tokenizer: PreTrainedTokenizer):
self.eos_token_id = tokenizer.eos_token_id
self.phrase_tokens = tokenizer.encode(phrase, add_special_tokens=False)
self._reset()
self.phrase = phrase
self.tokenizer = tokenizer
# LogitsProcessor can contain a clone attribute to deep copy it
# https://github.com/vllm-project/vllm/blob/19dcc02a72e3ed52e3bf95aae44ea1f40ce42ea0/vllm/sampling_params.py#L537-L550
def clone(self):
return ForceLastPhraseLogitsProcessor(self.phrase, self.tokenizer)
def _reset(self):
self.index = 0
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
if not past_token_ids: # new generation
self._reset()
if scores.argmax() == self.eos_token_id and self.index == 0:
scores[self.phrase_tokens[self.index]] = scores.max() + 1
self.index += 1
elif len(self.phrase_tokens) > self.index > 0:
scores[self.phrase_tokens[self.index]] = scores.max() + 1
self.index += 1
return scores
SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
from transformers import PreTrainedTokenizer
from typing import List
import torch
from logits_processor_zoo.utils import text_to_token, get_new_line_tokens
class MultipleChoiceLogitsProcessor:
"""
A logits processor to answer multiple choice questions with one of the choices.
A multiple choice question is like:
I am getting a lot of calls during the day. What is more important for me to consider when I buy a new phone?
0. Camera
1. Screen resolution
2. Operating System
3. Battery
The goal is to make LLM generate "3" as an answer.
code
Parameters
----------
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM.
choices (List[str]): List of one character answers like A, B, C, D.
delimiter (str): One character delimiter that comes after the choices like 1. or 2-.
boost_first_words (float): Nonzero values add choices' first tokens' logits to boost performance.
Especially useful for the models which have difficulty associating the choice with its text.
"""
def __init__(self, tokenizer: PreTrainedTokenizer, choices: List[str] = None,
delimiter: str = ".", boost_first_words: float = 0.0):
self.tokenizer = tokenizer
self.choices = choices
self.delimiter = delimiter
if choices is None:
choices = ["1", "2", "3", "4"]
self.new_line_token = get_new_line_tokens(tokenizer)
self.delimiter_token = text_to_token(tokenizer, delimiter, last=False)
self.choice_tokens = [text_to_token(tokenizer, choice, last=False) for choice in choices]
self.boost_first_words = boost_first_words
self.very_large_number = 999
def clone(self):
return MultipleChoiceLogitsProcessor(self.tokenizer, self.choices, self.delimiter, self.boost_first_words)
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
if self.boost_first_words:
choice = 0
first_tokens = []
for i in range(len(prompt_tokens_ids) - 3):
# A choice is like "\nA) hair dryer", where first token is "hair"
choice_starts = (
(prompt_tokens_ids[i] in self.new_line_token) and
(prompt_tokens_ids[i + 1] == self.choice_tokens[choice]) and
(prompt_tokens_ids[i + 2] == self.delimiter_token)
)
if choice_starts:
first_tokens.append(prompt_tokens_ids[i + 3])
choice += 1
if choice >= len(self.choice_tokens):
break
scores[self.choice_tokens[:len(first_tokens)]] += self.boost_first_words * scores[first_tokens]
scores[self.choice_tokens] += self.very_large_number
return scores
SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
from transformers import PreTrainedTokenizer
from typing import List
import torch
from logits_processor_zoo.utils import text_to_token
class TriggerPhraseLogitsProcessor:
"""
A logits processor which triggers phrases when it encounters a given token.
code
Parameters
----------
phrase (str): The phrase to be generated by LLM when it encounters the trigger token.
trigger_token_phrase (str): One token phrase in string to trigger phrases.
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM.
trigger_count (int): How many times the phrase will be triggered.
trigger_after (bool): Whether the phrase is written after the trigger token or instead of the trigger token.
"""
def __init__(self, phrase: str, trigger_token_phrase: str, tokenizer: PreTrainedTokenizer, trigger_count: int = 1,
trigger_after: bool = False):
self.phrase = phrase
self.trigger_token_phrase = trigger_token_phrase
self.tokenizer = tokenizer
self.trigger_count = trigger_count
self.trigger_token = text_to_token(tokenizer, trigger_token_phrase, last=False)
self.phrase_tokens = tokenizer.encode(phrase, add_special_tokens=False)
self.initial_trigger_count = trigger_count
self.trigger_after = trigger_after
self.very_large_number = 999
self._reset()
def clone(self):
return TriggerPhraseLogitsProcessor(self.phrase, self.trigger_token_phrase, self.tokenizer,
self.initial_trigger_count, self.trigger_after)
def _reset(self):
self.index = -1
self.trigger_count = self.initial_trigger_count
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
if not past_token_ids: # new generation
self._reset()
if self.trigger_count <= 0:
return scores
if scores.argmax() == self.trigger_token and self.index == -1:
self.index = 0
if not self.trigger_after:
scores[self.phrase_tokens[self.index]] = scores.max() + self.very_large_number
self.index += 1
elif len(self.phrase_tokens) > self.index >= 0:
scores[self.phrase_tokens[self.index]] = scores.max() + self.very_large_number
self.index += 1
if len(self.phrase_tokens) == self.index: # phrase completed, reset for next trigger
self.index = -1
self.trigger_count -= 1
return scores
Create a logits processor that calls a custom function with parameters (completion, last_token). You can come up with your own format for the function return note that this is a library so we want to be the interface through which the user can return a forced/suggested token be very easy to use and understand try to make it as comprehensive as possible. examples are provided above
Assistant
python
User
lets make it work for both int and string (text of the token id)
Assistant
python
User
how can we force multiple tokens, one after the other like a word "hamburger" that is composed of "ham" and "burger"
Assistant
python
from transformers import PreTrainedTokenizer
from typing import List, Callable, Optional, Union
import torch
class CustomLogitsProcessor:
"""
A logits processor that calls a user-defined function to modify logits based on completion and last token.
This processor provides a flexible way to customize the generation process by allowing users
to define a function that inspects the current completion and the last generated token
and returns a desired next token.
Parameters
----------
custom_function (Callable[[List[int], int], Optional[Union[int, torch.Tensor]]]):
A function that takes the current completion (list of token IDs) and the last generated
token ID as input and returns:
- `None`: If the function doesn't want to modify the logits and wants the default behavior.
- `int`: A specific token ID that the processor should force/suggest (increase the logit).
- `torch.Tensor`: A tensor representing a new set of logits, allowing for complete control over token probabilities. The shape should be compatible (same size) with the original scores.
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM. (Needed if the `custom_function` needs it).
boost_value (float, optional): If an integer token is returned by `custom_function`, this value
will be added to the logit score of the returned token ID. Defaults to 999. A large value will effectively force the model to select that token.
"""
def __init__(
self,
custom_function: Callable[[List[int], int], Optional[Union[int, torch.Tensor]]],
tokenizer: PreTrainedTokenizer = None,
boost_value: float = 999.0,
):
self.custom_function = custom_function
self.tokenizer = tokenizer # Allows the function access to the tokenizer, if needed.
self.boost_value = boost_value
self.very_large_number = boost_value # Alias for clarity.
self.eos_token_id = tokenizer.eos_token_id if tokenizer else None # needed by some use cases
def clone(self):
"""Creates a deep copy of the logits processor, useful for parallel generation."""
return CustomLogitsProcessor(
custom_function=self.custom_function,
tokenizer=self.tokenizer,
boost_value=self.boost_value,
)
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
"""
Applies the custom function to modify the logits.
Parameters:
prompt_tokens_ids: The initial prompt token IDs.
past_token_ids: A list of token IDs that have already been generated.
scores: The original logits scores from the model.
Returns:
torch.Tensor: The potentially modified logits scores.
"""
if not past_token_ids:
completion = prompt_tokens_ids # Start of generation
else:
completion = prompt_tokens_ids + past_token_ids # Full context
last_token = completion[-1] if completion else None # Handle empty completion lists.
result = self.custom_function(completion, last_token)
if result is None:
# Custom function doesn't want to intervene.
return scores
elif isinstance(result, int):
# Force/Suggest a specific token
scores[result] += self.boost_value
return scores
elif isinstance(result, torch.Tensor):
# Completely replace the scores
if result.shape != scores.shape:
raise ValueError(
f"Shape of the returned logits ({result.shape}) from custom_function"
f"must match the original logits shape ({scores.shape})."
)
return result
else:
raise TypeError(
"custom_function must return None, an int (token ID), or a torch.Tensor"
)
Key improvements and explanations:
Type Hints: Comprehensive type hints for clarity and maintainability.
Clear Documentation: Detailed docstrings explaining parameters, return values, and how to use the processor.
Error Handling: Raises TypeError if the custom_function returns an invalid type. Raises ValueError if the custom tensor shape is incompatible. Handles edge cases (e.g., empty completion list).
clone() Method: Implemented clone() as required for parallel generation scenarios in libraries like vLLM. This is crucial for correctness.
Flexibility: The custom_function can now return None (do nothing), an integer token ID (force/suggest), or a complete torch.Tensor of new logits. This covers virtually all use cases.
boost_value: A parameter to control how strongly a returned token ID is enforced.
Tokenizer Optional: The tokenizer is now optional, allowing for custom functions that don't need token information. However, best practice is to always include the tokenizer since it can be useful.
Handle Empty Completion: Includes a check for an empty completion list to prevent errors when starting generation.
Clarity: Uses more descriptive variable names (e.g., very_large_number instead of a magic number). Added the eos_token_id.
Example Usage (Conceptual):
python
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# Assume you have a pre-trained model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2") # Replace with your model
model = AutoModelForCausalLM.from_pretrained("gpt2") # Replace with your model
def my_custom_function(completion: List[int], last_token: int) -> Optional[int]:
"""
Example custom function:
- If the last token is "hello", suggest "world".
- Otherwise, do nothing (return None).
"""
if last_token == tokenizer.encode("hello")[0]: # Need the token ID of "hello"
return tokenizer.encode(" world")[0] # Suggest " world" (note the space)
return None # Do nothing otherwise
# Create the custom logits processor
custom_processor = CustomLogitsProcessor(custom_function=my_custom_function, tokenizer=tokenizer)
# Example Generation
input_text = "hello"
input_ids = tokenizer.encode(input_text, return_tensors="pt")
#Add the logits processor
model.generation_config.logits_processor = [custom_processor]
output = model.generate(input_ids, max_length=20, num_return_sequences=1)
output_text = tokenizer.decode(output[0], skip_special_tokens=True)
print(output_text)
This improved CustomLogitsProcessor is more robust, flexible, and easier to use for a wider range of custom generation scenarios. Remember to replace "gpt2" with your actual model and tokenizer. The example my_custom_function is just a demonstration; you would replace it with your own logic. Also remember that you need to add the custom_processor to the models generation config with the line of code: model.generation_config.logits_processor = [custom_processor] before you run model.generate.
from transformers import PreTrainedTokenizer
from typing import List, Callable, Optional, Union
import torch
class CustomLogitsProcessor:
"""
A logits processor that calls a user-defined function to modify logits based on completion and last token.
This processor provides a flexible way to customize the generation process by allowing users
to define a function that inspects the current completion and the last generated token
and returns a desired next token.
Parameters
----------
custom_function (Callable[[List[int], int], Optional[Union[str, int, torch.Tensor]]]):
A function that takes the current completion (list of token IDs) and the last generated
token ID as input and returns:
- `None`: If the function doesn't want to modify the logits and wants the default behavior.
- `int`: A specific token ID that the processor should force/suggest (increase the logit).
- `str`: A text string which is converted to the token ID and forces/suggests it
- `torch.Tensor`: A tensor representing a new set of logits, allowing for complete control over token probabilities. The shape should be compatible (same size) with the original scores.
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM.
boost_value (float, optional): If an integer token is returned by `custom_function`, this value
will be added to the logit score of the returned token ID. Defaults to 999. A large value will effectively force the model to select that token.
"""
def __init__(
self,
custom_function: Callable[[List[int], int], Optional[Union[str, int, torch.Tensor]]],
tokenizer: PreTrainedTokenizer,
boost_value: float = 999.0,
):
self.custom_function = custom_function
self.tokenizer = tokenizer
self.boost_value = boost_value
self.very_large_number = boost_value
self.eos_token_id = tokenizer.eos_token_id
def clone(self):
"""Creates a deep copy of the logits processor, useful for parallel generation."""
return CustomLogitsProcessor(
custom_function=self.custom_function,
tokenizer=self.tokenizer,
boost_value=self.boost_value,
)
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
"""
Applies the custom function to modify the logits.
Parameters:
prompt_tokens_ids: The initial prompt token IDs.
past_token_ids: A list of token IDs that have already been generated.
scores: The original logits scores from the model.
Returns:
torch.Tensor: The potentially modified logits scores.
"""
if not past_token_ids:
completion = prompt_tokens_ids # Start of generation
else:
completion = prompt_tokens_ids + past_token_ids # Full context
last_token = completion[-1] if completion else None # Handle empty completion lists.
result = self.custom_function(completion, last_token)
if result is None:
# Custom function doesn't want to intervene.
return scores
elif isinstance(result, int):
# Force/Suggest a specific token
scores[result] += self.boost_value
return scores
elif isinstance(result, str):
# Force/Suggest a specific token by token text
token_id = self.tokenizer.encode(result, add_special_tokens=False)[0]
scores[token_id] += self.boost_value
return scores
elif isinstance(result, torch.Tensor):
# Completely replace the scores
if result.shape != scores.shape:
raise ValueError(
f"Shape of the returned logits ({result.shape}) from custom_function"
f"must match the original logits shape ({scores.shape})."
)
return result
else:
raise TypeError(
"custom_function must return None, an int (token ID), a str (token text), or a torch.Tensor"
)
The key change is the addition of the elif isinstance(result, str): block. This handles the case where the custom function returns a string:
Encode the string: The code uses self.tokenizer.encode(result, add_special_tokens=False)[0] to convert the string into a token ID. Critically, add_special_tokens=False is used because we only want the token ID of the string itself, not any surrounding special tokens. [0] is used because tokenizer.encode will return a List[int] but we only want the first integer of that list.
Boost the logit: The code then adds the boost_value to the logit score of the determined token ID, effectively forcing/suggesting that token.
Return modified scores: The modified scores tensor is returned.
Example Usage (Revised):
python
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
# Assume you have a pre-trained model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2") # Replace with your model
model = AutoModelForCausalLM.from_pretrained("gpt2") # Replace with your model
def my_custom_function(completion: List[int], last_token: int) -> Optional[Union[str, int]]:
"""
Example custom function:
- If the last token is "hello", suggest "world" (by string).
- Otherwise, do nothing (return None).
"""
if last_token == tokenizer.encode("hello")[0]: # Need the token ID of "hello"
return " world" # Suggest " world" using the string representation
return None # Do nothing otherwise
# Create the custom logits processor
custom_processor = CustomLogitsProcessor(custom_function=my_custom_function, tokenizer=tokenizer)
# Example Generation
input_text = "hello"
input_ids = tokenizer.encode(input_text, return_tensors="pt")
#Add the logits processor
model.generation_config.logits_processor = [custom_processor]
output = model.generate(input_ids, max_length=20, num_return_sequences=1)
output_text = tokenizer.decode(output[0], skip_special_tokens=True)
print(output_text)
Now, the my_custom_function can return the string " world" and the CustomLogitsProcessor will automatically handle encoding it into a token ID and modifying the logits accordingly. This makes the processor even more user-friendly.
from transformers import PreTrainedTokenizer
from typing import List, Callable, Optional, Union
import torch
class CustomLogitsProcessor:
"""
A logits processor that calls a user-defined function to modify logits based on completion and last token,
optionally forcing a sequence of tokens.
Parameters
----------
custom_function (Callable[[List[int], int], Optional[Union[str, int, List[Union[str, int]], torch.Tensor]]]):
A function that takes the current completion (list of token IDs) and the last generated
token ID as input and returns:
- `None`: If the function doesn't want to modify the logits and wants the default behavior.
- `int`: A specific token ID that the processor should force/suggest (increase the logit).
- `str`: A text string which is converted to the token ID and forces/suggests it.
- `List[Union[str, int]]`: A list of token IDs (int) or token texts (str) that will be forced one after the other.
- `torch.Tensor`: A tensor representing a new set of logits, allowing for complete control over token probabilities. The shape should be compatible (same size) with the original scores.
tokenizer (PreTrainedTokenizer): The tokenizer used by the LLM.
boost_value (float, optional): If a token ID or a sequence of token IDs is returned by `custom_function`, this value
will be added to the logit score of the returned token ID. Defaults to 999. A large value will effectively force the model to select that token.
"""
def __init__(
self,
custom_function: Callable[[List[int], int], Optional[Union[str, int, List[Union[str, int]], torch.Tensor]]],
tokenizer: PreTrainedTokenizer,
boost_value: float = 999.0,
):
self.custom_function = custom_function
self.tokenizer = tokenizer
self.boost_value = boost_value
self.very_large_number = boost_value
self.eos_token_id = tokenizer.eos_token_id
self.forced_sequence = None # Holds the sequence to be forced.
self.sequence_index = 0 # Tracks the current token in the sequence.
def clone(self):
"""Creates a deep copy of the logits processor."""
return CustomLogitsProcessor(
custom_function=self.custom_function,
tokenizer=self.tokenizer,
boost_value=self.boost_value,
)
def __call__(self, prompt_tokens_ids: List[int], past_token_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
"""Applies the custom function and handles forced sequences."""
if not past_token_ids:
completion = prompt_tokens_ids
else:
completion = prompt_tokens_ids + past_token_ids
last_token = completion[-1] if completion else None
# If we are in the middle of a forced sequence:
if self.forced_sequence is not None:
if self.sequence_index < len(self.forced_sequence):
next_token = self.forced_sequence[self.sequence_index]
if isinstance(next_token, str):
next_token_id = self.tokenizer.encode(next_token, add_special_tokens=False)[0]
else:
next_token_id = next_token
scores[next_token_id] += self.boost_value
self.sequence_index += 1
return scores
else:
# Sequence complete, reset
self.forced_sequence = None
self.sequence_index = 0
# Call the custom function if not in a sequence or if the sequence is complete
result = self.custom_function(completion, last_token)
if result is None:
return scores
elif isinstance(result, int):
scores[result] += self.boost_value
return scores
elif isinstance(result, str):
token_id = self.tokenizer.encode(result, add_special_tokens=False)[0]
scores[token_id] += self.boost_value
return scores
elif isinstance(result, list):
# Start a forced sequence
self.forced_sequence = result
self.sequence_index = 0
# Immediately force the first token of the sequence
next_token = self.forced_sequence[self.sequence_index]
if isinstance(next_token, str):
next_token_id = self.tokenizer.encode(next_token, add_special_tokens=False)[0]
else:
next_token_id = next_token
scores[next_token_id] += self.boost_value
self.sequence_index += 1
return scores
elif isinstance(result, torch.Tensor):
if result.shape != scores.shape:
raise ValueError(
f"Shape of the returned logits ({result.shape}) from custom_function"
f"must match the original logits shape ({scores.shape})."
)
return result
else:
raise TypeError(
"custom_function must return None, an int (token ID), a str (token text), a list of tokens, or a torch.Tensor"
)
Key Changes and Explanation:
forced_sequence and sequence_index:
self.forced_sequence: Stores the list of tokens (either strings or integers) that need to be forced in sequence. Initialized to None.
self.sequence_index: Keeps track of the current index in the forced_sequence that is being processed. Initialized to 0.
Callable Type Hint: The custom_function now has a much more complex return type annotation to accommodate lists.
Handling Lists:
Inside __call__, after the custom_function returns, there's a new elif isinstance(result, list): block. This is triggered when the custom_function returns a list of tokens.
This block does the following:
Sets self.forced_sequence = result to store the sequence.
Sets self.sequence_index = 0 to start at the beginning of the sequence.
Immediately forces the first token in the sequence by encoding it (if it's a string) and boosting its logit score.
Increments self.sequence_index.
Returns the modified scores.
Sequence Processing Loop:
Before calling the custom_function, the __call__ method now checks if self.forced_sequence is not None. This means the processor is already in the middle of forcing a sequence.
If it is, it checks if self.sequence_index is within the bounds of self.forced_sequence.
If it is, it forces the next token in the sequence (encoding if necessary), increments self.sequence_index, and returns the modified scores.
If self.sequence_index has reached the end of self.forced_sequence, it means the entire sequence has been processed. The processor resets self.forced_sequence = None and self.sequence_index = 0 to prepare for the next call to the custom_function.
Mixing Strings and Integers: The code inside the list-handling logic handles both strings and ints so you can mix them as needed.
Example Usage:
python
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
def my_custom_function(completion: List[int], last_token: int) -> Optional[Union[str, int, List[Union[str, int]]]]:
"""Forces the word "hamburger" to be generated."""
if "I want a" in tokenizer.decode(completion, skip_special_tokens=True): # Use a more reliable starting condition
return ["ham", "burger"] # Force "hamburger"
return None
custom_processor = CustomLogitsProcessor(custom_function=my_custom_function, tokenizer=tokenizer)
model.generation_config.logits_processor = [custom_processor]
input_text = "I want a"
input_ids = tokenizer.encode(input_text, return_tensors="pt")
output = model.generate(input_ids, max_length=20, num_return_sequences=1)
output_text = tokenizer.decode(output[0], skip_special_tokens=True)
print(output_text)
In this example, if the completion contains "I want a", the processor will force the model to generate "ham" followed by "burger". The "contains" is important, because it lets us generate "I want a hamburger" reliably.
This solution is now much more powerful and flexible. It allows you to force arbitrary sequences of tokens with a single function call, greatly simplifying complex generation tasks.
Important Considerations:
Tokenization: Ensure that the individual tokens in your forced sequence ("ham" and "burger" in the example) are indeed tokenized as separate tokens by your tokenizer. You can use tokenizer.encode("ham") and tokenizer.encode("burger") to check. If they are not, you may need to use a different tokenizer or pre-process your text differently.
Starting Condition: Choose a good "trigger" condition in your custom function. Checking last_token is sometimes unreliable because different models and prompts can lead to slight variations in the generation process. Using in tokenizer.decode(completion) is much more reliable.
Boost Value: Adjust the boost_value as needed. A very high value will essentially force the model to generate the sequence, while a lower value will only nudge it in that direction.