tf_logits_process.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import inspect
  16. from typing import List, Tuple
  17. import numpy as np
  18. import tensorflow as tf
  19. from ..tf_utils import stable_softmax
  20. from ..utils import add_start_docstrings
  21. from ..utils.logging import get_logger
  22. logger = get_logger(__name__)
  23. TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
  24. Args:
  25. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  26. Indices of input sequence tokens in the vocabulary.
  27. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  28. [`PreTrainedTokenizer.__call__`] for details.
  29. [What are input IDs?](../glossary#input-ids)
  30. scores (`tf.Tensor` of shape `(batch_size, config.vocab_size)`):
  31. Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
  32. search or log softmax for each vocabulary token when using beam search.
  33. cur_len (`int`):
  34. The current length of valid input sequence tokens. In the TF implementation, the input_ids' sequence length
  35. is the maximum length generate can produce, and we need to know which of its tokens are valid.
  36. kwargs (`Dict[str, Any]`, *optional*):
  37. Additional logits processor specific kwargs.
  38. Return:
  39. `tf.Tensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
  40. """
  41. class TFLogitsProcessor:
  42. """Abstract base class for all logit processors that can be applied during generation."""
  43. @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  44. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  45. """TF method for processing logits."""
  46. raise NotImplementedError(
  47. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  48. )
  49. class TFLogitsWarper:
  50. """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
  51. @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  52. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  53. """TF method for warping logits."""
  54. raise NotImplementedError(
  55. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  56. )
  57. class TFLogitsProcessorList(list):
  58. """
  59. This class can be used to create a list of [`TFLogitsProcessor`] to subsequently process a `scores` input tensor.
  60. This class inherits from list and adds a specific *__call__* method to apply each [`TFLogitsProcessor`] to the
  61. inputs.
  62. """
  63. @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  64. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int, **kwargs) -> tf.Tensor:
  65. for processor in self:
  66. function_args = inspect.signature(processor.__call__).parameters
  67. if len(function_args) > 3:
  68. if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
  69. raise ValueError(
  70. f"Make sure that all the required parameters: {list(function_args.keys())} for "
  71. f"{processor.__class__} are passed to the logits processor."
  72. )
  73. scores = processor(input_ids, scores, cur_len, **kwargs)
  74. else:
  75. scores = processor(input_ids, scores, cur_len)
  76. return scores
  77. class TFTemperatureLogitsWarper(TFLogitsWarper):
  78. r"""
  79. [`TFLogitsWarper`] for temperature (exponential scaling output probability distribution).
  80. Args:
  81. temperature (`float`):
  82. The value used to module the logits distribution.
  83. """
  84. def __init__(self, temperature: float):
  85. if not isinstance(temperature, float) or not (temperature > 0):
  86. raise ValueError(f"`temperature` has to be a strictly positive float, but is {temperature}")
  87. self.temperature = temperature
  88. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  89. scores = scores / self.temperature
  90. return scores
  91. class TFTopKLogitsWarper(TFLogitsWarper):
  92. r"""
  93. [`TFLogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.
  94. Args:
  95. top_k (`int`):
  96. The number of highest probability vocabulary tokens to keep for top-k-filtering.
  97. filter_value (`float`, *optional*, defaults to -inf):
  98. All filtered values will be set to this float value.
  99. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  100. Minimum number of tokens that cannot be filtered.
  101. """
  102. def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  103. if not isinstance(top_k, int) or top_k <= 0:
  104. raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
  105. self.top_k = max(top_k, min_tokens_to_keep)
  106. self.filter_value = filter_value
  107. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  108. top_k = min(self.top_k, scores.shape[-1]) # Safety check
  109. # Boolean mask containing all tokens with a probability less than the last token of the top-k
  110. indices_to_remove = scores < tf.math.top_k(scores, k=top_k)[0][..., -1:]
  111. next_scores = tf.where(indices_to_remove, self.filter_value, scores)
  112. return next_scores
  113. class TFTopPLogitsWarper(TFLogitsWarper):
  114. """
  115. [`TFLogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.
  116. Args:
  117. top_p (`float`):
  118. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
  119. higher are kept for generation.
  120. filter_value (`float`, *optional*, defaults to -inf):
  121. All filtered values will be set to this float value.
  122. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  123. Minimum number of tokens that cannot be filtered.
  124. """
  125. def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  126. if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
  127. raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
  128. if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
  129. raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
  130. self.top_p = top_p
  131. self.filter_value = filter_value
  132. self.min_tokens_to_keep = min_tokens_to_keep
  133. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  134. topk_scores, topk_indices = tf.math.top_k(scores, scores.shape[-1])
  135. mask_scores = tf.fill(scores.shape, self.filter_value)
  136. cumulative_probs = tf.math.cumsum(stable_softmax(topk_scores, axis=-1), axis=-1)
  137. score_mask = cumulative_probs < self.top_p
  138. # Also include the token that is higher than top_p (the first false = shift and insert a True on the left)
  139. score_mask = tf.concat((tf.ones([score_mask.shape[0], 1], dtype=tf.bool), score_mask[:, :-1]), axis=-1)
  140. # Ensure min tokens to keep
  141. score_mask = tf.concat(
  142. (
  143. tf.ones([score_mask.shape[0], self.min_tokens_to_keep], dtype=tf.bool),
  144. score_mask[:, self.min_tokens_to_keep :],
  145. ),
  146. axis=-1,
  147. )
  148. # Mask the values that do not fit the criteria
  149. topk_next_scores = tf.where(score_mask, topk_scores, mask_scores)
  150. # Undo the topk sorting: converts the 2D matrix of per-row original indices of shape (batch_size, vocab_size)
  151. # to a 3D tensor of shape (batch_size, vocab_size, 2) containing the original score coordinate, from which we
  152. # can scatter (i.e. `scatter_indices[row, col, :]` is a tensor containing `[row, topk_indices[row, col]]`)
  153. scatter_rows = tf.tile(tf.expand_dims(tf.range(topk_indices.shape[0]), axis=-1), [1, topk_indices.shape[-1]])
  154. scatter_indices = tf.stack((scatter_rows, topk_indices), axis=-1)
  155. next_scores = tf.scatter_nd(scatter_indices, topk_next_scores, shape=topk_next_scores.shape)
  156. return next_scores
  157. class TFMinLengthLogitsProcessor(TFLogitsProcessor):
  158. r"""
  159. [`TFLogitsProcessor`] enforcing a min-length by setting EOS probability to 0.
  160. Args:
  161. min_length (`int`):
  162. The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
  163. eos_token_id (`int`):
  164. The id of the *end-of-sequence* token.
  165. """
  166. def __init__(self, min_length: int, eos_token_id: int):
  167. if not isinstance(min_length, int) or min_length < 0:
  168. raise ValueError(f"`min_length` has to be a positive integer, but is {min_length}")
  169. if not isinstance(eos_token_id, int) or eos_token_id < 0:
  170. raise ValueError(f"`eos_token_id` has to be a positive integer, but is {eos_token_id}")
  171. self.min_length = min_length
  172. self.eos_token_id = eos_token_id
  173. def _apply_eos_token_mask(self, scores: tf.Tensor) -> tf.Tensor:
  174. eos_token_id_mask = tf.range(scores.shape[-1]) == self.eos_token_id
  175. scores = tf.where(eos_token_id_mask, float("-inf"), scores)
  176. return scores
  177. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  178. # applies eos token masking if the first argument is true
  179. scores = tf.cond(
  180. tf.less(cur_len, self.min_length),
  181. lambda: self._apply_eos_token_mask(scores),
  182. lambda: tf.identity(scores),
  183. )
  184. return scores
  185. class TFRepetitionPenaltyLogitsProcessor(TFLogitsProcessor):
  186. r"""
  187. [`TFLogitsProcessor`] enforcing an exponential penalty on repeated sequences.
  188. Args:
  189. repetition_penalty (`float`):
  190. The parameter for repetition penalty. 1.0 means no penalty. See [this
  191. paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
  192. """
  193. def __init__(self, penalty: float):
  194. if not isinstance(penalty, float) or not (penalty > 0):
  195. raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
  196. self.penalty = penalty
  197. def _create_score_penalties(self, input_ids: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
  198. # We want to populate the penalties in the positions of `input_ids`. Since XLA can't handle shapes unknown
  199. # before runtime, `tf.unique` can't be used. Therefore, we may have redundant updates, when a given row has
  200. # the same token multiple times.
  201. # Gathers the penalties to apply
  202. logit_penalties = tf.gather(logits, input_ids, axis=1, batch_dims=1)
  203. logit_penalties = tf.where(logit_penalties > 0, 1 / self.penalty, logit_penalties)
  204. logit_penalties = tf.where(logit_penalties < 0, self.penalty, logit_penalties)
  205. # Scatters the penalties
  206. token_penalties = tf.ones(logits.shape)
  207. batch_size = input_ids.shape[0]
  208. seq_len = tf.shape(input_ids)[1] # the sequence length has dynamic size, hence the dynamic shape
  209. indexable_prev_input_ids = tf.concat(
  210. (
  211. tf.expand_dims(tf.repeat(tf.range(batch_size), seq_len), axis=-1),
  212. tf.expand_dims(tf.reshape(input_ids, [-1]), axis=-1),
  213. ),
  214. axis=1,
  215. )
  216. token_penalties = tf.tensor_scatter_nd_update(
  217. token_penalties, indices=indexable_prev_input_ids, updates=tf.reshape(logit_penalties, [-1])
  218. )
  219. return token_penalties
  220. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  221. score_penalties = self._create_score_penalties(input_ids[:, :cur_len], scores)
  222. scores = tf.math.multiply(scores, score_penalties)
  223. return scores
  224. class TFNoBadWordsLogitsProcessor(TFLogitsProcessor):
  225. """
  226. [`TFLogitsProcessor`] that enforces that specified sequences will never be sampled.
  227. Args:
  228. bad_words_ids (`List[List[int]]`):
  229. List of list of token ids that are not allowed to be generated. In order to get the tokens of the words
  230. that should not appear in the generated text, make sure to set `add_prefix_space=True` when initializing
  231. the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space`
  232. argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from
  233. `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
  234. eos_token_id (`int`):
  235. The id of the *end-of-sequence* token.
  236. """
  237. def __init__(self, bad_words_ids: List[List[int]], eos_token_id: int):
  238. if not isinstance(bad_words_ids, List) or len(bad_words_ids) == 0:
  239. raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
  240. if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
  241. raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
  242. if any(
  243. any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
  244. for bad_word_ids in bad_words_ids
  245. ):
  246. raise ValueError(
  247. f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
  248. )
  249. # stores the information about bad words in three tensors:
  250. # 1. a rectangular tensor with the forbidden sequences (padded with `-1`), for full data comparisons
  251. self.bad_word_seqs_ids = tf.ragged.constant(bad_words_ids).to_tensor(default_value=-1)
  252. # 2. a tensor with the unpadded length of each forbidden sequence, for quick length comparisons
  253. bad_word_seqs_len = [len(bad_words) for bad_words in bad_words_ids]
  254. if any(word_len == 0 for word_len in bad_word_seqs_len):
  255. raise ValueError(f"Banned words token sequences {bad_words_ids} cannot have an empty list")
  256. self.bad_word_seqs_len = tf.convert_to_tensor(bad_word_seqs_len, dtype=tf.int32)
  257. # 3. a tensor containing the last token for each sequence, for easy access to the tokens that may be banned
  258. self.seq_forbidden_tokens = tf.convert_to_tensor([bad_words[-1] for bad_words in bad_words_ids])
  259. def _calc_row_banned_bad_tokens(self, row_input_ids: tf.Tensor) -> tf.Tensor:
  260. def _tokens_match(bad_word_seq_number):
  261. def _len_one():
  262. # If the bad sequence only has one token, always mask it
  263. return tf.cond(
  264. tf.math.equal(self.bad_word_seqs_len[bad_word_seq_number], 1),
  265. lambda: tf.ones((), dtype=tf.bool),
  266. _len_greater_than_cur_len,
  267. )
  268. def _len_greater_than_cur_len():
  269. # Otherwise, if the bad sequence is longer than the current length they can't ever match
  270. return tf.cond(
  271. tf.math.greater(self.bad_word_seqs_len[bad_word_seq_number], tf.shape(row_input_ids)[0]),
  272. lambda: tf.zeros((), dtype=tf.bool),
  273. _match_found,
  274. )
  275. def _match_found():
  276. # Finaly, runs the actual comparison. Can only be called if the previous comparisons do not yield
  277. # an answer (otherwise we get indexing exceptions)
  278. compare_len = self.bad_word_seqs_len[bad_word_seq_number] - 1
  279. return tf.cond(
  280. tf.math.reduce_all(
  281. tf.math.equal(
  282. row_input_ids[-compare_len:], self.bad_word_seqs_ids[bad_word_seq_number, :compare_len]
  283. )
  284. ),
  285. lambda: tf.ones((), dtype=tf.bool),
  286. lambda: tf.zeros((), dtype=tf.bool),
  287. )
  288. match = _len_one()
  289. return match
  290. # Compares the current row against all bad word sequences, obtaining a mask with the matches.
  291. match_mask = tf.map_fn(_tokens_match, tf.range(self.bad_word_seqs_ids.shape[0]), fn_output_signature=tf.bool)
  292. row_banned_tokens = self.seq_forbidden_tokens[match_mask]
  293. return row_banned_tokens
  294. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  295. # We want to mask some banned tokens, at a score level. Since the banned tokens depend on the previous
  296. # `input_ids`, they may have a different length for each row, and they may even be empty for some rows.
  297. # To remain simple and XLA-compatible, we work on a per-row fashion.
  298. # TODO (Joao): this function might trigger XLA retracing as `cur_len` increases. Fix it if it becomes
  299. # a frequent choke point. (make `cur_len` a tensor?)
  300. def _get_row_updated_score(row_inputs: Tuple[tf.Tensor]) -> tf.Tensor:
  301. row_input_ids, row_score = row_inputs
  302. banned_tokens = self._calc_row_banned_bad_tokens(row_input_ids[:cur_len])
  303. banned_tokens_mask = tf.scatter_nd(
  304. indices=tf.expand_dims(banned_tokens, axis=-1),
  305. updates=tf.ones_like(banned_tokens, dtype=tf.bool),
  306. shape=row_score.shape,
  307. )
  308. row_score = tf.where(banned_tokens_mask, -float("inf"), row_score)
  309. return row_score
  310. scores = tf.map_fn(_get_row_updated_score, (input_ids, scores), fn_output_signature=tf.float32)
  311. return scores
  312. class TFNoRepeatNGramLogitsProcessor(TFLogitsProcessor):
  313. r"""
  314. [`TFLogitsProcessor`] that enforces no repetition of n-grams. See
  315. [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
  316. Args:
  317. ngram_size (`int`):
  318. All ngrams of size `ngram_size` can only occur once.
  319. """
  320. def __init__(self, ngram_size: int):
  321. if not isinstance(ngram_size, int) or ngram_size <= 0:
  322. raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
  323. self.ngram_size = ngram_size
  324. def calc_banned_ngram_tokens(self, input_ids, num_hypos, cur_len):
  325. # Copied from fairseq for no_repeat_ngram in beam_search
  326. if cur_len + 1 < self.ngram_size:
  327. # return no banned tokens if we haven't generated ngram_size tokens yet
  328. return [[] for _ in range(num_hypos)]
  329. generated_ngrams = [{} for _ in range(num_hypos)]
  330. prev_input_ids = input_ids[:, :cur_len]
  331. for idx in range(num_hypos):
  332. gen_tokens = prev_input_ids[idx].numpy().tolist()
  333. generated_ngram = generated_ngrams[idx]
  334. for ngram in zip(*[gen_tokens[i:] for i in range(self.ngram_size)]):
  335. prev_ngram_tuple = tuple(ngram[:-1])
  336. generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
  337. def _get_generated_ngrams(hypo_idx):
  338. # Before decoding the next token, prevent decoding of ngrams that have already appeared
  339. start_idx = cur_len + 1 - self.ngram_size
  340. ngram_idx = tuple(prev_input_ids[hypo_idx, start_idx:cur_len].numpy().tolist())
  341. return generated_ngrams[hypo_idx].get(ngram_idx, [])
  342. banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)]
  343. return banned_tokens
  344. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  345. # TODO (joao): enable XLA on this logits processor. See discussion and attempts in
  346. # https://github.com/huggingface/transformers/pull/16974
  347. if not tf.executing_eagerly():
  348. raise NotImplementedError("TFNoRepeatNGramLogitsProcessor is only implemented for eager execution.")
  349. batch_size, vocab_size = scores.shape
  350. banned_tokens = self.calc_banned_ngram_tokens(input_ids, batch_size, cur_len)
  351. # create banned_tokens boolean mask
  352. banned_tokens_indices_mask = []
  353. for banned_tokens_slice in banned_tokens:
  354. banned_tokens_indices_mask.append(
  355. [True if token in banned_tokens_slice else False for token in range(vocab_size)]
  356. )
  357. scores = tf.where(tf.convert_to_tensor(banned_tokens_indices_mask, dtype=tf.bool), -float("inf"), scores)
  358. return scores
  359. class TFForcedBOSTokenLogitsProcessor(TFLogitsProcessor):
  360. r"""
  361. [`TFLogitsProcessor`] that enforces the specified token as the first generated token.
  362. Args:
  363. bos_token_id (`int`):
  364. The id of the token to force as the first generated token.
  365. """
  366. def __init__(self, bos_token_id: int):
  367. if bos_token_id < 0:
  368. raise ValueError(f"The forced bos token id must be a non-negative integer, got {bos_token_id}")
  369. self.bos_token_id = bos_token_id
  370. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  371. if cur_len == 1:
  372. batch_size, num_tokens = scores.shape
  373. # sets the score to 0 in the bos_token_id column
  374. scores = tf.zeros((batch_size, 1))
  375. # sets the score to -inf everywhere else
  376. if self.bos_token_id > 0:
  377. scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.bos_token_id)), scores), axis=-1)
  378. if self.bos_token_id < (num_tokens - 1):
  379. scores = tf.concat(
  380. (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.bos_token_id))),
  381. axis=-1,
  382. )
  383. return scores
  384. class TFForcedEOSTokenLogitsProcessor(TFLogitsProcessor):
  385. r"""
  386. [`TFLogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
  387. Args:
  388. max_length (`int`):
  389. The maximum length of the sequence to be generated.
  390. eos_token_id (`int`):
  391. The id of the token to force as the last generated token when `max_length` is reached.
  392. """
  393. def __init__(self, max_length: int, eos_token_id: int):
  394. self.max_length = max_length
  395. if eos_token_id < 0:
  396. raise ValueError(f"The forced eos token id must be a non-negative integer, got {eos_token_id}")
  397. self.eos_token_id = eos_token_id
  398. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  399. if cur_len == self.max_length - 1:
  400. batch_size, num_tokens = scores.shape
  401. # sets the score to 0 in the eos_token_id column
  402. scores = tf.zeros((batch_size, 1))
  403. # sets the score to -inf everywhere else
  404. if self.eos_token_id > 0:
  405. scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.eos_token_id)), scores), axis=-1)
  406. if self.eos_token_id < (num_tokens - 1):
  407. scores = tf.concat(
  408. (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.eos_token_id))),
  409. axis=-1,
  410. )
  411. return scores
  412. class TFSuppressTokensAtBeginLogitsProcessor(TFLogitsProcessor):
  413. r"""
  414. [`TFSuppressTokensAtBeginLogitsProcessor`] suppresses a list of tokens as soon as the `generate` function starts
  415. generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` at not
  416. sampled at the begining of the generation.
  417. """
  418. def __init__(self, begin_suppress_tokens, begin_index):
  419. self.begin_suppress_tokens = list(begin_suppress_tokens)
  420. self.begin_index = begin_index
  421. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  422. suppressed_indices = []
  423. for token in self.begin_suppress_tokens:
  424. if token < scores.shape[-1]: # to ensure we don't go beyond the vocab size
  425. suppressed_indices.extend([[i, token] for i in range(scores.shape[0])])
  426. if len(suppressed_indices) > 0:
  427. scores = tf.cond(
  428. tf.equal(cur_len, self.begin_index),
  429. lambda: tf.tensor_scatter_nd_update(
  430. scores,
  431. indices=suppressed_indices,
  432. updates=[-float("inf") for _ in range(scores.shape[0] * len(self.begin_suppress_tokens))],
  433. ),
  434. lambda: scores,
  435. )
  436. return scores
  437. class TFSuppressTokensLogitsProcessor(TFLogitsProcessor):
  438. r"""This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they
  439. are not sampled."""
  440. def __init__(self, suppress_tokens):
  441. self.suppress_tokens = list(suppress_tokens)
  442. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  443. suppressed_indices = []
  444. for token in self.suppress_tokens:
  445. if token < scores.shape[-1]: # to ensure we don't go beyond the vocab size
  446. suppressed_indices.extend([[i, token] for i in range(scores.shape[0])])
  447. if len(suppressed_indices) > 0:
  448. scores = tf.tensor_scatter_nd_update(
  449. scores,
  450. indices=[[i, token] for i in range(scores.shape[0]) for token in self.suppress_tokens],
  451. updates=[-float("inf") for _ in range(scores.shape[0] * len(self.suppress_tokens))],
  452. )
  453. return scores
  454. class TFForceTokensLogitsProcessor(TFLogitsProcessor):
  455. r"""This processor takes a list of pairs of integers which indicates a mapping from generation indices to token
  456. indices that will be forced before sampling. The processor will set their log probs to `0` and all other tokens to
  457. `-inf` so that they are sampled at their corresponding index."""
  458. def __init__(self, force_token_map: List[List[int]]):
  459. force_token_map = dict(force_token_map)
  460. # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
  461. # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
  462. # Indexes without forced tokens will have an negative value.
  463. force_token_array = np.ones((max(force_token_map.keys()) + 1), dtype=np.int32) * -1
  464. for index, token in force_token_map.items():
  465. if token is not None:
  466. force_token_array[index] = token
  467. self.force_token_array = tf.convert_to_tensor(force_token_array, dtype=tf.int32)
  468. def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
  469. def _force_token(generation_idx):
  470. batch_size = scores.shape[0]
  471. current_token = self.force_token_array[generation_idx]
  472. new_scores = tf.zeros_like(scores, dtype=scores.dtype) + tf.constant([scores.dtype.min])
  473. indices = tf.stack((tf.range(batch_size), tf.tile([current_token], [batch_size])), axis=1)
  474. updates = tf.zeros((batch_size,), dtype=scores.dtype)
  475. new_scores = tf.tensor_scatter_nd_update(new_scores, indices, updates)
  476. return new_scores
  477. scores = tf.cond(
  478. tf.greater_equal(cur_len, tf.shape(self.force_token_array)[0]),
  479. # If the current length is geq than the length of force_token_array, the processor does nothing.
  480. lambda: tf.identity(scores),
  481. # Otherwise, it may force a certain token.
  482. lambda: tf.cond(
  483. tf.greater_equal(self.force_token_array[cur_len], 0),
  484. # Only valid (positive) tokens are forced
  485. lambda: _force_token(cur_len),
  486. # Otherwise, the processor does nothing.
  487. lambda: scores,
  488. ),
  489. )
  490. return scores