text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
class MaxLengthCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep
in mind for decoder-only type of transformers, this will include the initial prompted tokens.
Args:
max_length (`int`):
Th... | 10,714 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
cur_len = input_ids.shape[-1]
is_done = cur_len >= self.max_length
if self.max_position_embeddings is not None and not is_done a... | 10,714 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class MaxTimeCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the
time will start being counted when you initialize this function. You can override this by passing an
`initial_time`.
Args:
max_tim... | 10,715 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
is_done = time.time() - self.initial_timestamp > self.max_time
return torch.full((input_ids.shape[0],), is_done, device=input_ids.device... | 10,715 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class StopStringCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever specific string sequences are generated. It preprocesses
the strings together with the tokenizer vocab to find positions where tokens can validly complete the stop strings.
Generation is stopped as soon a... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
- ["stop", "at"]
- ["st", "op", "at"]
- ["st", "opera", "tion"]
The reason these are not a match is that the stop string does not overlap with the final token. If you can remove
one or more tokens from the end of the sequence without destroying the stop string, then this criterion will not
match th... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
How is the match actually performed, though? We do it in quite a confusing way, because we want the entire match
process to be compilable with Torch or XLA, which means we cannot use standard string methods. However, it is possible,
with some work, to do string matching with pure tensor operations. We'll begin ... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
- ["st", "op"] (overlap is "op", overlap length == 2)
- ["stop"] (overlap is "stop", overlap length == 4)
- ["st", "opera"] (overlap is "op", overlap length == 2)
- ["sto", "pper"] (overlap is "p", overlap length == 1)
- ["las", "topper"] (overlap is "top", overlap length == 3)
- ["s", "to", "pp... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
How do we do that? Let's use ["s", "to", "pped"] as an example. We know that the final token, "pped", has an
overlap of 1 with the stop string, "stop". We then go back to the previous token, "to". Since we have already
matched 1 character from the stop string, the remainder to check is "sto". We check that the ... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
How does it work when the tokens run off the start of the stop string, though? Let's consider the example of
["las", "topper"]. The final token, "topper", has an overlap of 3 with the stop string, "stop". Therefore,
the remaining stop string to match is "s". We go back to the previous token, "las". Because the ... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
For example, for the token "pped", we would compute an end overlap of 1, no internal matching positions,
and a length of 4. For the token "to", we would compute no end overlap, a single internal matching position
of 1 (counting from the end), and a length of 2. For the token "s", we would compute no end overlap... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
Again, consider ["s", "to", "pped"] as an example. "pped" has an end overlap of 1, so we can begin a match.
We have matched 1 character so far, so we check that the next token "to", has 1 as a valid position (again,
counting from the end). It does, so we add the length of "to" to our position tracker. We have n... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
In the second case, ["las", "topper"], "topper" has an end overlap of 3, so we can begin a match. We have
matched 3 characters so far, so we check that the next token "las" has 3 as a valid position. It does, because we
allow tokens to match positions that run off the start of the stop string. We add its length... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2")
>>> model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2")
>>> inputs = tokenizer("The biggest states in the USA by land area:", return_tensors="pt")
>>> gen_out = model.generate(**inputs)
>>> print(tokenizer.batch_decode(gen_out... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
def __init__(self, tokenizer: PreTrainedTokenizerBase, stop_strings: Union[str, List[str]]):
if isinstance(stop_strings, str):
stop_strings = [stop_strings]
self.stop_strings: Tuple[str, ...] = tuple(stop_strings)
vocab = tokenizer.get_vocab()
token_list, token_indices = tupl... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
def clean_and_embed_tokens_with_cache(self, token_list, token_indices, stop_strings, tokenizer):
# We don't use the tokenizer in the cache key, because I don't trust it to have well-behaved equality
if (token_list, token_indices, stop_strings) in STOP_STRING_EMBEDDING_CACHE:
embedding_vec, m... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
max_valid_end_lens,
)
if len(STOP_STRING_EMBEDDING_CACHE) > 8:
STOP_STRING_EMBEDDING_CACHE.popitem(last=False) # Pop from the start, the least recently used item
return embedding_vec, max_valid_positions, max_valid_end_lens | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
@staticmethod
def clean_tokenizer_vocab(tokenizer, static_prefix="abcdef"):
"""
This method turns a tokenizer vocab into a "clean" vocab where each token represents the actual string
it will yield, without any special prefixes like "##" or "Ġ". This is trickier than it looks - the method
... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
token_string = tokenizer.convert_tokens_to_string(tokens_base + [token])
token_string = token_string[token_string.index(static_prefix) + len(static_prefix) :]
clean_token_list.append(token_string)
clean_token_indices.append(token_idx)
return tuple(clean_token_list), tuple(cle... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
@staticmethod
def _stop_string_get_matching_positions(
token_list, token_indices, stop_strings
) -> Tuple[Dict[str, Dict[str, List[int]]], Dict[str, Dict[str, List[int]]]]:
"""This function preprocesses stop strings and the tokenizer vocabulary to determine where tokens can
validly appea... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
token_valid_positions = {}
token_end_overlaps = {}
for stop_string in stop_strings:
reversed_stop_string = stop_string[::-1]
token_valid_positions[stop_string] = {}
token_end_overlaps[stop_string] = {}
for token, tok_idx in zip(token_list, token_indices):
... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
if matching_positions:
token_valid_positions[stop_string][tok_idx] = matching_positions
if possible_end_lengths:
token_end_overlaps[stop_string][tok_idx] = possible_end_lengths
return token_valid_positions, token_end_overlaps | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
@staticmethod
def _stop_string_create_embedding_vec(token_list, token_indices, stop_strings) -> Dict[str, torch.tensor]:
"""This function precomputes everything needed for the run-time checks in StopStringCriteria, and packs
them into an embedding tensor that can be accessed with pure tensor operati... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
# There should always be at least one valid end_len, however, so no fallback needed here
valid_end_lens = [len(val) for positions in token_end_overlaps.values() for val in positions.values()]
if not valid_end_lens:
raise ValueError(
"Stop string preprocessing was unable to id... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
for i, stop_string in enumerate(stop_strings):
positions = token_valid_positions[stop_string]
end_lens = token_end_overlaps[stop_string] | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
# Since this is lots of very small assignments of lists, we build it with numpy rather
# than torch for speed + simplicity, then convert to torch at the end
for token_idx, valid_positions in positions.items():
gather_vec[token_idx, max_valid_positions * i : max_valid_positions * ... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
return gather_vec, max_valid_positions, max_valid_end_lens
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.Tensor:
self.embedding_vec = self.embedding_vec.to(input_ids.device)
self.target_len... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
# The embedding vec contains the valid positions, end_lengths and total lengths for each token
embedded = F.embedding(flipped_ids, self.embedding_vec)
# Now we split the embedding vector. valid_positions is the positions in the stop string the token can fit
valid_positions = embedded[:, 1:, : m... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
# Concatenate lengths onto each possible end_lengths value
lengths = lengths.expand((-1, -1, end_lengths.shape[-2], end_lengths.shape[-1]))
lengths_with_ends = torch.cat([end_lengths, lengths], dim=1)
# cumsum() to get the number of matched characters in the stop string after each token
... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
# The match vector is a boolean vector that indicates which positions have valid tokens
match = torch.cat([initial_match, later_match], dim=1)
# Once a single position does not match, all positions following that position are masked
mask = (~match).cumsum(dim=1, dtype=torch.int32)
mask ... | 10,716 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class EosTokenCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever the "end-of-sequence" token is generated.
By default, it uses the `model.generation_config.eos_token_id`.
Args:
eos_token_id (`Union[int, List[int], torch.Tensor]`):
The id(s) of the *en... | 10,717 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class ConfidenceCriteria(StoppingCriteria):
"""
This class can be used to stop generation whenever assistant model's confidence in its prediction for the current token is lower than the threshold
`model.generation_config.assistant_confidence_threshold` even if the number of speculative tokens (defined b... | 10,718 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class StoppingCriteriaList(list):
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
is_done = torch.full((input_ids.shape[0],), False, device=input_ids.device, dtype=torch.bool)
for ... | 10,719 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/stopping_criteria.py |
class CandidateGenerator:
"""Abstract base class for all candidate generators that can be applied during assisted generation."""
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
"""
Fetches the candidates to be tried for the current ... | 10,720 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Return:
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
assessed by the model and, optionally, a `torch.FloatTensor` of shape `(batch_size, candidate_length,
vocabulary_size)` containing the logits associated to each candidate.
... | 10,720 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
... | 10,720 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
class AssistedCandidateGenerator(CandidateGenerator):
"""
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
candidates through the use of a smaller model. Read the following blog post for more information:
https://huggingface.co/blog/assisted-ge... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
assistant_model (`PreTrainedModel`):
The model to be used for generating candidates. This model should b... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
inputs_tensor (`torch.Tensor`, *optional*):
The model input tensor. In encoder-decoder models, this is the encoder input.
""" | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def __init__(
self,
input_ids: torch.LongTensor,
assistant_model: "PreTrainedModel",
generation_config: "GenerationConfig",
model_kwargs: Dict,
inputs_tensor: Optional[torch.Tensor] = None,
logits_processor: "LogitsProcessorList" = None,
):
# Make sure... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# Prepare the kwargs for the assistant model
assistant_kwargs = {}
for key, value in model_kwargs.items(): # deepcopy crashes if we attempt to copy encoder outputs with grads
if key not in ("encoder_outputs", "assistant_encoder_outputs", "past_key_values"):
assistant_kwargs[... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if "assistant_encoder_outputs" in model_kwargs:
assistant_kwargs["encoder_outputs"] = model_kwargs["assistant_encoder_outputs"]
elif assistant_model.config.is_encoder_decoder:
inputs_tensor, model_input_name, assistant_kwargs = assistant_model._prepare_model_inputs(
input... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# Prepare assistant model's keys of inputs
if assistant_model.config.is_encoder_decoder:
# both are encoder-decoder
self.input_ids_key = "decoder_input_ids"
elif "encoder_outputs" in assistant_kwargs:
# special case for encoder-decoder with decoder-only assistant (lik... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
self.generation_config.return_dict_in_generate = True
self.generation_config.output_scores = True
self.generation_config.assistant_confidence_threshold = self.assistant_confidence_threshold
# this flag allow us set the confidence stopping criteria for assistant model generation.
self.gen... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# avoid unnecessary warnings that min_length is larger than max_new_tokens
# remove the `MinLengthLogitsProcessor` if exists (NOTE: no need to check for `MinNewTokensLogitsProcessor`)
self.main_model_min_length = self.generation_config.min_length
self.generation_config.min_length = 0
sel... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if (
is_sklearn_available()
and self.assistant_model.generation_config.assistant_confidence_threshold
and type(self) is AssistedCandidateGenerator
):
self.probs = []
self.matches = []
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Return:
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
vocabulary_size)` containing the logits associated to each candidate.
"""
... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
"""
Updates the candidate generation strategy based on the outcomes. | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if self.assistant_model.generation_config.num_assistant_tokens_schedule in {
"heuristic",
"heuristic_transient",
}:
# len(scores[0])-1 is the number of candidates according to the target tokenizer.
if num_matches == len(scores[0]) - 1:
self.num_ass... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes. The costs are estimated based on the ROC curve, which considers the probability of the draft token and its match with the target. A cost of 25% is assigned to fal... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# update self.probs
excess_length = len(self.probs) - len(self.matches)
if excess_length > 0:
del self.probs[-excess_length:]
if (
len(self.probs) > 5 and {0, 1}.issubset(self.matches)
): # require at least 5 samples to calculate the ROC ... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def _calculate_new_tokens(self, input_ids: torch.LongTensor) -> Tuple[int, int]:
"""Calculate the minimum and maximum number of new tokens to generate."""
new_cur_len = input_ids.shape[-1]
max_new_tokens = min(int(self.num_assistant_tokens), self.generation_config.max_length - new_cur_len - 1)
... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def _update_past_and_masks(self, input_ids: torch.LongTensor, remove_from_pkv: int = 0) -> bool:
"""Update past key values and attention masks for subsequent generation rounds."""
has_past_key_values = self.assistant_kwargs.get("past_key_values", None) is not None
if has_past_key_values:
... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def _prepare_generation_args(self, input_ids: torch.LongTensor, min_new_tokens: int, max_new_tokens: int) -> Dict:
"""Prepare arguments for the generation call."""
return {
self.input_ids_key: input_ids,
"min_new_tokens": min_new_tokens,
"max_new_tokens": max_new_toke... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def _generate_candidates(self, generation_args: Dict) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
"""Generate candidate sequences using the assistant model."""
assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs)
self.assistant_kwargs["past_ke... | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
return candidate_ids, candidate_logits | 10,721 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
class AssistedCandidateGeneratorDifferentTokenizers(AssistedCandidateGenerator):
"""
`CandidateGenerator` class to be used for Universal Assisted Generation (UAD): assisted generation with different tokenizers
for the assistant and main models. This class generates candidates through the use of a smaller
... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
assistant_model (`PreTrainedModel`):
The model to be used for generating candidates. This model should b... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
model_kwargs (`Dict`):
The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
model as well.
inputs_tensor (`torch.Tensor`, *optional*):
The model input tensor. In encoder-decoder models, this is the encoder input.
""" | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def __init__(
self,
input_ids: torch.LongTensor,
assistant_model: "PreTrainedModel",
target_tokenizer: "PreTrainedTokenizerBase",
assistant_tokenizer: "PreTrainedTokenizerBase",
generation_config: "GenerationConfig",
model_kwargs: Dict,
inputs_tensor: Opti... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
@staticmethod
def _get_longest_diag_dict(input_matrix, nonzero_idx):
"""
Calculates the length of the longest diagonal sequence in a given matrix.
Args:
input_matrix (torch.Tensor): The input matrix.
nonzero_idx (torch.Tensor): The indices of the non-zero elements in ... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
visited.add(tuple_start_idx)
cur_diag_len = 1
start_idx += 1
while start_idx[0] < input_matrix.shape[0] and start_idx[1] < input_matrix.shape[1]:
tuple_start_idx = tuple(start_idx.tolist())
visited.add(tuple_start_idx)
if input_matrix[... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
diags = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict(
input_matrix, input_matrix.nonzero()
)
diags_values = list(diags.values())
diags_keys = list(diags.keys())
best_diag = np.argmax(diags_values)
diag_start_index = diags_keys[best_diag]
... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
@staticmethod
def _get_tokens_diag(prompt, prompt_plus_new_tokens):
"""
Input:
prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens
prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the orig... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if not compare_mat_int.any().item():
# empty intersection between prompt and prompt_plus_new_tokens
return None, None, None
longest_location, longest_diag_length = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_index(
compare_mat_int
)
new_to... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def convert_source_tokens_to_target_tokens(
self,
input_ids,
source_tokenizer,
destination_tokenizer,
):
"""
Convert token IDs from one tokenizer to another.
Args:
input_ids: The input token IDs.
source_tokenizer: The source tokenizer.
... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
Return:
`torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate s... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
self._update_past_and_masks(assistant_input_ids, remove_from_pkv)
generation_args = self._prepare_generation_args(assistant_input_ids, min_new_tokens, max_new_tokens)
self.assistant_kwargs.pop("attention_mask", None)
assistant_output = self.assistant_model.generate(**generation_args, **self.ass... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def _prepare_assistant_input_ids(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, int]:
"""Converts target input IDs to assistant input IDs, handling discrepancies."""
convert_kwargs = {
"source_tokenizer": self.target_tokenizer,
"destination_tokenizer": self.assista... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
discrepancy_length, new_tokens_only, discrepancy_only = self._get_tokens_diag(
prompt_use, new_assistant_ids
)
assistant_input_ids = self.prev_assistant_ids
if new_tokens_only is not None:
if discrepancy_length > 0 and discrepancy_only.shape[1] > 0:
... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if new_tokens_only.shape[1] > 0:
assistant_input_ids = torch.cat([assistant_input_ids, new_tokens_only], dim=-1)
else:
# edge case: in case of no intersection between prompt and new_assistant_ids
assistant_input_ids = torch.cat([assistant_input_ids, new_as... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
new_target_ids_from_window = self.convert_source_tokens_to_target_tokens(
assistant_sequences[:, start_assistant_look_index:],
source_tokenizer=self.assistant_tokenizer,
destination_tokenizer=self.target_tokenizer,
)
target_prompt_use_length = new_target_ids_from_wind... | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
if hasattr(self.generation_config, "max_length"):
new_target_ids = new_target_ids[:, : self.generation_config.max_length]
return new_target_ids | 10,722 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
class PromptLookupCandidateGenerator(CandidateGenerator):
"""
`CandidateGenerator` class to be used for prompt lookup generation. This class generates candidates by looking up
likely continuations in the provided prompt (input_ids) itself.
Read the following blog post for more information: https://githu... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def __init__(
self,
eos_token_id: torch.Tensor = None,
num_output_tokens: int = 10,
max_matching_ngram_size: int = None,
max_length: int = 20,
):
self.num_output_tokens = num_output_tokens
self.max_matching_ngram_size = max_matching_ngram_size if max_matching_... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Return:
`torch.LongTensor` of shape `(num_candidates, candidate_length)`: The candidate sequences to be tried.
"""
input_length = input_ids.size(1)
# Don't generate more than `max_length - 1` candidates since the target model generates one extra token.
if self.max_length == ... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# Iterate through match indices to find a valid continuation
for idx in match_indices:
start_idx = idx + ngram_size
end_idx = start_idx + self.num_output_tokens
end_idx = min(end_idx, input_length, self.max_length)
if start_idx < end_idx:
... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# remove remaining candidate ids if an "eos" token is found, otherwise the target model may
# accept eos and the rest as valid, thus not stopping generation after "eos"
# NOTE: below code is written based on the fact that assisted decoding supports only bs=1
m... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
# Now need extend input_ids with chosen_ids
chosen_ids = chosen_ids.unsqueeze(0)
candidate_input_ids = torch.cat((input_ids, chosen_ids), dim=1)
# assisted_generation expects logits as well, but we don't have those here, so returning None
return candidate_input_ids, None
def update_... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
... | 10,723 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
class EarlyExitCandidateGenerator(AssistedCandidateGenerator):
"""
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
candidates through the use of **the model itself**, exiting early. Can only be used with models that support early
exit, e.g., `... | 10,724 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
assistant_model (`PreTrainedModel`):
The original model. This model must support early exit (i.e. is tra... | 10,724 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
inputs_tensor (`torch.Tensor`, *optional*):
The model input tensor. In encoder-decoder models, this is the encoder input.
""" | 10,724 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def __init__(
self,
input_ids: torch.LongTensor,
assistant_model: "PreTrainedModel",
generation_config: "GenerationConfig",
model_kwargs: Dict,
inputs_tensor: Optional[torch.Tensor] = None,
logits_processor: "LogitsProcessorList" = None,
):
super().__i... | 10,724 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
# Temporarily sets the number of hidden layers to the early exit value
base_model = getattr(self.assistant_model, self.assistant_model.base_model_prefix)
original_num_hidden_layers = ba... | 10,724 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/candidate_generator.py |
class WatermarkDetectorOutput:
"""
Outputs of a watermark detector. | 10,725 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
Args:
num_tokens_scored (np.array of shape (batch_size)):
Array containing the number of tokens scored for each element in the batch.
num_green_tokens (np.array of shape (batch_size)):
Array containing the number of green tokens for each element in the batch.
green_fracti... | 10,725 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
Array containing boolean predictions whether a text is machine-generated for each element in the batch.
confidence (np.array of shape (batch_size)), *optional*:
Array containing confidence scores of a text being machine-generated for each element in the batch.
""" | 10,725 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
num_tokens_scored: np.array = None
num_green_tokens: np.array = None
green_fraction: np.array = None
z_score: np.array = None
p_value: np.array = None
prediction: Optional[np.array] = None
confidence: Optional[np.array] = None | 10,725 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
class WatermarkDetector:
r"""
Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
the correct device that was used duri... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
Args:
model_config (`PretrainedConfig`):
The model config that will be used to get model specific arguments used when generating.
device (`str`):
The device which was used during watermarked text generation.
watermarking_config (Union[`WatermarkingConfig`, `Dict`]):
... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
>>> model_id = "openai-community/gpt2"
>>> model = AutoModelForCausalLM.from_pretrained(model_id)
>>> tok = AutoTokenizer.from_pretrained(model_id)
>>> tok.pad_token_id = tok.eos_token_id
>>> tok.padding_side = "left"
>>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], ... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
>>> # now we can instantiate the detector and check the generated text
>>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
>>> detection_out_watermarked = detector(out_watermarked, return_dict=True)
>>> detection_out = detector(out, return_dict=... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
self.bos_token_id = (
model_config.bos_token_id if not model_config.is_encoder_decoder else model_config.decoder_start_token_id
)
self.greenlist_ratio = watermarking_config["greenlist_ratio"]
self.ignore_repeated_ngrams = ignore_repeated_ngrams
self.processor = WatermarkLogit... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
def _score_ngrams_in_passage(self, input_ids: torch.LongTensor):
batch_size, seq_length = input_ids.shape
selfhash = int(self.processor.seeding_scheme == "selfhash")
n = self.processor.context_width + 1 - selfhash
indices = torch.arange(n).unsqueeze(0) + torch.arange(seq_length - n + 1).... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
if self.ignore_repeated_ngrams:
# counts a green/red hit once per unique ngram.
# num total tokens scored becomes the number unique ngrams.
num_tokens_scored_batch[batch_idx] = len(frequencies_table.keys())
green_token_count_batch[batch_idx] = sum(ngram_to... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
def _compute_z_score(self, green_token_count: np.array, total_num_tokens: np.array) -> np.array:
expected_count = self.greenlist_ratio
numer = green_token_count - expected_count * total_num_tokens
denom = np.sqrt(total_num_tokens * expected_count * (1 - expected_count))
z = numer / denom... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
def __call__(
self,
input_ids: torch.LongTensor,
z_threshold: float = 3.0,
return_dict: bool = False,
) -> Union[WatermarkDetectorOutput, np.array]:
"""
Args:
input_ids (`torch.LongTensor`):
The watermark generated text. It ... | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
if `return_dict=True` otherwise a `np.array`. | 10,726 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/generation/watermarking.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.