logits_process.py 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team and Google DeepMind.
  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. import math
  17. from typing import Callable, Iterable, List, Optional, Tuple, Union
  18. import numpy as np
  19. import torch
  20. from ..pytorch_utils import isin_mps_friendly
  21. from ..utils import add_start_docstrings
  22. from ..utils.logging import get_logger
  23. logger = get_logger(__name__)
  24. LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
  25. Args:
  26. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  27. Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
  28. scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
  29. Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
  30. search or log softmax for each vocabulary token when using beam search
  31. Return:
  32. `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
  33. """
  34. class LogitsProcessor:
  35. """Abstract base class for all logit processors that can be applied during generation."""
  36. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  37. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  38. raise NotImplementedError(
  39. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  40. )
  41. class LogitsWarper:
  42. """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
  43. def __init__(self):
  44. logger.warning_once(
  45. "`LogitsWarper` is deprecated and will be removed in v4.48. Your class should inherit `LogitsProcessor` "
  46. "instead, which has the same properties and interface."
  47. )
  48. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  49. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  50. raise NotImplementedError(
  51. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  52. )
  53. class LogitsProcessorList(list):
  54. """
  55. This class can be used to create a list of [`LogitsProcessor`] to subsequently process a `scores` input tensor.
  56. This class inherits from list and adds a specific *__call__* method to apply each [`LogitsProcessor`] to the
  57. inputs.
  58. """
  59. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
  60. r"""
  61. Args:
  62. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  63. Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
  64. scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
  65. Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
  66. beam search or log softmax for each vocabulary token when using beam search
  67. kwargs (`Dict[str, Any]`, *optional*):
  68. Additional kwargs that are specific to a logits processor.
  69. Return:
  70. `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
  71. The processed prediction scores.
  72. """
  73. for processor in self:
  74. function_args = inspect.signature(processor.__call__).parameters
  75. if len(function_args) > 2:
  76. if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
  77. raise ValueError(
  78. f"Make sure that all the required parameters: {list(function_args.keys())} for "
  79. f"{processor.__class__} are passed to the logits processor."
  80. )
  81. scores = processor(input_ids, scores, **kwargs)
  82. else:
  83. scores = processor(input_ids, scores)
  84. return scores
  85. class MinLengthLogitsProcessor(LogitsProcessor):
  86. r"""
  87. [`LogitsProcessor`] enforcing a min-length by setting EOS probability to 0. Note that, for decoder-only models
  88. like most LLMs, the length includes the prompt.
  89. Args:
  90. min_length (`int`):
  91. The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
  92. eos_token_id (`Union[int, List[int], torch.Tensor]`):
  93. The id(s) of the *end-of-sequence* token.
  94. device (`str`, *optional*, defaults to `"cpu"`):
  95. The device to allocate the tensors.
  96. Examples:
  97. ```python
  98. >>> from transformers import AutoModelForCausalLM, AutoTokenizer
  99. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  100. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  101. >>> inputs = tokenizer("A number:", return_tensors="pt")
  102. >>> gen_out = model.generate(**inputs)
  103. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  104. A number: one
  105. >>> # setting `min_length` to a value smaller than the uncontrolled output length has no impact
  106. >>> gen_out = model.generate(**inputs, min_length=3)
  107. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  108. A number: one
  109. >>> # setting a larger `min_length` will force the model to generate beyond its natural ending point, which is not
  110. >>> # necessarily incorrect
  111. >>> gen_out = model.generate(**inputs, min_length=10)
  112. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  113. A number: one thousand, nine hundred and ninety-four
  114. ```
  115. """
  116. def __init__(self, min_length: int, eos_token_id: Union[int, List[int], torch.Tensor], device: str = "cpu"):
  117. if not isinstance(min_length, int) or min_length < 0:
  118. raise ValueError(f"`min_length` has to be a non-negative integer, but is {min_length}")
  119. if not isinstance(eos_token_id, torch.Tensor):
  120. if isinstance(eos_token_id, int):
  121. eos_token_id = [eos_token_id]
  122. eos_token_id = torch.tensor(eos_token_id, device=device)
  123. self.min_length = min_length
  124. self.eos_token_id = eos_token_id
  125. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  126. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  127. vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
  128. eos_token_mask = isin_mps_friendly(vocab_tensor, self.eos_token_id)
  129. scores_processed = scores.clone()
  130. if input_ids.shape[-1] < self.min_length:
  131. scores_processed = torch.where(eos_token_mask, -math.inf, scores)
  132. return scores_processed
  133. class MinNewTokensLengthLogitsProcessor(LogitsProcessor):
  134. r"""
  135. [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.
  136. Contrarily to [`MinLengthLogitsProcessor`], this processor ignores the prompt.
  137. Args:
  138. prompt_length_to_skip (`int`):
  139. The input tokens length. Not a valid argument when used with `generate` as it will automatically assign the
  140. input length.
  141. min_new_tokens (`int`):
  142. The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
  143. eos_token_id (`Union[int, List[int], torch.Tensor]`):
  144. The id(s) of the *end-of-sequence* token.
  145. device (`str`, *optional*, defaults to `"cpu"`):
  146. The device to allocate the tensors.
  147. Examples:
  148. ```python
  149. >>> from transformers import AutoModelForCausalLM, AutoTokenizer
  150. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  151. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  152. >>> inputs = tokenizer(["A number:"], return_tensors="pt")
  153. >>> gen_out = model.generate(**inputs)
  154. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  155. A number: one
  156. >>> # setting `min_new_tokens` will force the model to generate beyond its natural ending point, which is not
  157. >>> # necessarily incorrect
  158. >>> gen_out = model.generate(**inputs, min_new_tokens=2)
  159. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  160. A number: one thousand
  161. ```
  162. """
  163. def __init__(
  164. self,
  165. prompt_length_to_skip: int,
  166. min_new_tokens: int,
  167. eos_token_id: Union[int, List[int], torch.Tensor],
  168. device: str = "cpu",
  169. ):
  170. for arg_name, arg_value in [
  171. ("prompt_length_to_skip", prompt_length_to_skip),
  172. ("min_new_tokens", min_new_tokens),
  173. ]:
  174. if not isinstance(arg_value, int) or arg_value < 0:
  175. raise ValueError(f"`{arg_name}` has to be a positive integer, but is {arg_value}")
  176. if not isinstance(eos_token_id, torch.Tensor):
  177. if isinstance(eos_token_id, int):
  178. eos_token_id = [eos_token_id]
  179. eos_token_id = torch.tensor(eos_token_id, device=device)
  180. self.prompt_length_to_skip = prompt_length_to_skip
  181. self.min_new_tokens = min_new_tokens
  182. self.eos_token_id = eos_token_id
  183. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  184. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  185. new_tokens_length = input_ids.shape[-1] - self.prompt_length_to_skip
  186. scores_processed = scores.clone()
  187. vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
  188. eos_token_mask = isin_mps_friendly(vocab_tensor, self.eos_token_id)
  189. if new_tokens_length < self.min_new_tokens:
  190. scores_processed = torch.where(eos_token_mask, -math.inf, scores)
  191. return scores_processed
  192. class TemperatureLogitsWarper(LogitsProcessor):
  193. r"""
  194. [`LogitsProcessor`] for temperature (exponential scaling output probability distribution), which effectively means
  195. that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and
  196. [`TopKLogitsWarper`].
  197. <Tip>
  198. Make sure that `do_sample=True` is included in the `generate` arguments otherwise the temperature value won't have
  199. any effect.
  200. </Tip>
  201. Args:
  202. temperature (`float`):
  203. Strictly positive float value used to modulate the logits distribution. A value smaller than `1` decreases
  204. randomness (and vice versa), with `0` being equivalent to shifting all probability mass to the most likely
  205. token.
  206. Examples:
  207. ```python
  208. >>> import torch
  209. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  210. >>> set_seed(0) # for reproducibility
  211. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  212. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  213. >>> model.config.pad_token_id = model.config.eos_token_id
  214. >>> inputs = tokenizer(["Hugging Face Company is"], return_tensors="pt")
  215. >>> # With temperature=1.0, the default, we consistently get random outputs due to random sampling.
  216. >>> generate_kwargs = {"max_new_tokens": 10, "do_sample": True, "temperature": 1.0, "num_return_sequences": 2}
  217. >>> outputs = model.generate(**inputs, **generate_kwargs)
  218. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
  219. ['Hugging Face Company is one of these companies that is going to take a',
  220. "Hugging Face Company is a brand created by Brian A. O'Neil"]
  221. >>> # However, with temperature close to 0, it approximates greedy decoding strategies (invariant)
  222. >>> generate_kwargs["temperature"] = 0.0001
  223. >>> outputs = model.generate(**inputs, **generate_kwargs)
  224. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
  225. ['Hugging Face Company is a company that has been around for over 20 years',
  226. 'Hugging Face Company is a company that has been around for over 20 years']
  227. ```
  228. """
  229. def __init__(self, temperature: float):
  230. if not isinstance(temperature, float) or not (temperature > 0):
  231. except_msg = (
  232. f"`temperature` (={temperature}) has to be a strictly positive float, otherwise your next token "
  233. "scores will be invalid."
  234. )
  235. if isinstance(temperature, float) and temperature == 0.0:
  236. except_msg += " If you're looking for greedy decoding strategies, set `do_sample=False`."
  237. raise ValueError(except_msg)
  238. self.temperature = temperature
  239. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  240. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  241. scores_processed = scores / self.temperature
  242. return scores_processed
  243. class RepetitionPenaltyLogitsProcessor(LogitsProcessor):
  244. r"""
  245. [`LogitsProcessor`] that prevents the repetition of previous tokens through a penalty. This penalty is applied at
  246. most once per token. Note that, for decoder-only models like most LLMs, the considered tokens include the prompt.
  247. In the original [paper](https://arxiv.org/pdf/1909.05858.pdf), the authors suggest the use of a penalty of around
  248. 1.2 to achieve a good balance between truthful generation and lack of repetition. To penalize and reduce
  249. repetition, use `penalty` values above 1.0, where a higher value penalizes more strongly. To reward and encourage
  250. repetition, use `penalty` values between 0.0 and 1.0, where a lower value rewards more strongly.
  251. Args:
  252. penalty (`float`):
  253. The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 penalizes previously generated
  254. tokens. Between 0.0 and 1.0 rewards previously generated tokens.
  255. Examples:
  256. ```py
  257. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  258. >>> # Initializing the model and tokenizer for it
  259. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  260. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  261. >>> inputs = tokenizer(["I'm not going to"], return_tensors="pt")
  262. >>> # This shows a normal generate without any specific parameters
  263. >>> summary_ids = model.generate(**inputs)
  264. >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
  265. I'm not going to be able to do that. I'm going to be able to do that
  266. >>> # This generates a penalty for repeated tokens
  267. >>> penalized_ids = model.generate(**inputs, repetition_penalty=1.1)
  268. >>> print(tokenizer.batch_decode(penalized_ids, skip_special_tokens=True)[0])
  269. I'm not going to be able to do that. I'll just have to go out and play
  270. ```
  271. """
  272. def __init__(self, penalty: float):
  273. if not isinstance(penalty, float) or not (penalty > 0):
  274. raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
  275. self.penalty = penalty
  276. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  277. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  278. score = torch.gather(scores, 1, input_ids)
  279. # if score < 0 then repetition penalty has to be multiplied to reduce the token probabilities
  280. score = torch.where(score < 0, score * self.penalty, score / self.penalty)
  281. scores_processed = scores.scatter(1, input_ids, score)
  282. return scores_processed
  283. class EncoderRepetitionPenaltyLogitsProcessor(LogitsProcessor):
  284. r"""
  285. [`LogitsProcessor`] that works similarly to [`RepetitionPenaltyLogitsProcessor`], but with an *inverse* penalty
  286. that is applied to the tokens present in the prompt. In other words, a penalty above 1.0 increases the odds of
  287. selecting tokens that were present in the prompt.
  288. It was designed to avoid hallucination in input-grounded tasks, like summarization. Although originally intended
  289. for encoder-decoder models, it can also be used with decoder-only models like LLMs.
  290. Args:
  291. penalty (`float`):
  292. The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 rewards prompt tokens. Between 0.0
  293. and 1.0 penalizes prompt tokens.
  294. encoder_input_ids (`torch.LongTensor`):
  295. The encoder_input_ids that should be repeated within the decoder ids.
  296. Examples:
  297. ```python
  298. >>> from transformers import AutoModelForCausalLM, AutoTokenizer
  299. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  300. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  301. >>> inputs = tokenizer(["Alice and Bob. The third member's name was"], return_tensors="pt")
  302. >>> gen_out = model.generate(**inputs)
  303. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  304. Alice and Bob. The third member's name was not mentioned.
  305. >>> # With the `encoder_repetition_penalty` argument we can trigger this logits processor in `generate`, which can
  306. >>> # promote the use of prompt tokens ("Bob" in this example)
  307. >>> gen_out = model.generate(**inputs, encoder_repetition_penalty=1.2)
  308. >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
  309. Alice and Bob. The third member's name was Bob. The third member's name was Bob.
  310. ```
  311. """
  312. def __init__(self, penalty: float, encoder_input_ids: torch.LongTensor):
  313. if not isinstance(penalty, float) or not (penalty > 0):
  314. raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
  315. self.penalty = 1 / penalty
  316. self.encoder_input_ids = encoder_input_ids
  317. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  318. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  319. score = torch.gather(scores, 1, self.encoder_input_ids)
  320. # if score < 0 then hallucination penalty has to be multiplied to increase the token probabilities
  321. score = torch.where(score < 0, score * self.penalty, score / self.penalty)
  322. scores_processed = scores.scatter(1, self.encoder_input_ids, score)
  323. return scores_processed
  324. class TopPLogitsWarper(LogitsProcessor):
  325. """
  326. [`LogitsProcessor`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
  327. Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].
  328. Args:
  329. top_p (`float`):
  330. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
  331. higher are kept for generation.
  332. filter_value (`float`, *optional*, defaults to -inf):
  333. All filtered values will be set to this float value.
  334. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  335. Minimum number of tokens that cannot be filtered.
  336. Examples:
  337. ```python
  338. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  339. >>> set_seed(1)
  340. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  341. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  342. >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
  343. >>> # With sampling, the output is unexpected -- sometimes too unexpected.
  344. >>> outputs = model.generate(**inputs, do_sample=True)
  345. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  346. A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
  347. <BLANKLINE>
  348. <BLANKLINE>
  349. >>> # With `top_p` sampling, the output gets restricted to high-probability tokens.
  350. >>> # Pro tip: In practice, LLMs use `top_p` in the 0.9-0.95 range.
  351. >>> outputs = model.generate(**inputs, do_sample=True, top_p=0.1)
  352. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  353. A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
  354. ```
  355. """
  356. def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  357. top_p = float(top_p)
  358. if top_p < 0 or top_p > 1.0:
  359. raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
  360. if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
  361. raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
  362. self.top_p = top_p
  363. self.filter_value = filter_value
  364. self.min_tokens_to_keep = min_tokens_to_keep
  365. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  366. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  367. sorted_logits, sorted_indices = torch.sort(scores, descending=False)
  368. cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
  369. # Remove tokens with cumulative top_p above the threshold (token with 0 are kept)
  370. sorted_indices_to_remove = cumulative_probs <= (1 - self.top_p)
  371. # Keep at least min_tokens_to_keep
  372. sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = 0
  373. # scatter sorted tensors to original indexing
  374. indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
  375. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  376. return scores_processed
  377. class TopKLogitsWarper(LogitsProcessor):
  378. r"""
  379. [`LogitsProcessor`] that performs top-k, i.e. restricting to the k highest probability elements. Often used
  380. together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].
  381. Args:
  382. top_k (`int`):
  383. The number of highest probability vocabulary tokens to keep for top-k-filtering.
  384. filter_value (`float`, *optional*, defaults to -inf):
  385. All filtered values will be set to this float value.
  386. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  387. Minimum number of tokens that cannot be filtered.
  388. Examples:
  389. ```python
  390. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  391. >>> set_seed(1)
  392. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  393. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  394. >>> inputs = tokenizer("A sequence: A, B, C, D", return_tensors="pt")
  395. >>> # With sampling, the output is unexpected -- sometimes too unexpected.
  396. >>> outputs = model.generate(**inputs, do_sample=True)
  397. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  398. A sequence: A, B, C, D, E — S — O, P — R
  399. >>> # With `top_k` sampling, the output gets restricted the k most likely tokens.
  400. >>> # Pro tip: In practice, LLMs use `top_k` in the 5-50 range.
  401. >>> outputs = model.generate(**inputs, do_sample=True, top_k=2)
  402. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  403. A sequence: A, B, C, D, E, F, G, H, I
  404. ```
  405. """
  406. def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  407. if not isinstance(top_k, int) or top_k <= 0:
  408. raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
  409. self.top_k = max(top_k, min_tokens_to_keep)
  410. self.filter_value = filter_value
  411. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  412. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  413. top_k = min(self.top_k, scores.size(-1)) # Safety check
  414. # Remove all tokens with a probability less than the last token of the top-k
  415. indices_to_remove = scores < torch.topk(scores, top_k)[0][..., -1, None]
  416. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  417. return scores_processed
  418. class MinPLogitsWarper(LogitsProcessor):
  419. """
  420. [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the
  421. probability of the most likely token. As a result, the filter becomes more agressive in the presence of
  422. high-probability tokens, which is a sign of a confident output that we shouldn't deviate from.
  423. Often used together with [`TemperatureLogitsWarper`]. Used as an alternative to [`TopPLogitsWarper`] and
  424. [`TopKLogitsWarper`].
  425. Created by @menhguin and @kalomaze (github handles). Code adapted from [this external PR](https://github.com/oobabooga/text-generation-webui/pull/4449/files)
  426. Args:
  427. min_p (`float`):
  428. Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
  429. value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in
  430. the 0.99-0.8 range (use the opposite of normal `top_p` values).
  431. filter_value (`float`, *optional*, defaults to -inf):
  432. All filtered values will be set to this float value.
  433. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  434. Minimum number of tokens that cannot be filtered.
  435. Examples:
  436. ```python
  437. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  438. >>> set_seed(1)
  439. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  440. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  441. >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
  442. >>> # With sampling, the output is unexpected -- sometimes too unexpected.
  443. >>> outputs = model.generate(**inputs, do_sample=True)
  444. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  445. A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
  446. <BLANKLINE>
  447. <BLANKLINE>
  448. >>> # With `min_p` sampling, the output gets restricted to high-probability tokens.
  449. >>> # Pro tip: In practice, LLMs use `min_p` in the 0.01-0.2 range.
  450. >>> outputs = model.generate(**inputs, do_sample=True, min_p=0.1)
  451. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  452. A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
  453. ```
  454. """
  455. def __init__(self, min_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  456. if not (0 <= min_p <= 1.0):
  457. raise ValueError(f"`min_p` has to be a float in the [0, 1] interval, but is {min_p}")
  458. if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
  459. raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
  460. self.min_p = min_p
  461. self.filter_value = filter_value
  462. self.min_tokens_to_keep = min_tokens_to_keep
  463. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  464. # Convert logits to probabilities
  465. probs = torch.softmax(scores, dim=-1)
  466. # Get the probability of the top token for each sequence in the batch
  467. top_probs, _ = probs.max(dim=-1, keepdim=True)
  468. # Calculate the actual min_p threshold by scaling min_p with the top token's probability
  469. scaled_min_p = self.min_p * top_probs
  470. # Create a mask for tokens that have a probability less than the scaled min_p
  471. tokens_to_remove = probs < scaled_min_p
  472. sorted_indices = torch.argsort(scores, descending=True, dim=-1)
  473. sorted_indices_to_remove = torch.gather(tokens_to_remove, dim=-1, index=sorted_indices)
  474. # Keep at least min_tokens_to_keep
  475. sorted_indices_to_remove[..., : self.min_tokens_to_keep] = False
  476. indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
  477. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  478. return scores_processed
  479. class TypicalLogitsWarper(LogitsProcessor):
  480. r"""
  481. [`LogitsProcessor`] that performs typical decoding. Inspired on how humans use language, it prioritizes tokens
  482. whose log probability is close to the entropy of the token probability distribution. This means that the most
  483. likely tokens may be discarded in the process.
  484. See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
  485. Args:
  486. mass (`float`, *optional*, defaults to 0.9):
  487. Value of typical_p between 0 and 1 inclusive, defaults to 0.9.
  488. filter_value (`float`, *optional*, defaults to -inf):
  489. All filtered values will be set to this float value.
  490. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  491. Minimum number of tokens that cannot be filtered.
  492. Examples:
  493. ```python
  494. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  495. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  496. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  497. >>> inputs = tokenizer("1, 2, 3", return_tensors="pt")
  498. >>> # We can see that greedy decoding produces a sequence of numbers
  499. >>> outputs = model.generate(**inputs)
  500. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  501. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  502. >>> # For this particular seed, we can see that sampling produces nearly the same low-information (= low entropy)
  503. >>> # sequence
  504. >>> set_seed(18)
  505. >>> outputs = model.generate(**inputs, do_sample=True)
  506. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  507. 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10
  508. >>> # With `typical_p` set, the most obvious sequence is no longer produced, which may be good for your problem
  509. >>> set_seed(18)
  510. >>> outputs = model.generate(
  511. ... **inputs, do_sample=True, typical_p=0.1, return_dict_in_generate=True, output_scores=True
  512. ... )
  513. >>> print(tokenizer.batch_decode(outputs.sequences, skip_special_tokens=True)[0])
  514. 1, 2, 3 and 5
  515. >>> # We can see that the token corresponding to "4" (token 934) in the second position, the most likely token
  516. >>> # as seen with greedy decoding, was entirely blocked out
  517. >>> print(outputs.scores[1][0, 934])
  518. tensor(-inf)
  519. ```
  520. """
  521. def __init__(self, mass: float = 0.9, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  522. mass = float(mass)
  523. if not (mass > 0 and mass < 1):
  524. raise ValueError(f"`typical_p` has to be a float > 0 and < 1, but is {mass}")
  525. if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
  526. raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
  527. self.filter_value = filter_value
  528. self.mass = mass
  529. self.min_tokens_to_keep = min_tokens_to_keep
  530. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  531. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  532. # calculate entropy
  533. normalized = torch.nn.functional.log_softmax(scores, dim=-1)
  534. p = torch.exp(normalized)
  535. ent = -(normalized * p).nansum(-1, keepdim=True)
  536. # shift and sort
  537. shifted_scores = torch.abs((-normalized) - ent)
  538. sorted_scores, sorted_indices = torch.sort(shifted_scores, descending=False)
  539. sorted_logits = scores.gather(-1, sorted_indices)
  540. cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
  541. # Remove tokens with cumulative mass above the threshold
  542. last_ind = (cumulative_probs < self.mass).sum(dim=1)
  543. last_ind.clamp_(max=sorted_scores.shape[-1] - 1)
  544. sorted_indices_to_remove = sorted_scores > sorted_scores.gather(1, last_ind.view(-1, 1))
  545. sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0
  546. indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
  547. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  548. return scores_processed
  549. class EpsilonLogitsWarper(LogitsProcessor):
  550. r"""
  551. [`LogitsProcessor`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
  552. largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
  553. Desmoothing](https://arxiv.org/abs/2210.15191) for more information.
  554. Args:
  555. epsilon (`float`):
  556. If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation.
  557. filter_value (`float`, *optional*, defaults to -inf):
  558. All filtered values will be set to this float value.
  559. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  560. Minimum number of tokens that cannot be filtered.
  561. Examples:
  562. ```python
  563. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  564. >>> set_seed(1)
  565. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  566. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  567. >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
  568. >>> # With sampling, the output is unexpected -- sometimes too unexpected.
  569. >>> outputs = model.generate(**inputs, do_sample=True)
  570. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  571. A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
  572. <BLANKLINE>
  573. <BLANKLINE>
  574. >>> # With epsilon sampling, the output gets restricted to high-probability tokens. Note that this is similar to
  575. >>> # Top P sampling, which restricts tokens based on their cumulative probability.
  576. >>> # Pro tip: The paper recomends using `epsilon_cutoff` values between 3e-4 and 9e-4
  577. >>> outputs = model.generate(**inputs, do_sample=True, epsilon_cutoff=0.1)
  578. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  579. A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
  580. ```
  581. """
  582. def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
  583. epsilon = float(epsilon)
  584. if epsilon <= 0 or epsilon >= 1:
  585. raise ValueError(f"`epsilon_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
  586. min_tokens_to_keep = int(min_tokens_to_keep)
  587. if min_tokens_to_keep < 1:
  588. raise ValueError(
  589. f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
  590. )
  591. self.epsilon = epsilon
  592. self.filter_value = filter_value
  593. self.min_tokens_to_keep = min_tokens_to_keep
  594. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  595. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  596. # Determine which indices to remove
  597. probabilities = scores.softmax(dim=-1)
  598. indices_to_remove = probabilities < self.epsilon
  599. # Keep the words with the 'min_tokens_to_keep'-highest probabilities
  600. top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
  601. indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
  602. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  603. return scores_processed
  604. class EtaLogitsWarper(LogitsProcessor):
  605. r"""
  606. [`LogitsProcessor`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic
  607. cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of
  608. the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest
  609. min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long
  610. samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation
  611. Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Note: `do_sample`
  612. must be set to `True` for this `LogitsProcessor` to work.
  613. Args:
  614. epsilon (`float`):
  615. A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The
  616. suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model.
  617. filter_value (`float`, *optional*, defaults to -inf):
  618. All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This
  619. parameter is useful when logits need to be modified for very low probability tokens that should be excluded
  620. from generation entirely.
  621. min_tokens_to_keep (`int`, *optional*, defaults to 1):
  622. Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities.
  623. For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation,
  624. even if all tokens have probabilities below the cutoff `eta`.
  625. device (`str`, *optional*, defaults to `"cpu"`):
  626. The device to allocate the tensors.
  627. Examples:
  628. ```python
  629. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  630. >>> set_seed(1)
  631. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  632. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  633. >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
  634. >>> # With sampling, the output is unexpected -- sometimes too unexpected.
  635. >>> outputs = model.generate(**inputs, do_sample=True)
  636. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  637. A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
  638. <BLANKLINE>
  639. <BLANKLINE>
  640. >>> # With eta sampling, the output gets restricted to high-probability tokens. You can see it as a dynamic form of
  641. >>> # epsilon sampling that adapts its cutoff probability based on the entropy (high entropy = lower cutoff).
  642. >>> # Pro tip: The paper recomends using `eta_cutoff` values between 3e-4 to 4e-3
  643. >>> outputs = model.generate(**inputs, do_sample=True, eta_cutoff=0.1)
  644. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  645. A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
  646. ```
  647. """
  648. def __init__(
  649. self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1, device: str = "cpu"
  650. ):
  651. epsilon = float(epsilon)
  652. if epsilon <= 0 or epsilon >= 1:
  653. raise ValueError(f"`eta_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
  654. min_tokens_to_keep = int(min_tokens_to_keep)
  655. if min_tokens_to_keep < 1:
  656. raise ValueError(
  657. f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
  658. )
  659. self.epsilon = torch.tensor(epsilon, device=device)
  660. self.filter_value = filter_value
  661. self.min_tokens_to_keep = min_tokens_to_keep
  662. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  663. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  664. probabilities = scores.softmax(dim=-1)
  665. entropy = torch.distributions.Categorical(logits=scores).entropy()
  666. eta = torch.min(self.epsilon, torch.sqrt(self.epsilon) * torch.exp(-entropy))[..., None]
  667. indices_to_remove = probabilities < eta
  668. # Keep the words with the 'min_tokens_to_keep'-highest probabilities
  669. top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
  670. indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
  671. scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
  672. return scores_processed
  673. def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int):
  674. """
  675. Assume ngram_size=2 and prev_input_ids=tensor([[40, 2883, 2712, 4346]]). The output of generated ngrams look like
  676. this {(40,): [2883], (2883,): [2712], (2712,): [4346]}.
  677. Args:
  678. ngram_size (`int`):
  679. The number sequential tokens taken as a group which may only occur once before being banned.
  680. prev_input_ids (`torch.Tensor`):
  681. Generated token ids for the current hypothesis.
  682. num_hypos (`int`):
  683. The number of hypotheses for which n-grams need to be generated.
  684. Returns:
  685. generated_ngrams (`dict`):
  686. Dictionary of generated ngrams.
  687. """
  688. # Initialize an empty list of dictionaries, one for each hypothesis (index) in the range of num_hypos
  689. generated_ngrams = [{} for _ in range(num_hypos)]
  690. for idx in range(num_hypos):
  691. gen_tokens = prev_input_ids[idx].tolist()
  692. generated_ngram = generated_ngrams[idx]
  693. # Loop through each n-gram of size ngram_size in the list of tokens (gen_tokens)
  694. for ngram in zip(*[gen_tokens[i:] for i in range(ngram_size)]):
  695. prev_ngram_tuple = tuple(ngram[:-1])
  696. generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
  697. return generated_ngrams
  698. def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len):
  699. """
  700. Determines the banned tokens for the current hypothesis based on previously generated n-grams.
  701. Args:
  702. banned_ngrams (`dict`):
  703. A dictionary containing previously generated n-grams for each hypothesis.
  704. prev_input_ids (`torch.Tensor`):
  705. Generated token ids for the current hypothesis.
  706. ngram_size (`int`):
  707. The number sequential tokens taken as a group which may only occur once before being banned.
  708. cur_len (`int`):
  709. The current length of the token sequences for which the n-grams are being checked.
  710. Returns:
  711. List of tokens that are banned.
  712. """
  713. # Before decoding the next token, prevent decoding of ngrams that have already appeared
  714. start_idx = cur_len + 1 - ngram_size
  715. ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist())
  716. return banned_ngrams.get(ngram_idx, [])
  717. def _calc_banned_ngram_tokens(
  718. ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int, cur_len: int
  719. ) -> List[Iterable[int]]:
  720. """Copied from fairseq for no_repeat_ngram in beam_search"""
  721. if cur_len + 1 < ngram_size:
  722. # return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
  723. return [[] for _ in range(num_hypos)]
  724. generated_ngrams = _get_ngrams(ngram_size, prev_input_ids, num_hypos)
  725. banned_tokens = [
  726. _get_generated_ngrams(generated_ngrams[hypo_idx], prev_input_ids[hypo_idx], ngram_size, cur_len)
  727. for hypo_idx in range(num_hypos)
  728. ]
  729. return banned_tokens
  730. class NoRepeatNGramLogitsProcessor(LogitsProcessor):
  731. r"""
  732. N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the
  733. sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation,
  734. avoiding repetitions of word sequences provides a more diverse output. This [`LogitsProcessor`] enforces no
  735. repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens
  736. from consideration when further processing the scores. Note that, for decoder-only models like most LLMs, the
  737. prompt is also considered to obtain the n-grams.
  738. [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
  739. <Tip>
  740. Use n-gram penalties with care. For instance, penalizing 2-grams (bigrams) in an article about the city of New York
  741. might lead to undesirable outcomes where the city's name appears only once in the entire text.
  742. [Reference](https://huggingface.co/blog/how-to-generate)
  743. </Tip>
  744. Args:
  745. ngram_size (`int`):
  746. All ngrams of size `ngram_size` can only occur once.
  747. Examples:
  748. ```py
  749. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  750. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  751. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  752. >>> inputs = tokenizer(["Today I"], return_tensors="pt")
  753. >>> output = model.generate(**inputs)
  754. >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
  755. Today I’m not sure if I’m going to be able to do it.
  756. >>> # Now let's add ngram size using `no_repeat_ngram_size`. This stops the repetitions ("I’m") in the output.
  757. >>> output = model.generate(**inputs, no_repeat_ngram_size=2)
  758. >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
  759. Today I’m not sure if I can get a better understanding of the nature of this issue
  760. ```
  761. """
  762. def __init__(self, ngram_size: int):
  763. if not isinstance(ngram_size, int) or ngram_size <= 0:
  764. raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
  765. self.ngram_size = ngram_size
  766. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  767. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  768. num_batch_hypotheses = scores.shape[0]
  769. cur_len = input_ids.shape[-1]
  770. scores_processed = scores.clone()
  771. banned_batch_tokens = _calc_banned_ngram_tokens(self.ngram_size, input_ids, num_batch_hypotheses, cur_len)
  772. for i, banned_tokens in enumerate(banned_batch_tokens):
  773. scores_processed[i, banned_tokens] = -float("inf")
  774. return scores_processed
  775. class EncoderNoRepeatNGramLogitsProcessor(LogitsProcessor):
  776. r"""
  777. [`LogitsProcessor`] that works similarly to [`NoRepeatNGramLogitsProcessor`], but applied exclusively to prevent
  778. the repetition of n-grams present in the prompt.
  779. It was designed to promote chattiness in a language model, by preventing the generation of n-grams present in
  780. previous conversation rounds.
  781. Args:
  782. encoder_ngram_size (`int`):
  783. All ngrams of size `ngram_size` can only occur within the encoder input ids.
  784. encoder_input_ids (`int`):
  785. The encoder_input_ids that should not be repeated within the decoder ids.
  786. Examples:
  787. ```py
  788. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  789. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  790. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  791. >>> inputs = tokenizer("Alice: I love cats. What do you love?\nBob:", return_tensors="pt")
  792. >>> # With greedy decoding, we see Bob repeating Alice's opinion. If Bob was a chatbot, it would be a poor one.
  793. >>> outputs = model.generate(**inputs)
  794. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  795. Alice: I love cats. What do you love?
  796. Bob: I love cats. What do you
  797. >>> # With this logits processor, we can prevent Bob from repeating Alice's opinion.
  798. >>> outputs = model.generate(**inputs, encoder_no_repeat_ngram_size=2)
  799. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  800. Alice: I love cats. What do you love?
  801. Bob: My cats are very cute.
  802. ```
  803. """
  804. def __init__(self, encoder_ngram_size: int, encoder_input_ids: torch.LongTensor):
  805. if not isinstance(encoder_ngram_size, int) or encoder_ngram_size <= 0:
  806. raise ValueError(
  807. f"`encoder_ngram_size` has to be a strictly positive integer, but is {encoder_ngram_size}"
  808. )
  809. self.ngram_size = encoder_ngram_size
  810. if len(encoder_input_ids.shape) == 1:
  811. encoder_input_ids = encoder_input_ids.unsqueeze(0)
  812. self.batch_size = encoder_input_ids.shape[0]
  813. self.generated_ngrams = _get_ngrams(encoder_ngram_size, encoder_input_ids, self.batch_size)
  814. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  815. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  816. # B x num_beams
  817. num_hypos = scores.shape[0]
  818. num_beams = num_hypos // self.batch_size
  819. cur_len = input_ids.shape[-1]
  820. scores_processed = scores.clone()
  821. banned_batch_tokens = [
  822. _get_generated_ngrams(
  823. self.generated_ngrams[hypo_idx // num_beams], input_ids[hypo_idx], self.ngram_size, cur_len
  824. )
  825. for hypo_idx in range(num_hypos)
  826. ]
  827. for i, banned_tokens in enumerate(banned_batch_tokens):
  828. scores_processed[i, banned_tokens] = -float("inf")
  829. return scores_processed
  830. class SequenceBiasLogitsProcessor(LogitsProcessor):
  831. """
  832. [`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence
  833. when the next generated token can complete it. Consequently, to take the most of biasing sequences with more than
  834. one token, consider using beam methods (to gracefully work around partially completed sequences that have a
  835. negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier).
  836. <Tip>
  837. In order to get the token ids of the sequences that you want to bias, make sure to set `add_prefix_space=True` when
  838. initializing the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The
  839. `add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours
  840. come from `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
  841. </Tip>
  842. Args:
  843. sequence_bias (`List[List[Union[List[int], float]]]`):
  844. List of lists that maps a sequence of tokens to its bias term (e.g. `[[[10, 45], -2.0],
  845. [[64], -7.5]]`). Positive biases increase the odds of the
  846. sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias
  847. will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be
  848. completed (in the token selection step after this processor is applied).
  849. Examples:
  850. ```python
  851. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  852. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  853. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  854. >>> inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt")
  855. >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4)
  856. >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
  857. The full name of Donald is Donald J. Trump Jr
  858. >>> # Now let's control generation through a bias. Please note that the tokenizer is initialized differently!
  859. >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True)
  860. >>> def get_tokens(word):
  861. ... return tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
  862. >>> # If we add a negative bias without beam search, it may become "stuck" in a prefix without good continuations
  863. >>> sequence_bias = [get_tokens("Trump"), -10.0]
  864. >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, sequence_bias=sequence_bias)
  865. >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
  866. The full name of Donald is Donald J. Donald,
  867. >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
  868. >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
  869. The full name of Donald is Donald Rumsfeld,
  870. >>> # We can also add a positive bias to nudge the model towards specific tokens or continuations
  871. >>> sequence_bias = [get_tokens("Donald Duck"), 10.0]
  872. >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
  873. >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
  874. The full name of Donald is Donald Duck.
  875. ```
  876. """
  877. def __init__(self, sequence_bias: List[List[Union[List[int], float]]]):
  878. self.sequence_bias = sequence_bias
  879. self._validate_arguments()
  880. self._convert_list_arguments_into_dict()
  881. # Bias variables that will be populated on the first call (for retrocompatibility purposes, the vocabulary size
  882. # is infered in the first usage, which inhibits initializing here)
  883. self.length_1_bias = None
  884. self.prepared_bias_variables = False
  885. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  886. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  887. # 1 - Prepares the bias tensors. This is only needed the first time the logit processor is called.
  888. if not self.prepared_bias_variables:
  889. self._prepare_bias_variables(scores)
  890. # 2 - prepares an empty bias to add
  891. bias = torch.zeros_like(scores)
  892. # 3 - include the bias from length = 1
  893. bias += self.length_1_bias
  894. # 4 - include the bias from length > 1, after determining which biased sequences may be completed.
  895. for sequence_ids, sequence_bias in self.sequence_bias.items():
  896. if len(sequence_ids) == 1: # the sequence is of length 1, already applied
  897. continue
  898. if len(sequence_ids) > input_ids.shape[1]: # the sequence is longer than the context, ignore
  899. continue
  900. prefix_length = len(sequence_ids) - 1
  901. last_token = sequence_ids[-1]
  902. matching_rows = torch.eq(
  903. input_ids[:, -prefix_length:],
  904. torch.tensor(sequence_ids[:-1], dtype=input_ids.dtype, device=input_ids.device),
  905. ).prod(dim=1)
  906. bias[:, last_token] += torch.where(
  907. matching_rows.bool(),
  908. torch.tensor(sequence_bias, device=input_ids.device),
  909. torch.tensor(0.0, device=input_ids.device),
  910. )
  911. # 5 - apply the bias to the scores
  912. scores_processed = scores + bias
  913. return scores_processed
  914. def _prepare_bias_variables(self, scores: torch.FloatTensor):
  915. vocabulary_size = scores.shape[-1]
  916. # Check biased tokens out of bounds
  917. invalid_biases = []
  918. for sequence_ids in self.sequence_bias:
  919. for token_id in sequence_ids:
  920. if token_id >= vocabulary_size:
  921. invalid_biases.append(token_id)
  922. if len(invalid_biases) > 0:
  923. raise ValueError(
  924. f"The model vocabulary size is {vocabulary_size}, but the following tokens were being biased: "
  925. f"{invalid_biases}"
  926. )
  927. # Precompute the bias tensors to be applied. Sequences of length 1 are kept separately, as they can be applied
  928. # with simpler logic.
  929. self.length_1_bias = torch.zeros((vocabulary_size,), dtype=torch.float).to(scores.device)
  930. for sequence_ids, bias in self.sequence_bias.items():
  931. if len(sequence_ids) == 1:
  932. self.length_1_bias[sequence_ids[-1]] = bias
  933. self.prepared_bias_variables = True
  934. def _validate_arguments(self):
  935. sequence_bias = self.sequence_bias
  936. if not isinstance(sequence_bias, dict) and not isinstance(sequence_bias, list) or len(sequence_bias) == 0:
  937. raise ValueError(
  938. f"`sequence_bias` has to be a non-empty dictionary, or non-empty list of lists but is {sequence_bias}."
  939. )
  940. if isinstance(sequence_bias, dict) and any(
  941. not isinstance(sequence_ids, tuple) for sequence_ids in sequence_bias.keys()
  942. ):
  943. raise ValueError(f"`sequence_bias` has to be a dict with tuples as keys, but is {sequence_bias}.")
  944. if isinstance(sequence_bias, dict) and any(
  945. any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in sequence_ids)
  946. or len(sequence_ids) == 0
  947. for sequence_ids in sequence_bias.keys()
  948. ):
  949. raise ValueError(
  950. f"Each key in `sequence_bias` has to be a non-empty tuple of positive integers, but is "
  951. f"{sequence_bias}."
  952. )
  953. def all_token_bias_pairs_are_valid(sequence):
  954. return (
  955. isinstance(sequence[0], list)
  956. and all(isinstance(token_id, (int, np.integer)) and token_id > 0 for token_id in sequence[0])
  957. and isinstance(sequence[1], float)
  958. )
  959. if isinstance(sequence_bias, list) and any(
  960. (not all_token_bias_pairs_are_valid(sequence)) or len(sequence) == 0 for sequence in sequence_bias
  961. ):
  962. raise ValueError(
  963. f"Each element in `sequence_bias` has to be a non-empty list of lists of positive integers and float, but is "
  964. f"{sequence_bias}."
  965. )
  966. if isinstance(sequence_bias, dict) and any(not isinstance(bias, float) for bias in sequence_bias.values()):
  967. raise ValueError(f"`sequence_bias` has to be a dict with floats as values, but is {sequence_bias}.")
  968. def _convert_list_arguments_into_dict(self):
  969. """BC: we used to accept `dict{tuple of tokens: float}` directly, now we expect a list"""
  970. if isinstance(self.sequence_bias, list):
  971. temp_sequence = self.sequence_bias
  972. self.sequence_bias = {tuple(sublist[0]): sublist[1] for sublist in temp_sequence}
  973. class NoBadWordsLogitsProcessor(SequenceBiasLogitsProcessor):
  974. """
  975. [`LogitsProcessor`] that enforces that specified sequences will never be selected.
  976. <Tip>
  977. In order to get the token ids of the words that should not appear in the generated text, make sure to set
  978. `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words,
  979. add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers,
  980. as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more
  981. [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
  982. </Tip>
  983. Args:
  984. bad_words_ids (`List[List[int]]`):
  985. List of list of token ids that are not allowed to be generated.
  986. eos_token_id (`Union[int, List[int], torch.Tensor]`, *optional*):
  987. The id(s) of the *end-of-sequence* token.
  988. Examples:
  989. ```python
  990. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  991. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  992. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  993. >>> inputs = tokenizer(["In a word, the cake is a"], return_tensors="pt")
  994. >>> output_ids = model.generate(inputs["input_ids"], max_new_tokens=5, pad_token_id=tokenizer.eos_token_id)
  995. >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
  996. In a word, the cake is a bit of a mess.
  997. >>> # Now let's take the bad words out. Please note that the tokenizer is initialized differently
  998. >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True)
  999. >>> def get_tokens_as_list(word_list):
  1000. ... "Converts a sequence of words into a list of tokens"
  1001. ... tokens_list = []
  1002. ... for word in word_list:
  1003. ... tokenized_word = tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
  1004. ... tokens_list.append(tokenized_word)
  1005. ... return tokens_list
  1006. >>> bad_words_ids = get_tokens_as_list(word_list=["mess"])
  1007. >>> output_ids = model.generate(
  1008. ... inputs["input_ids"], max_new_tokens=5, bad_words_ids=bad_words_ids, pad_token_id=tokenizer.eos_token_id
  1009. ... )
  1010. >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
  1011. In a word, the cake is a bit of a surprise.
  1012. ```
  1013. """
  1014. def __init__(
  1015. self, bad_words_ids: List[List[int]], eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None
  1016. ):
  1017. self.bad_word_ids = bad_words_ids
  1018. self._validate_arguments()
  1019. # Filter EOS token from bad_words_ids
  1020. if eos_token_id is not None:
  1021. if not isinstance(eos_token_id, torch.Tensor):
  1022. if isinstance(eos_token_id, int):
  1023. eos_token_id = [eos_token_id]
  1024. eos_token_id = torch.tensor(eos_token_id)
  1025. bad_words_ids = list(
  1026. filter(lambda bad_token_seq: all(bad_token_seq != [i] for i in eos_token_id), bad_words_ids)
  1027. )
  1028. # Forbidding a sequence is equivalent to setting its bias to -inf
  1029. sequence_bias = {tuple(sequence): float("-inf") for sequence in bad_words_ids}
  1030. super().__init__(sequence_bias=sequence_bias)
  1031. def _validate_arguments(self):
  1032. bad_words_ids = self.bad_word_ids
  1033. if not isinstance(bad_words_ids, list) or len(bad_words_ids) == 0:
  1034. raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
  1035. if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
  1036. raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
  1037. if any(
  1038. any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
  1039. for bad_word_ids in bad_words_ids
  1040. ):
  1041. raise ValueError(
  1042. f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
  1043. )
  1044. class PrefixConstrainedLogitsProcessor(LogitsProcessor):
  1045. r"""
  1046. [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
  1047. generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information.
  1048. Args:
  1049. prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`):
  1050. This function constraints the beam search to allowed tokens only at each step. This function takes 2
  1051. arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the
  1052. next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID
  1053. `batch_id`.
  1054. Examples:
  1055. ```py
  1056. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  1057. >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
  1058. >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
  1059. >>> inputs = tokenizer("Alice and Bob", return_tensors="pt")
  1060. >>> # By default, it continues generating according to the model's logits
  1061. >>> outputs = model.generate(**inputs, max_new_tokens=5)
  1062. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  1063. Alice and Bob are friends
  1064. >>> # We can contrain it with `prefix_allowed_tokens_fn` to force a certain behavior based on a prefix.
  1065. >>> # For instance, we can force an entire entity to be generated when its beginning is detected.
  1066. >>> entity = tokenizer(" Bob Marley", return_tensors="pt").input_ids[0] # 3 tokens
  1067. >>> def prefix_allowed_tokens_fn(batch_id, input_ids):
  1068. ... '''
  1069. ... Attempts to generate 'Bob Marley' when 'Bob' is detected.
  1070. ... In this case, `batch_id` is not used, but you can set rules for each batch member.
  1071. ... '''
  1072. ... if input_ids[-1] == entity[0]:
  1073. ... return [entity[1].item()]
  1074. ... elif input_ids[-2] == entity[0] and input_ids[-1] == entity[1]:
  1075. ... return [entity[2].item()]
  1076. ... return list(range(tokenizer.vocab_size)) # If no match, allow all tokens
  1077. >>> outputs = model.generate(**inputs, max_new_tokens=5, prefix_allowed_tokens_fn=prefix_allowed_tokens_fn)
  1078. >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
  1079. Alice and Bob Marley
  1080. ```
  1081. """
  1082. def __init__(self, prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]], num_beams: int):
  1083. self._prefix_allowed_tokens_fn = prefix_allowed_tokens_fn
  1084. self._num_beams = num_beams
  1085. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1086. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1087. mask = torch.full_like(scores, -math.inf)
  1088. for batch_id, beam_sent in enumerate(input_ids.view(-1, self._num_beams, input_ids.shape[-1])):
  1089. for beam_id, sent in enumerate(beam_sent):
  1090. prefix_allowed_tokens = self._prefix_allowed_tokens_fn(batch_id, sent)
  1091. if len(prefix_allowed_tokens) == 0:
  1092. raise ValueError(
  1093. f"`prefix_allowed_tokens_fn` returned an empty list for batch ID {batch_id}."
  1094. f"This means that the constraint is unsatisfiable. Please check your implementation"
  1095. f"of `prefix_allowed_tokens_fn` "
  1096. )
  1097. mask[batch_id * self._num_beams + beam_id, prefix_allowed_tokens] = 0
  1098. scores_processed = scores + mask
  1099. return scores_processed
  1100. class HammingDiversityLogitsProcessor(LogitsProcessor):
  1101. r"""
  1102. [`LogitsProcessor`] that enforces diverse beam search.
  1103. Note that this logits processor is only effective for [`PreTrainedModel.group_beam_search`]. See [Diverse Beam
  1104. Search: Decoding Diverse Solutions from Neural Sequence Models](https://arxiv.org/pdf/1610.02424.pdf) for more
  1105. details.
  1106. Traditional beam search often generates very similar sequences across different beams.
  1107. `HammingDiversityLogitsProcessor` addresses this by penalizing beams that generate tokens already chosen by other
  1108. beams in the same time step.
  1109. Args:
  1110. diversity_penalty (`float`):
  1111. This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
  1112. particular time. A higher `diversity_penalty` will enforce greater diversity among the beams. Adjusting
  1113. this value can help strike a balance between diversity and natural likelihood.
  1114. num_beams (`int`):
  1115. Number of beams for beam search. 1 means no beam search.
  1116. num_beam_groups (`int`):
  1117. Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
  1118. [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
  1119. Examples:
  1120. ```python
  1121. >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
  1122. >>> import torch
  1123. >>> # Initialize the model and tokenizer
  1124. >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
  1125. >>> model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
  1126. >>> # A long text about the solar system
  1127. >>> text = (
  1128. ... "The Solar System is a gravitationally bound system comprising the Sun and the objects that orbit it, "
  1129. ... "either directly or indirectly. Of the objects that orbit the Sun directly, the largest are the eight "
  1130. ... "planets, with the remainder being smaller objects, such as the five dwarf planets and small Solar System "
  1131. ... "bodies. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant "
  1132. ... "interstellar molecular cloud."
  1133. ... )
  1134. >>> inputs = tokenizer("summarize: " + text, return_tensors="pt")
  1135. >>> # Generate diverse summary
  1136. >>> outputs_diverse = model.generate(
  1137. ... **inputs,
  1138. ... num_beam_groups=2,
  1139. ... diversity_penalty=10.0,
  1140. ... max_length=100,
  1141. ... num_beams=4,
  1142. ... num_return_sequences=2,
  1143. ... )
  1144. >>> summaries_diverse = tokenizer.batch_decode(outputs_diverse, skip_special_tokens=True)
  1145. >>> # Generate non-diverse summary
  1146. >>> outputs_non_diverse = model.generate(
  1147. ... **inputs,
  1148. ... max_length=100,
  1149. ... num_beams=4,
  1150. ... num_return_sequences=2,
  1151. ... )
  1152. >>> summary_non_diverse = tokenizer.batch_decode(outputs_non_diverse, skip_special_tokens=True)
  1153. >>> # With `diversity_penalty`, the resulting beams are much more diverse
  1154. >>> print(summary_non_diverse)
  1155. ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
  1156. 'the Solar System formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.']
  1157. >>> print(summaries_diverse)
  1158. ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
  1159. 'the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets. the rest of the objects are smaller objects, such as the five dwarf planets and small solar system bodies.']
  1160. ```
  1161. """
  1162. def __init__(self, diversity_penalty: float, num_beams: int, num_beam_groups: int):
  1163. if not isinstance(diversity_penalty, float) or (not diversity_penalty > 0.0):
  1164. raise ValueError("`diversity_penalty` should be a float strictly larger than 0.")
  1165. self._diversity_penalty = diversity_penalty
  1166. if not isinstance(num_beams, int) or num_beams < 2:
  1167. raise ValueError("`num_beams` should be an integer strictly larger than 1.")
  1168. self._num_beams = num_beams
  1169. if not isinstance(num_beam_groups, int) or num_beam_groups < 2:
  1170. raise ValueError("`num_beam_groups` should be an integer strictly larger than 1.")
  1171. if num_beam_groups > num_beams:
  1172. raise ValueError("`beam_groups` has to be smaller or equal to `num_beams`.")
  1173. self._num_sub_beams = num_beams // num_beam_groups
  1174. def __call__(
  1175. self,
  1176. input_ids: torch.LongTensor,
  1177. scores: torch.FloatTensor,
  1178. current_tokens: torch.LongTensor,
  1179. beam_group_idx: int,
  1180. ) -> torch.FloatTensor:
  1181. r"""
  1182. Args:
  1183. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1184. Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
  1185. scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
  1186. Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
  1187. beam search or log softmax for each vocabulary token when using beam search
  1188. current_tokens (`torch.LongTensor` of shape `(batch_size)`):
  1189. Indices of input sequence tokens in the vocabulary, corresponding to the tokens selected by the other
  1190. beam groups in the current generation step.
  1191. beam_group_idx (`int`):
  1192. The index of the beam group currently being processed.
  1193. Return:
  1194. `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
  1195. The processed prediction scores.
  1196. """
  1197. # hamming diversity: penalise using same token in current group which was used in previous groups at
  1198. # the same time step
  1199. batch_size = current_tokens.shape[0] // self._num_beams
  1200. group_start_idx = beam_group_idx * self._num_sub_beams
  1201. group_end_idx = min(group_start_idx + self._num_sub_beams, self._num_beams)
  1202. group_size = group_end_idx - group_start_idx
  1203. vocab_size = scores.shape[-1]
  1204. if group_start_idx == 0:
  1205. return scores
  1206. scores_processed = scores.clone()
  1207. for batch_idx in range(batch_size):
  1208. # predicted tokens of last time step of previous groups
  1209. previous_group_tokens = current_tokens[
  1210. batch_idx * self._num_beams : batch_idx * self._num_beams + group_start_idx
  1211. ]
  1212. token_frequency = torch.bincount(previous_group_tokens, minlength=vocab_size).to(scores.device)
  1213. scores_processed[batch_idx * group_size : (batch_idx + 1) * group_size] -= (
  1214. self._diversity_penalty * token_frequency
  1215. )
  1216. return scores_processed
  1217. class ForcedBOSTokenLogitsProcessor(LogitsProcessor):
  1218. r"""
  1219. [`LogitsProcessor`] that enforces the specified token as the first generated token. Used with encoder-decoder
  1220. models.
  1221. Args:
  1222. bos_token_id (`int`):
  1223. The id of the token to force as the first generated token.
  1224. Examples:
  1225. ```python
  1226. >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
  1227. >>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small")
  1228. >>> tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small")
  1229. >>> inputs = tokenizer("Translate from English to German: I love cats.", return_tensors="pt")
  1230. >>> # By default, it continues generating according to the model's logits
  1231. >>> outputs = model.generate(**inputs, max_new_tokens=10)
  1232. >>> print(tokenizer.batch_decode(outputs)[0])
  1233. <pad> Ich liebe Kitty.</s>
  1234. >>> # We can use `forced_bos_token_id` to force the start of generation with an encoder-decoder model
  1235. >>> # (including forcing it to end straight away with an EOS token)
  1236. >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_bos_token_id=tokenizer.eos_token_id)
  1237. >>> print(tokenizer.batch_decode(outputs)[0])
  1238. <pad></s>
  1239. ```
  1240. """
  1241. def __init__(self, bos_token_id: int):
  1242. self.bos_token_id = bos_token_id
  1243. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1244. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1245. cur_len = input_ids.shape[-1]
  1246. scores_processed = scores
  1247. if cur_len == 1:
  1248. scores_processed = torch.full_like(scores, -math.inf)
  1249. scores_processed[:, self.bos_token_id] = 0
  1250. return scores_processed
  1251. class ForcedEOSTokenLogitsProcessor(LogitsProcessor):
  1252. r"""
  1253. [`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
  1254. Args:
  1255. max_length (`int`):
  1256. The maximum length of the sequence to be generated.
  1257. eos_token_id (`Union[int, List[int], torch.Tensor]`):
  1258. The id(s) of the *end-of-sequence* token.
  1259. device (`str`, *optional*, defaults to `"cpu"`):
  1260. The device to allocate the tensors.
  1261. Examples:
  1262. ```python
  1263. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  1264. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  1265. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  1266. >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")
  1267. >>> # By default, it continues generating according to the model's logits
  1268. >>> outputs = model.generate(**inputs, max_new_tokens=10)
  1269. >>> print(tokenizer.batch_decode(outputs)[0])
  1270. A sequence: 1, 2, 3, 4, 5, 6, 7, 8
  1271. >>> # `forced_eos_token_id` ensures the generation ends with a EOS token
  1272. >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_eos_token_id=tokenizer.eos_token_id)
  1273. >>> print(tokenizer.batch_decode(outputs)[0])
  1274. A sequence: 1, 2, 3, 4, 5, 6, 7,<|endoftext|>
  1275. ```
  1276. """
  1277. def __init__(self, max_length: int, eos_token_id: Union[int, List[int], torch.Tensor], device: str = "cpu"):
  1278. self.max_length = max_length
  1279. if not isinstance(eos_token_id, torch.Tensor):
  1280. if isinstance(eos_token_id, int):
  1281. eos_token_id = [eos_token_id]
  1282. eos_token_id = torch.tensor(eos_token_id, device=device)
  1283. self.eos_token_id = eos_token_id
  1284. if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
  1285. raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
  1286. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1287. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1288. cur_len = input_ids.shape[-1]
  1289. scores_processed = scores
  1290. if cur_len == self.max_length - 1:
  1291. scores_processed = torch.full_like(scores, -math.inf)
  1292. scores_processed[:, self.eos_token_id] = 0
  1293. return scores_processed
  1294. class InfNanRemoveLogitsProcessor(LogitsProcessor):
  1295. r"""
  1296. [`LogitsProcessor`] that removes all `nan` and `inf` values to avoid the generation method to fail. Note that using
  1297. the logits processor should only be used if necessary since it can slow down the generation method.
  1298. This logits processor has no `generate` example, as there shouldn't be a correct combination of flags that warrants
  1299. its use.
  1300. """
  1301. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1302. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1303. # set all nan values to 0.0
  1304. scores_processed = torch.where(scores != scores, 0.0, scores)
  1305. # set all +/-inf values to max/min possible value
  1306. scores_processed = torch.where(scores == float("inf"), torch.finfo(scores.dtype).max, scores_processed)
  1307. scores_processed = torch.where(scores == -float("inf"), torch.finfo(scores.dtype).min, scores_processed)
  1308. return scores_processed
  1309. class ExponentialDecayLengthPenalty(LogitsProcessor):
  1310. r"""
  1311. [`LogitsProcessor`] that exponentially increases the score of the `eos_token_id` after `start_index` has been
  1312. reached. This allows generating shorter sequences without having a hard cutoff, allowing the `eos_token` to be
  1313. predicted in a meaningful position.
  1314. Args:
  1315. exponential_decay_length_penalty (`tuple(int, float)`):
  1316. This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
  1317. starts and `decay_factor` represents the factor of exponential decay
  1318. eos_token_id (`Union[int, List[int], torch.Tensor]`):
  1319. The id(s) of the *end-of-sequence* token.
  1320. input_ids_seq_length (`int`):
  1321. The length of the input sequence.
  1322. Examples:
  1323. ```python
  1324. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
  1325. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1326. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1327. >>> text = "Just wanted to let you know, I"
  1328. >>> inputs = tokenizer(text, return_tensors="pt")
  1329. >>> # Let's consider that we want short sentences, so we limit `max_length=30`. However, we observe that the answer
  1330. >>> # tends to end abruptly.
  1331. >>> set_seed(1)
  1332. >>> outputs = model.generate(**inputs, do_sample=True, temperature=0.9, max_length=30, pad_token_id=50256)
  1333. >>> print(tokenizer.batch_decode(outputs)[0])
  1334. Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
  1335. published in 2010. Although
  1336. >>> # To promote the appearance of the EOS token at the right time, we add the `exponential_decay_length_penalty =
  1337. >>> # (start_index, decay_factor)`. Instead of cutting at max_tokens, the output comes to an end before and usually
  1338. >>> # with more meaning. What happens is that starting from `start_index` the EOS token score will be increased
  1339. >>> # by `decay_factor` exponentially. However, if you set a high decay factor, you may also end up with abruptly
  1340. >>> # ending sequences.
  1341. >>> set_seed(1)
  1342. >>> outputs = model.generate(
  1343. ... **inputs,
  1344. ... do_sample=True,
  1345. ... temperature=0.9,
  1346. ... max_length=30,
  1347. ... pad_token_id=50256,
  1348. ... exponential_decay_length_penalty=(15, 1.6),
  1349. ... )
  1350. >>> print(tokenizer.batch_decode(outputs)[0])
  1351. Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network
  1352. which<|endoftext|>
  1353. >>> # With a small decay factor, you will have a higher chance of getting a meaningful sequence.
  1354. >>> set_seed(1)
  1355. >>> outputs = model.generate(
  1356. ... **inputs,
  1357. ... do_sample=True,
  1358. ... temperature=0.9,
  1359. ... max_length=30,
  1360. ... pad_token_id=50256,
  1361. ... exponential_decay_length_penalty=(15, 1.01),
  1362. ... )
  1363. >>> print(tokenizer.batch_decode(outputs)[0])
  1364. Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
  1365. published in 2010.<|endoftext|>
  1366. ```
  1367. """
  1368. def __init__(
  1369. self,
  1370. exponential_decay_length_penalty: Tuple[int, float],
  1371. eos_token_id: Union[int, List[int], torch.Tensor],
  1372. input_ids_seq_length: int,
  1373. ):
  1374. self.regulation_start = exponential_decay_length_penalty[0] + input_ids_seq_length
  1375. self.regulation_factor = exponential_decay_length_penalty[1]
  1376. if not isinstance(eos_token_id, torch.Tensor):
  1377. if isinstance(eos_token_id, int):
  1378. eos_token_id = [eos_token_id]
  1379. eos_token_id = torch.tensor(eos_token_id)
  1380. self.eos_token_id = eos_token_id
  1381. if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
  1382. raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
  1383. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1384. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1385. cur_len = input_ids.shape[-1]
  1386. self.eos_token_id = self.eos_token_id.to(scores.device)
  1387. penalties = torch.zeros_like(scores)
  1388. scores_processed = scores
  1389. if cur_len > self.regulation_start:
  1390. penalty_idx = cur_len - self.regulation_start
  1391. # To support negative logits we compute the penalty of the absolute value and add to the original logit
  1392. penalty = torch.abs(scores[:, self.eos_token_id]) * (pow(self.regulation_factor, penalty_idx) - 1)
  1393. penalties[:, self.eos_token_id] = penalty
  1394. scores_processed = scores + penalties
  1395. return scores_processed
  1396. class LogitNormalization(LogitsProcessor):
  1397. r"""
  1398. [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize
  1399. the scores during beam search, after applying the logits processors or warpers, since the search algorithm used in
  1400. this library doesn't do it (it only does it before, but they may need re-normalization) but it still supposes that
  1401. the scores are normalized when comparing the hypotheses.
  1402. Examples:
  1403. ```python
  1404. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  1405. >>> import torch
  1406. >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
  1407. >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
  1408. >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")
  1409. >>> # By default, the scores are not normalized -- the sum of their exponentials is NOT a normalized probability
  1410. >>> # distribution, summing to 1
  1411. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
  1412. >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4))
  1413. False
  1414. >>> # Normalizing them may have a positive impact on beam methods, or when using the scores on your application
  1415. >>> outputs = model.generate(**inputs, renormalize_logits=True, return_dict_in_generate=True, output_scores=True)
  1416. >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4))
  1417. True
  1418. ```
  1419. """
  1420. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1421. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1422. scores_processed = scores.log_softmax(dim=-1)
  1423. return scores_processed
  1424. class SuppressTokensAtBeginLogitsProcessor(LogitsProcessor):
  1425. r"""
  1426. [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts
  1427. generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` are
  1428. not generated at the begining. Originally created for
  1429. [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper).
  1430. Examples:
  1431. ```python
  1432. >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
  1433. >>> from datasets import load_dataset
  1434. >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
  1435. >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
  1436. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  1437. >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
  1438. >>> # Whisper has `begin_suppress_tokens` set by default (= `[220, 50256]`). 50256 is the EOS token, so this means
  1439. >>> # it can't generate and EOS token in the first iteration, but it can in the others.
  1440. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
  1441. >>> print(outputs.scores[0][0, 50256])
  1442. tensor(-inf)
  1443. >>> print(outputs.scores[-1][0, 50256]) # in other places we can see some probability mass for EOS
  1444. tensor(29.9010)
  1445. >>> # If we disable `begin_suppress_tokens`, we can generate EOS in the first iteration.
  1446. >>> outputs = model.generate(
  1447. ... **inputs, return_dict_in_generate=True, output_scores=True, begin_suppress_tokens=None
  1448. ... )
  1449. >>> print(outputs.scores[0][0, 50256])
  1450. tensor(11.2027)
  1451. ```
  1452. """
  1453. def __init__(self, begin_suppress_tokens, begin_index, device: str = "cpu"):
  1454. self.begin_suppress_tokens = torch.tensor(list(begin_suppress_tokens), device=device)
  1455. self.begin_index = begin_index
  1456. def set_begin_index(self, begin_index):
  1457. self.begin_index = begin_index
  1458. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1459. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1460. vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
  1461. suppress_token_mask = isin_mps_friendly(vocab_tensor, self.begin_suppress_tokens)
  1462. scores_processed = scores
  1463. if input_ids.shape[-1] == self.begin_index:
  1464. scores_processed = torch.where(suppress_token_mask, -float("inf"), scores)
  1465. return scores_processed
  1466. class SuppressTokensLogitsProcessor(LogitsProcessor):
  1467. r"""
  1468. This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so
  1469. that they are not generated. Originally created for
  1470. [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper).
  1471. Examples:
  1472. ```python
  1473. >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
  1474. >>> from datasets import load_dataset
  1475. >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
  1476. >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
  1477. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  1478. >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
  1479. >>> # Whisper has a long list of suppressed tokens. For instance, in this case, the token 1 is suppressed by default.
  1480. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
  1481. >>> print(outputs.scores[1][0, 1]) # 1 (and not 0) is the first freely generated token
  1482. tensor(-inf)
  1483. >>> # If we disable `suppress_tokens`, we can generate it.
  1484. >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True, suppress_tokens=None)
  1485. >>> print(outputs.scores[1][0, 1])
  1486. tensor(6.0678)
  1487. ```
  1488. """
  1489. def __init__(self, suppress_tokens, device: str = "cpu"):
  1490. self.suppress_tokens = torch.tensor(list(suppress_tokens), device=device)
  1491. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1492. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1493. vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
  1494. suppress_token_mask = isin_mps_friendly(vocab_tensor, self.suppress_tokens)
  1495. scores = torch.where(suppress_token_mask, -float("inf"), scores)
  1496. return scores
  1497. class WhisperTimeStampLogitsProcessor(LogitsProcessor):
  1498. r"""
  1499. [`LogitsProcessor`] that modifies the logits for the generation of timestamps in the transcription. When the input
  1500. tokens are at a specific threshold, the processor sets the scores to negative infinity. The processor makes sure
  1501. that timestamp tokens appear in pairs, by masking out the logits that would break this pairing pattern. This is
  1502. done to maintain the consistency and structure of generated timestamps. It also ensures that when the predicted
  1503. probability of sampling any of the timestamp token is greater than any individual non-timestamp token, those
  1504. non-timestamp logits are set to negative infinity. This is done to ensure the generation of timestamps over other
  1505. potential tokens.
  1506. See [the paper](https://arxiv.org/abs/2212.04356) for more information.
  1507. Args:
  1508. generate_config (`GenerateConfig`):
  1509. The generate config used to generate the output. The following parameters are required:
  1510. eos_token_id (`int`, *optional*, defaults to 50257):
  1511. The id of the *end-of-sequence* token.
  1512. no_timestamps_token_id (`int`, *optional*, defaults to 50363):
  1513. The id of the `"<|notimestamps|>"` token.
  1514. max_initial_timestamp_index (`int`, *optional*, defaults to 1):
  1515. Used to set the maximum value of the initial timestamp. This is used to prevent the model from
  1516. predicting timestamps that are too far in the future.
  1517. begin_index (`Optional`, *optional*): Token index of the first token that is generated by the model.
  1518. _detect_timestamp_from_logprob (`bool`, *optional*): Whether timestamps can be predicted from logprobs over all timestamps.
  1519. Examples:
  1520. ``` python
  1521. >>> import torch
  1522. >>> from transformers import AutoProcessor, WhisperForConditionalGeneration, GenerationConfig
  1523. >>> from datasets import load_dataset
  1524. >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
  1525. >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
  1526. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  1527. >>> inputs = processor(ds[3]["audio"]["array"], return_tensors="pt")
  1528. >>> input_features = inputs.input_features
  1529. >>> #Displaying timestamps
  1530. >>> generated_ids = model.generate(inputs=input_features, return_timestamps=True)
  1531. >>> transcription = processor.batch_decode(generated_ids, decode_with_timestamps=True)[0]
  1532. >>> print("Transcription:", transcription)
  1533. Transcription: <|startoftranscript|><|0.00|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all, and can<|6.44|><|6.44|> discover in it but little of rocky Ithaca.<|9.44|><|endoftext|>
  1534. >>> #No timestamps & change EOS:
  1535. >>> #This allows the user to select a specific token to terminate the sequence on, in this case it's the word "can"(460)
  1536. >>> model.generation_config.eos_token_id = 460
  1537. >>> generated_ids = model.generate(inputs=input_features,return_timestamps=False)
  1538. >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  1539. >>> print("Transcription:", transcription)
  1540. Transcription: He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can
  1541. ```
  1542. """
  1543. def __init__(
  1544. self,
  1545. generate_config,
  1546. begin_index: Optional[int] = None,
  1547. _detect_timestamp_from_logprob: Optional[bool] = None,
  1548. ): # support for the kwargs
  1549. self.no_timestamps_token_id = generate_config.no_timestamps_token_id
  1550. self.timestamp_begin = generate_config.no_timestamps_token_id + 1
  1551. self.eos_token_id = generate_config.eos_token_id or generate_config.bos_token_id
  1552. # this variable is mostly just used for testing
  1553. self._detect_timestamp_from_logprob = (
  1554. _detect_timestamp_from_logprob
  1555. if _detect_timestamp_from_logprob is not None
  1556. else getattr(generate_config, "_detect_timestamp_from_logprob", True)
  1557. )
  1558. num_forced_ids = (
  1559. len(generate_config.forced_decoder_ids) if generate_config.forced_decoder_ids is not None else 0
  1560. )
  1561. self.begin_index = begin_index or (num_forced_ids + 1)
  1562. self.max_initial_timestamp_index = getattr(generate_config, "max_initial_timestamp_index", None)
  1563. # TODO(Patrick): Make sure that official models have max_initial_timestamp_index set to 50
  1564. # self.max_initial_timestamp_index = 50
  1565. def set_begin_index(self, begin_index):
  1566. self.begin_index = begin_index
  1567. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1568. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1569. # suppress <|notimestamps|> which is handled by without_timestamps
  1570. scores_processed = scores.clone()
  1571. scores_processed[:, self.no_timestamps_token_id] = -float("inf")
  1572. # timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
  1573. for k in range(input_ids.shape[0]):
  1574. sampled_tokens = input_ids[k, self.begin_index :]
  1575. seq = list(sampled_tokens.tolist())
  1576. last_was_timestamp = len(seq) >= 1 and seq[-1] >= self.timestamp_begin
  1577. penultimate_was_timestamp = len(seq) < 2 or seq[-2] >= self.timestamp_begin
  1578. if last_was_timestamp:
  1579. if penultimate_was_timestamp: # has to be non-timestamp
  1580. scores_processed[k, self.timestamp_begin :] = -float("inf")
  1581. else: # cannot be normal text tokens
  1582. scores_processed[k, : self.eos_token_id] = -float("inf")
  1583. timestamps = sampled_tokens[sampled_tokens.ge(self.timestamp_begin)]
  1584. if timestamps.numel() > 0:
  1585. # `timestamps` shouldn't decrease; forbid timestamp tokens smaller than the last
  1586. # The following lines of code are copied from: https://github.com/openai/whisper/pull/914/files#r1137085090
  1587. if last_was_timestamp and not penultimate_was_timestamp:
  1588. timestamp_last = timestamps[-1]
  1589. else:
  1590. # Avoid to emit <|0.00|> again
  1591. timestamp_last = timestamps[-1] + 1
  1592. scores_processed[k, self.timestamp_begin : timestamp_last] = -float("inf")
  1593. # apply the `max_initial_timestamp` option
  1594. if input_ids.shape[1] == self.begin_index:
  1595. scores_processed[:, : self.timestamp_begin] = -float("inf")
  1596. if self.max_initial_timestamp_index is not None:
  1597. last_allowed = self.timestamp_begin + self.max_initial_timestamp_index
  1598. scores_processed[:, last_allowed + 1 :] = -float("inf")
  1599. # if sum of probability over timestamps is above any other token, sample timestamp
  1600. logprobs = torch.nn.functional.log_softmax(scores_processed.float(), dim=-1)
  1601. for k in range(input_ids.shape[0]):
  1602. timestamp_logprob = logprobs[k, self.timestamp_begin :].logsumexp(dim=-1)
  1603. max_text_token_logprob = logprobs[k, : self.timestamp_begin].max()
  1604. if timestamp_logprob > max_text_token_logprob and self._detect_timestamp_from_logprob:
  1605. scores_processed[k, : self.timestamp_begin] = -float("inf")
  1606. return scores_processed
  1607. class WhisperNoSpeechDetection(LogitsProcessor):
  1608. r"""This processor can be used to detect silence when using Whisper. It should take as input unprocessed logits to follow the original implementation"""
  1609. def __init__(self, no_speech_token: int, begin_index: int, scores_is_logprobs: bool = False):
  1610. self.no_speech_token = no_speech_token
  1611. # offset between <start-of-transcription> token, <SOT>, in paper and first generated token
  1612. # is equal to the position of the first generated token index
  1613. self.start_of_trans_offset = begin_index
  1614. # `self.begin_index` is a running value that is changed on the fly
  1615. self.begin_index = begin_index
  1616. self._no_speech_prob = [0.0]
  1617. self.is_scores_logprobs = scores_is_logprobs
  1618. # overwritten dynamically
  1619. self.model = None
  1620. self.inputs = None
  1621. def set_model(self, model):
  1622. self.model = model
  1623. def set_inputs(self, inputs):
  1624. self.inputs = {**self.model.prepare_inputs_for_generation(**inputs), **inputs}
  1625. self.inputs["input_features"] = self.inputs.pop("inputs")
  1626. @property
  1627. def no_speech_prob(self):
  1628. return self._no_speech_prob
  1629. def set_begin_index(self, begin_index):
  1630. self.begin_index = begin_index
  1631. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1632. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1633. is_scores_logprobs = self.is_scores_logprobs
  1634. if input_ids.shape[1] == self.begin_index:
  1635. if self.start_of_trans_offset > 1:
  1636. with torch.no_grad():
  1637. logits = self.model(**self.inputs).logits
  1638. no_speech_index = self.begin_index - self.start_of_trans_offset
  1639. no_speech_scores = logits[:, no_speech_index]
  1640. is_scores_logprobs = False
  1641. else:
  1642. no_speech_scores = scores
  1643. if is_scores_logprobs:
  1644. probs = no_speech_scores.exp()
  1645. else:
  1646. probs = no_speech_scores.float().softmax(dim=-1)
  1647. self._no_speech_prob = probs[:, self.no_speech_token]
  1648. return scores
  1649. class ClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
  1650. r"""
  1651. [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,
  1652. where the first half correspond to the conditional logits (predicted from the input prompt) and the second half
  1653. correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a
  1654. weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.
  1655. See [the paper](https://arxiv.org/abs/2306.05284) for more information.
  1656. <Tip warning={true}>
  1657. This logits processor is exclusively compatible with
  1658. [MusicGen](https://huggingface.co/docs/transformers/main/en/model_doc/musicgen)
  1659. </Tip>
  1660. Args:
  1661. guidance_scale (float):
  1662. The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
  1663. Higher guidance scale encourages the model to generate samples that are more closely linked to the input
  1664. prompt, usually at the expense of poorer quality.
  1665. Examples:
  1666. ```python
  1667. >>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
  1668. >>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
  1669. >>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
  1670. >>> inputs = processor(
  1671. ... text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"],
  1672. ... padding=True,
  1673. ... return_tensors="pt",
  1674. ... )
  1675. >>> audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)
  1676. ```
  1677. """
  1678. def __init__(self, guidance_scale):
  1679. if guidance_scale > 1:
  1680. self.guidance_scale = guidance_scale
  1681. else:
  1682. raise ValueError(
  1683. "Require guidance scale >1 to use the classifier free guidance processor, got guidance scale "
  1684. f"{guidance_scale}."
  1685. )
  1686. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1687. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1688. # simple check to make sure we have compatible batch sizes between our
  1689. # logits scores (cond + uncond) and input ids (cond only)
  1690. if scores.shape[0] != 2 * input_ids.shape[0]:
  1691. raise ValueError(
  1692. f"Logits should have twice the batch size of the input ids, the first half of batches corresponding to "
  1693. f"the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got "
  1694. f"batch size {scores.shape[0]} for the logits and {input_ids.shape[0]} for the input ids."
  1695. )
  1696. unguided_bsz = scores.shape[0] // 2
  1697. cond_logits, uncond_logits = scores.split(unguided_bsz, dim=0)
  1698. scores_processed = uncond_logits + (cond_logits - uncond_logits) * self.guidance_scale
  1699. return scores_processed
  1700. class AlternatingCodebooksLogitsProcessor(LogitsProcessor):
  1701. r"""
  1702. [`LogitsProcessor`] enforcing alternated generation between the two codebooks of Bark.
  1703. <Tip warning={true}>
  1704. This logits processor is exclusively compatible with
  1705. [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark)'s fine submodel. See the model documentation
  1706. for examples.
  1707. </Tip>
  1708. Args:
  1709. input_start_len (`int`):
  1710. The length of the initial input sequence.
  1711. semantic_vocab_size (`int`):
  1712. Vocabulary size of the semantic part, i.e number of tokens associated to the semantic vocabulary.
  1713. codebook_size (`int`):
  1714. Number of tokens associated to the codebook.
  1715. """
  1716. def __init__(self, input_start_len: int, semantic_vocab_size: int, codebook_size: int):
  1717. if not isinstance(input_start_len, int) or input_start_len < 0:
  1718. raise ValueError(f"`input_starting_length` has to be a non-negative integer, but is {input_start_len}")
  1719. self.input_start_len = input_start_len
  1720. self.semantic_vocab_size = semantic_vocab_size
  1721. self.codebook_size = codebook_size
  1722. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1723. curr_len = input_ids.shape[-1]
  1724. # even -> first codebook, odd -> second codebook
  1725. is_first_codebook = ((curr_len - self.input_start_len) % 2) == 0
  1726. scores_processed = scores.clone()
  1727. if is_first_codebook:
  1728. scores_processed[:, : self.semantic_vocab_size] = -float("inf")
  1729. scores_processed[:, self.semantic_vocab_size + self.codebook_size :] = -float("inf")
  1730. else:
  1731. scores_processed[:, : self.semantic_vocab_size + self.codebook_size] = -float("inf")
  1732. return scores_processed
  1733. class UnbatchedClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
  1734. r"""
  1735. Logits processor for Classifier-Free Guidance (CFG). The processors computes a weighted average across scores
  1736. from prompt conditional and prompt unconditional (or negative) logits, parameterized by the `guidance_scale`.
  1737. The unconditional scores are computed internally by prompting `model` with the `unconditional_ids` branch.
  1738. See [the paper](https://arxiv.org/abs/2306.17806) for more information.
  1739. Args:
  1740. guidance_scale (`float`):
  1741. The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale != 1`.
  1742. Higher guidance scale encourages the model to generate samples that are more closely linked to the input
  1743. prompt, usually at the expense of poorer quality. A value smaller than 1 has the opposite effect, while
  1744. making the negative prompt provided with negative_prompt_ids (if any) act as a positive prompt.
  1745. model (`PreTrainedModel`):
  1746. The model computing the unconditional scores. Supposedly the same as the one computing the conditional
  1747. scores. Both models must use the same tokenizer.
  1748. unconditional_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1749. Indices of input sequence tokens in the vocabulary for the unconditional branch. If unset, will default to
  1750. the last token of the prompt.
  1751. unconditional_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1752. Attention mask for unconditional_ids.
  1753. use_cache (`bool`, *optional*, defaults to `True`):
  1754. Whether to cache key/values during the negative prompt forward pass.
  1755. Examples:
  1756. ```python
  1757. >>> from transformers import AutoTokenizer, AutoModelForCausalLM
  1758. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1759. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1760. >>> inputs = tokenizer(["Today, a dragon flew over Paris, France,"], return_tensors="pt")
  1761. >>> out = model.generate(inputs["input_ids"], guidance_scale=1.5)
  1762. >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
  1763. 'Today, a dragon flew over Paris, France, killing at least 50 people and injuring more than 100'
  1764. >>> # with a negative prompt
  1765. >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
  1766. >>> out = model.generate(inputs["input_ids"], guidance_scale=2, negative_prompt_ids=neg_inputs["input_ids"])
  1767. >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
  1768. 'Today, a dragon flew over Paris, France, killing at least 130 people. French media reported that'
  1769. >>> # with a positive prompt
  1770. >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
  1771. >>> out = model.generate(inputs["input_ids"], guidance_scale=0, negative_prompt_ids=neg_inputs["input_ids"])
  1772. >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
  1773. "Today, a dragon flew over Paris, France, and I'm very happy to be here. I"
  1774. ```
  1775. """
  1776. def __init__(
  1777. self,
  1778. guidance_scale: float,
  1779. model,
  1780. unconditional_ids: Optional[torch.LongTensor] = None,
  1781. unconditional_attention_mask: Optional[torch.LongTensor] = None,
  1782. use_cache: Optional[bool] = True,
  1783. ):
  1784. self.guidance_scale = guidance_scale
  1785. self.model = model
  1786. self.unconditional_context = {
  1787. "input_ids": unconditional_ids,
  1788. "attention_mask": unconditional_attention_mask,
  1789. "use_cache": use_cache,
  1790. "past_key_values": None,
  1791. "first_pass": True,
  1792. }
  1793. def get_unconditional_logits(self, input_ids):
  1794. if self.unconditional_context["first_pass"]:
  1795. if self.unconditional_context["input_ids"] is None:
  1796. self.unconditional_context["input_ids"] = input_ids[:, -1:]
  1797. if self.unconditional_context["attention_mask"] is None:
  1798. self.unconditional_context["attention_mask"] = torch.ones_like(
  1799. self.unconditional_context["input_ids"], dtype=torch.long
  1800. )
  1801. input_ids = self.unconditional_context["input_ids"]
  1802. attention_mask = self.unconditional_context["attention_mask"]
  1803. self.unconditional_context["first_pass"] = False
  1804. else:
  1805. attention_mask = torch.cat(
  1806. [
  1807. self.unconditional_context["attention_mask"],
  1808. torch.ones_like(input_ids[:, -1:], dtype=torch.long),
  1809. ],
  1810. dim=1,
  1811. )
  1812. if not self.unconditional_context["use_cache"]:
  1813. input_ids = torch.cat([self.unconditional_context["input_ids"], input_ids[:, -1:]], dim=1)
  1814. else:
  1815. input_ids = input_ids[:, -1:]
  1816. self.unconditional_context["input_ids"] = input_ids
  1817. self.unconditional_context["attention_mask"] = attention_mask
  1818. out = self.model(
  1819. input_ids,
  1820. attention_mask=attention_mask,
  1821. use_cache=self.unconditional_context["use_cache"],
  1822. past_key_values=self.unconditional_context["past_key_values"],
  1823. )
  1824. self.unconditional_context["past_key_values"] = out.get("past_key_values", None)
  1825. return out.logits
  1826. def __call__(self, input_ids, scores):
  1827. scores = torch.nn.functional.log_softmax(scores, dim=-1)
  1828. if self.guidance_scale == 1:
  1829. return scores
  1830. logits = self.get_unconditional_logits(input_ids)
  1831. unconditional_logits = torch.nn.functional.log_softmax(logits[:, -1], dim=-1)
  1832. scores_processed = self.guidance_scale * (scores - unconditional_logits) + unconditional_logits
  1833. return scores_processed
  1834. class BarkEosPrioritizerLogitsProcessor(LogitsProcessor):
  1835. r"""This processor ensures that the EOS token is selected if its probability is greater than the `min_eos_p`.
  1836. <Tip warning={true}>
  1837. This logits processor is exclusively compatible with
  1838. [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark). See the model documentation for examples.
  1839. </Tip>
  1840. Args:
  1841. eos_token_id (`Union[int, List[int], torch.Tensor]`):
  1842. The id(s) of the *end-of-sequence* token.
  1843. min_eos_p (`float`, *optional*):
  1844. Minimum end of speech threshold.
  1845. """
  1846. def __init__(self, eos_token_id: Union[int, List[int], torch.Tensor], min_eos_p: float, device: str = "cpu"):
  1847. if not isinstance(eos_token_id, torch.Tensor):
  1848. if isinstance(eos_token_id, int):
  1849. eos_token_id = [eos_token_id]
  1850. eos_token_id = torch.tensor(eos_token_id, device=device)
  1851. self.eos_token_id = eos_token_id
  1852. if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
  1853. raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
  1854. if min_eos_p is not None and min_eos_p <= 0:
  1855. raise ValueError(f"`min_eos_p` has to be a positive float, but is {min_eos_p}")
  1856. self.min_eos_p = min_eos_p
  1857. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1858. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1859. scores_processed = scores
  1860. if self.min_eos_p:
  1861. probs = torch.nn.functional.softmax(scores.float(), dim=-1)
  1862. # create scores full of -inf except for the eos_token_id
  1863. early_stop_scores = torch.ones_like(scores) * -float("inf")
  1864. early_stop_scores[:, self.eos_token_id] = scores[:, self.eos_token_id]
  1865. do_early_stop = probs[:, self.eos_token_id] > self.min_eos_p
  1866. do_early_stop = torch.any(do_early_stop, dim=1, keepdim=True)
  1867. scores_processed = torch.where(do_early_stop, early_stop_scores, scores)
  1868. return scores_processed
  1869. class WatermarkLogitsProcessor(LogitsProcessor):
  1870. r"""
  1871. Logits processor for watermarking generated text. The processor modifies model output scores by adding a small bias to
  1872. randomized set of "green" tokens before generating the next token. "Green" tokens selection process depends on the
  1873. `seeding_scheme` used. The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).
  1874. The text generated by this `LogitsProcessor` can be detected using `WatermarkDetector`. See [`~WatermarkDetector.__call__`] for details,
  1875. See [the paper](https://arxiv.org/abs/2306.04634) for more information.
  1876. Args:
  1877. vocab_size (`int`):
  1878. The model tokenizer's vocab_size. Used to calculate "green" tokens ratio.
  1879. device (`str`):
  1880. The device where model is allocated.
  1881. greenlist_ratio (`float`, optional, *optional*, defaults to 0.25):
  1882. The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25.
  1883. bias (`float`, optional, *optional*, defaults to 2.0):
  1884. The bias added to the selected "green" tokens' logits. Consider lowering the
  1885. `bias` if the text generation quality degrades. Recommended values are in the
  1886. range of [0.5, 2.0]. Defaults to 2.0.
  1887. hashing_key (`int`, optional, *optional*, defaults to 15485863):
  1888. Key used for hashing. If you deploy this watermark, we advise using another private key.
  1889. Defaults to 15485863 (the millionth prime).
  1890. seeding_scheme (`str`, optional, *optional*, defaults to `"lefthash"`):
  1891. The seeding scheme used for selecting "green" tokens. Accepts values:
  1892. - "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from paper)
  1893. - "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from paper)
  1894. The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash".
  1895. The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust.
  1896. context_width (`int`, *optional*, defaults to 1):
  1897. The number of previous tokens to use when setting the seed.
  1898. Examples:
  1899. ```python
  1900. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkingConfig
  1901. >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1902. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1903. >>> inputs = tokenizer(["Alice and Bob are"], return_tensors="pt")
  1904. >>> # normal generation
  1905. >>> out = model.generate(inputs["input_ids"], max_length=20, do_sample=False)
  1906. >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
  1907. 'Alice and Bob are both in the same room.\n\n"I\'m not sure if you\'re'
  1908. >>> # watermarked generation
  1909. >>> watermarking_config = WatermarkingConfig(bias=2.5, context_width=2, seeding_scheme="selfhash")
  1910. >>> out = model.generate(inputs["input_ids"], watermarking_config=watermarking_config, max_length=20, do_sample=False)
  1911. >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
  1912. 'Alice and Bob are both still alive and well and the story is pretty much a one-hour adventure'
  1913. >>> # to detect watermarked text use the WatermarkDetector class
  1914. >>> from transformers import WatermarkDetector
  1915. >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config= watermarking_config)
  1916. >>> detection_preds = detector(out)
  1917. >>> detection_preds
  1918. array([ True])
  1919. ```
  1920. """
  1921. def __init__(
  1922. self,
  1923. vocab_size,
  1924. device,
  1925. greenlist_ratio: float = 0.25,
  1926. bias: float = 2.0,
  1927. hashing_key: int = 15485863,
  1928. seeding_scheme: str = "lefthash",
  1929. context_width: int = 1,
  1930. ):
  1931. if seeding_scheme not in ["selfhash", "lefthash"]:
  1932. raise ValueError(f"seeding_scheme has to be one of [`selfhash`, `lefthash`], but found {seeding_scheme}")
  1933. if greenlist_ratio >= 1.0 or greenlist_ratio <= 0.0:
  1934. raise ValueError(
  1935. f"greenlist_ratio has be in range between 0.0 and 1.0, exclusively. but found {greenlist_ratio}"
  1936. )
  1937. self.vocab_size = vocab_size
  1938. self.greenlist_size = int(self.vocab_size * greenlist_ratio)
  1939. self.bias = bias
  1940. self.seeding_scheme = seeding_scheme
  1941. self.rng = torch.Generator(device=device)
  1942. self.hash_key = hashing_key
  1943. self.context_width = context_width
  1944. self.rng.manual_seed(hashing_key)
  1945. self.table_size = 1_000_003
  1946. self.fixed_table = torch.randperm(self.table_size, generator=self.rng, device=device)
  1947. def set_seed(self, input_seq: torch.LongTensor):
  1948. input_seq = input_seq[-self.context_width :]
  1949. if self.seeding_scheme == "selfhash":
  1950. a = self.fixed_table[input_seq % self.table_size] + 1
  1951. b = self.fixed_table[input_seq[-1] % self.table_size] + 1
  1952. seed = (self.hash_key * a * b).min().item()
  1953. else:
  1954. seed = self.hash_key * input_seq[-1].item()
  1955. self.rng.manual_seed(seed % (2**64 - 1))
  1956. def _get_greenlist_ids(self, input_seq: torch.LongTensor) -> torch.LongTensor:
  1957. self.set_seed(input_seq)
  1958. vocab_permutation = torch.randperm(self.vocab_size, device=input_seq.device, generator=self.rng)
  1959. greenlist_ids = vocab_permutation[: self.greenlist_size]
  1960. return greenlist_ids
  1961. def _score_rejection_sampling(self, input_seq: torch.LongTensor, scores: torch.FloatTensor) -> torch.LongTensor:
  1962. """
  1963. Generate greenlist based on current candidate next token. Reject and move on if necessary.
  1964. Runs for a fixed number of steps only for efficiency, since the methods is not batched.
  1965. """
  1966. final_greenlist = []
  1967. _, greedy_predictions = scores.sort(dim=-1, descending=True)
  1968. # 40 is an arbitrary number chosen to save compute and not run for long (taken from orig repo)
  1969. for i in range(40):
  1970. greenlist_ids = self._get_greenlist_ids(torch.cat([input_seq, greedy_predictions[i, None]], dim=-1))
  1971. if greedy_predictions[i] in greenlist_ids:
  1972. final_greenlist.append(greedy_predictions[i])
  1973. return torch.tensor(final_greenlist, device=input_seq.device)
  1974. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  1975. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  1976. if input_ids.shape[-1] < self.context_width:
  1977. logger.warning(
  1978. f"`input_ids` should have at least `{self.context_width}` tokens but has {input_ids.shape[-1]}. "
  1979. "The seeding will be skipped for this generation step!"
  1980. )
  1981. return scores
  1982. scores_processed = scores.clone()
  1983. for b_idx, input_seq in enumerate(input_ids):
  1984. if self.seeding_scheme == "selfhash":
  1985. greenlist_ids = self._score_rejection_sampling(input_seq, scores[b_idx])
  1986. else:
  1987. greenlist_ids = self._get_greenlist_ids(input_seq)
  1988. scores_processed[b_idx, greenlist_ids] = scores_processed[b_idx, greenlist_ids] + self.bias
  1989. return scores_processed
  1990. class SynthIDTextWatermarkState:
  1991. """SynthID watermarking state."""
  1992. def __init__(
  1993. self,
  1994. batch_size: int,
  1995. ngram_len: int,
  1996. context_history_size: int,
  1997. device: torch.device,
  1998. ):
  1999. """Initializes the state.
  2000. Args:
  2001. batch_size (`int`): Batch size.
  2002. ngram_len (`int`): Ngram length.
  2003. context_history_size (`int`): Size of the tensor to keep track of seen contexts.
  2004. device (`int`): Device to use.
  2005. """
  2006. self.context = torch.zeros(
  2007. (batch_size, ngram_len - 1),
  2008. dtype=torch.int64,
  2009. device=device,
  2010. )
  2011. self.context_history = torch.zeros(
  2012. (batch_size, context_history_size),
  2013. dtype=torch.int64,
  2014. device=device,
  2015. )
  2016. self.num_calls = 0
  2017. class SynthIDTextWatermarkLogitsProcessor(LogitsProcessor):
  2018. r"""
  2019. Logits processor that implements watermarking techniques for text generation models.
  2020. This class facilitates the application of SynthID text watermarking, a method for embedding imperceptible signals
  2021. into generated text to aid in detecting synthetic content. It operates by subtly manipulating the probabilities of
  2022. token selection during text generation in a manner that can be reliably recovered later for verification.
  2023. Key Features:
  2024. * **State Management:** Maintains internal state to track token sequences and generate watermarking keys
  2025. dynamically.
  2026. * **Key Generation:** Computes hashes based on token sequences and watermarking parameters to create unique keys
  2027. for each position.
  2028. * **G-Value Sampling:** Employs a pre-computed sampling table to sample watermarking values (g-values) based on
  2029. the generated keys.
  2030. * **Score Adjustment:** Applies calculated g-values to modify token probabilities during generation, embedding the
  2031. watermark.
  2032. * **Context Repetition Handling:** Incorporates logic to avoid watermarking tokens in repeated contexts,
  2033. preserving naturalness.
  2034. * **EOS Token Masking:** Supports masking end-of-sentence tokens to prevent their inclusion in watermarking
  2035. calculations.
  2036. * **Utility Functions:** Provides functions to compute g-values directly, check for context repetition, create
  2037. EOS token masks, and estimate expected mean g-values.
  2038. Refer to paper url: https://www.nature.com/articles/s41586-024-08025-4 for more details around this.
  2039. Args:
  2040. ngram_len (`int`):
  2041. Ngram length.
  2042. keys (`List[int]`):
  2043. A sequence of watermarking keys, one for each depth.
  2044. sampling_table_size (`int`):
  2045. Size of the sampling table.
  2046. sampling_table_seed (`int`):
  2047. Random seed to generate the sampling table.
  2048. context_history_size (`int`):
  2049. Size of the tensor to keep track of seen contexts.
  2050. device (`torch.device`):
  2051. Device to use.
  2052. skip_first_ngram_calls (`bool`, *optional*, defaults to `False`):
  2053. Whether to skip first ngram calls.
  2054. debug_mode (`bool`, optional, *optional*, defaults to `False`):
  2055. Logits are modified to uniform one got before watermarking modification is applied. This is to test the
  2056. implementation.
  2057. Examples:
  2058. ```python
  2059. >>> from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig
  2060. >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b-it')
  2061. >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b-it')
  2062. >>> # SynthID Text configuration
  2063. >>> watermarking_config = SynthIDTextWatermarkingConfig(
  2064. ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57],
  2065. ... ngram_len=5,
  2066. ... )
  2067. >>> # Generation with watermarking
  2068. >>> tokenized_prompts = tokenizer(["your prompts here"])
  2069. >>> output_sequences = model.generate(
  2070. ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True,
  2071. ... )
  2072. >>> watermarked_text = tokenizer.batch_decode(output_sequences)
  2073. ```
  2074. """
  2075. def __init__(
  2076. self,
  2077. ngram_len: int,
  2078. keys: List[int],
  2079. sampling_table_size: int,
  2080. sampling_table_seed: int,
  2081. context_history_size: int,
  2082. device: torch.device,
  2083. skip_first_ngram_calls: bool = False,
  2084. debug_mode: bool = False,
  2085. ):
  2086. self.ngram_len = ngram_len
  2087. self.keys = torch.tensor(keys, device=device)
  2088. generator = torch.Generator(device=device).manual_seed(sampling_table_seed)
  2089. # A random sampling table is pre-computed and modulo table size is applied to map from a hash of ngram keys to
  2090. # g values, this is similar to the hashtable implementation used in
  2091. # https://github.com/facebookresearch/three_bricks. We note that the hashing employed in this repository is
  2092. # different from that used to watermark the Gemini App, and hence the detectors trained based on the
  2093. # hashing in this repository will not transfer to text generated by the Gemini App.
  2094. self.sampling_table = torch.randint(
  2095. low=0,
  2096. high=2,
  2097. size=(sampling_table_size,),
  2098. generator=generator,
  2099. device=device,
  2100. )
  2101. self.context_history_size = context_history_size
  2102. self.device = device
  2103. self.state = None
  2104. self.skip_first_ngram_calls = skip_first_ngram_calls
  2105. self.debug_mode = debug_mode
  2106. def _init_state(self, batch_size: int):
  2107. """Initializes the state."""
  2108. self.state = SynthIDTextWatermarkState(
  2109. batch_size=batch_size,
  2110. ngram_len=self.ngram_len,
  2111. context_history_size=self.context_history_size,
  2112. device=self.device,
  2113. )
  2114. def update_scores(self, scores: torch.FloatTensor, g_values: torch.FloatTensor) -> torch.FloatTensor:
  2115. """Updates scores using the g values.
  2116. We assume that the scores are in the log space.
  2117. Args:
  2118. scores (`torch.FloatTensor`): Scores (batch_size, vocab_size).
  2119. g_values (`torch.FloatTensor`): G valus (batch_size, vocab_size, depth).
  2120. Returns:
  2121. Updated scores (batch_size, vocab_size).
  2122. """
  2123. _, _, depth = g_values.shape
  2124. probs = torch.softmax(scores, dim=1)
  2125. for i in range(depth):
  2126. g_values_at_depth = g_values[:, :, i]
  2127. g_mass_at_depth = (g_values_at_depth * probs).sum(axis=1, keepdims=True)
  2128. probs = probs * (1 + g_values_at_depth - g_mass_at_depth)
  2129. log_probs = torch.log(probs)
  2130. log_probs = torch.where(torch.isfinite(log_probs), log_probs, torch.finfo(log_probs.dtype).min)
  2131. return log_probs
  2132. @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
  2133. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  2134. self._check_input_ids_shape(input_ids)
  2135. batch_size, vocab_size = scores.shape
  2136. if self.debug_mode:
  2137. scores = torch.ones_like(scores)
  2138. # Currently indices is just a arange to compute watermarking on the desnse logits.
  2139. all_indices = torch.stack([torch.arange(vocab_size, device=self.device) for _ in range(batch_size)])
  2140. if self.state is None:
  2141. # Initialize watermarking state if it does not exist.
  2142. self._init_state(batch_size)
  2143. else:
  2144. # Append last input id (which is the input id added in last call) to the
  2145. # previous context so we have the context to be used for current
  2146. # watermarking.
  2147. self.state.context = torch.concat(
  2148. (self.state.context, input_ids[:, -1:]),
  2149. dim=1,
  2150. )
  2151. self.state.context = self.state.context[:, 1:]
  2152. if self.state is None:
  2153. raise ValueError("self.state can't be None! Call `self._init_state` to initialize the state.")
  2154. self.state.num_calls += 1
  2155. # Don't watermark the first ngram_len - 1 tokens if set.
  2156. if self.skip_first_ngram_calls and self.state.num_calls < self.ngram_len:
  2157. return scores
  2158. # 2. Generate random keys for each ngram key combination.
  2159. ngram_keys, hash_result_with_just_context = self._compute_keys(self.state.context, all_indices)
  2160. # ngram_keys shape [batch_size, top_k, depth]
  2161. # 3. Sample g values.
  2162. g_values = self.sample_g_values(ngram_keys)
  2163. # g_values shape [batch_size, top_k, depth]
  2164. # 4. Modify scores.
  2165. updated_scores = self.update_scores(scores, g_values)
  2166. # updated scores shape [batch_size, top_k]
  2167. # 5. Check if the current watermarking context was previously used, if yes skip watermarking.
  2168. hash_result_with_just_context = hash_result_with_just_context[:, None]
  2169. is_repeated_context = (self.state.context_history == hash_result_with_just_context).any(
  2170. dim=1,
  2171. keepdim=True,
  2172. )
  2173. self.state.context_history = torch.concat(
  2174. (hash_result_with_just_context, self.state.context_history),
  2175. dim=1,
  2176. )[:, :-1]
  2177. updated_watermarked_scores = torch.where(
  2178. is_repeated_context,
  2179. input=scores,
  2180. other=updated_scores,
  2181. )
  2182. return updated_watermarked_scores
  2183. def accumulate_hash(
  2184. self,
  2185. current_hash: torch.LongTensor,
  2186. data: torch.LongTensor,
  2187. multiplier: int = 6364136223846793005,
  2188. increment: int = 1,
  2189. ) -> torch.LongTensor:
  2190. """
  2191. Accumulate hash of data on current hash.
  2192. Method uses adapted linear congruential generator with newlib/musl parameters.
  2193. This function has following property -
  2194. f(x, data[T]) = f(f(x, data[:T - 1]), data[T])
  2195. This function expects current_hash.shape and data.shape[:-1] to
  2196. match/broadcastable.
  2197. Args:
  2198. current_hash (`torch.LongTensor`):
  2199. (shape,)
  2200. data (`torch.LongTensor`):
  2201. (shape, tensor_len)
  2202. multiplier (`int`, optional, *optional*, defaults to 6364136223846793005):
  2203. multiplier of linear congruential generator
  2204. increment (`int`, optional, *optional*, defaults to 1):
  2205. increment of linear congruential generator
  2206. Returns:
  2207. updated hash (shape,)
  2208. """
  2209. for i in range(data.shape[-1]):
  2210. current_hash = torch.add(current_hash, data[..., i])
  2211. current_hash = torch.mul(current_hash, multiplier)
  2212. current_hash = torch.add(current_hash, increment)
  2213. return current_hash
  2214. def compute_ngram_keys(self, ngrams: torch.LongTensor) -> torch.LongTensor:
  2215. """Computes random keys for each ngram and depth.
  2216. Args:
  2217. ngrams (`torch.LongTensor`):
  2218. Ngrams (batch_size, num_ngrams, ngram_len).
  2219. Returns:
  2220. ngram keys (batch_size, num_ngrams, depth).
  2221. """
  2222. if len(ngrams.shape) != 3:
  2223. raise ValueError(
  2224. "Ngrams should be of shape (batch_size, num_ngrams, ngram_len), but" f" is {ngrams.shape}"
  2225. )
  2226. if ngrams.shape[2] != self.ngram_len:
  2227. raise ValueError(
  2228. "Ngrams should be of shape (batch_size, num_ngrams, ngram_len),"
  2229. f" where ngram_len is {self.ngram_len}, but is {ngrams.shape}"
  2230. )
  2231. batch_size, _, _ = ngrams.shape
  2232. hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
  2233. # hash_result shape [batch_size,]
  2234. # ngrams shape [batch_size, num_ngrams, ngram_len]
  2235. hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 1), out_dims=1)(hash_result, ngrams)
  2236. # hash_result shape [batch_size, num_ngrams]
  2237. keys = self.keys[None, None, :, None]
  2238. # hash_result shape [batch_size, num_ngrams]
  2239. # keys shape [1, 1, depth, 1]
  2240. hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 2), out_dims=2)(hash_result, keys)
  2241. # hash_result shape [batch_size, num_ngrams, depth]
  2242. return hash_result
  2243. def _compute_keys(
  2244. self, n_minus_1_grams: torch.LongTensor, indices: torch.LongTensor
  2245. ) -> Tuple[torch.LongTensor, torch.LongTensor]:
  2246. """Computes random keys for each ngram and depth.
  2247. Args:
  2248. n_minus_1_grams (`torch.LongTensor`):
  2249. Ngrams (batch_size, ngram_len - 1).
  2250. indices (`torch.LongTensor`):
  2251. indices of the continuations (batch_size, num_indices)
  2252. Returns:
  2253. Ngram keys (batch_size, num_indices, depth).
  2254. """
  2255. batch_size, _ = n_minus_1_grams.shape
  2256. hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
  2257. # First hash n_minus_1 gram, for each batch entry we have a single
  2258. # n_minus_1 gram context.
  2259. # hash_result shape [batch_size]
  2260. # n_minus_1_gram shape [batch_size, ngram_len - 1]
  2261. hash_result_with_just_context = self.accumulate_hash(hash_result, n_minus_1_grams)
  2262. # hash_result shape [batch_size,]
  2263. # Indices is of shape [batch_size, num_indices], so we make it
  2264. # [batch_size, num_indices, 1] so we can vmap over num_indices dim.
  2265. hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 1), out_dims=1)(
  2266. hash_result_with_just_context, indices[:, :, None]
  2267. )
  2268. # hash_result shape [batch_size, num_indices]
  2269. # Basically we have a hash for each batch entry and each indices
  2270. # Now we add watermarking keys to this hash.
  2271. # keys are of shape [depth,]
  2272. # We add batch, num_indices and data dimension to this making it
  2273. # [1, 1, depth, 1].
  2274. # So we can vmap over the depth dimension for compute_hash
  2275. keys = self.keys[None, None, :, None]
  2276. hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 2), out_dims=2)(hash_result, keys)
  2277. # hash_result shape should be [batch_size, num_indices, depth]
  2278. return hash_result, hash_result_with_just_context
  2279. def sample_g_values(self, ngram_keys: torch.LongTensor) -> torch.LongTensor:
  2280. """
  2281. Samples g values from Bernoulli distribution.
  2282. It is not possible to pass random keys in a vectorized way in torch. Instead
  2283. we pre-compute a random sampling table, and use apply modulo table size to
  2284. map from ngram keys (int64) to g values.
  2285. Args:
  2286. ngram_keys (`torch.LongTensor`):
  2287. Random keys (batch_size, num_ngrams, depth).
  2288. Returns:
  2289. G values (batch_size, num_ngrams, depth).
  2290. """
  2291. (sampling_table_size,) = self.sampling_table.shape
  2292. sampling_table = self.sampling_table.reshape((1, 1, sampling_table_size))
  2293. ngram_keys = ngram_keys % sampling_table_size
  2294. return torch.take_along_dim(sampling_table, indices=ngram_keys, dim=2)
  2295. def _check_input_ids_shape(self, input_ids: torch.LongTensor):
  2296. """Checks the shape of input ids."""
  2297. if len(input_ids.shape) != 2:
  2298. raise ValueError("Input ids should be of shape (batch_size, input_len), but is" f" {input_ids.shape}")
  2299. def compute_g_values(self, input_ids: torch.LongTensor) -> torch.LongTensor:
  2300. """
  2301. Computes g values for each ngram from the given sequence of tokens.
  2302. Args:
  2303. input_ids (`torch.LongTensor`):
  2304. Input token ids (batch_size, input_len).
  2305. Returns:
  2306. G values (batch_size, input_len - (ngram_len - 1), depth).
  2307. """
  2308. self._check_input_ids_shape(input_ids)
  2309. ngrams = input_ids.unfold(dimension=1, size=self.ngram_len, step=1)
  2310. ngram_keys = self.compute_ngram_keys(ngrams)
  2311. return self.sample_g_values(ngram_keys)
  2312. def compute_context_repetition_mask(self, input_ids: torch.LongTensor) -> torch.LongTensor:
  2313. """
  2314. Computes repetition mask.
  2315. 0 and 1 stand for repeated and not repeated context n-1 grams respectively.
  2316. Args:
  2317. input_ids (`torch.LongTensor`):
  2318. Input token ids (batch_size, input_len).
  2319. Returns:
  2320. Repetitions mask (batch_size, input_len - (ngram_len - 1)).
  2321. """
  2322. self._check_input_ids_shape(input_ids)
  2323. batch_size, _ = input_ids.shape
  2324. state = SynthIDTextWatermarkState(
  2325. batch_size=batch_size,
  2326. ngram_len=self.ngram_len,
  2327. context_history_size=self.context_history_size,
  2328. device=self.device,
  2329. )
  2330. contexts = input_ids[:, :-1].unfold(
  2331. dimension=1,
  2332. size=self.ngram_len - 1,
  2333. step=1,
  2334. )
  2335. _, num_contexts, _ = contexts.shape
  2336. are_repeated_contexts = []
  2337. for i in range(num_contexts):
  2338. context = contexts[:, i, :]
  2339. hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
  2340. context_hash = self.accumulate_hash(hash_result, context)[:, None]
  2341. is_repeated_context = (state.context_history == context_hash).any(
  2342. dim=1,
  2343. keepdim=True,
  2344. )
  2345. are_repeated_contexts.append(is_repeated_context)
  2346. state.context_history = torch.concat(
  2347. (context_hash, state.context_history),
  2348. dim=1,
  2349. )[:, :-1]
  2350. are_repeated_contexts = torch.concat(are_repeated_contexts, dim=1)
  2351. return torch.logical_not(are_repeated_contexts)
  2352. def compute_eos_token_mask(self, input_ids: torch.LongTensor, eos_token_id: int) -> torch.LongTensor:
  2353. """
  2354. Computes repetitions mask.
  2355. 1 stands for ngrams that don't contain EOS tokens and vice versa.
  2356. Args:
  2357. input_ids (`torch.LongTensor`):
  2358. Input token ids (batch_size, input_len).
  2359. eos_token_id (`int`):
  2360. EOS token ID.
  2361. Returns:
  2362. EOS token mask (batch_size, input_len).
  2363. """
  2364. self._check_input_ids_shape(input_ids)
  2365. noneos_masks = []
  2366. all_eos_equated = input_ids == eos_token_id
  2367. for eos_equated in all_eos_equated:
  2368. nonzero_idx = torch.nonzero(eos_equated)
  2369. noneos_mask = torch.ones_like(eos_equated)
  2370. if nonzero_idx.shape[0] != 0:
  2371. noneos_mask[nonzero_idx[0][0] :] = 0
  2372. noneos_masks.append(noneos_mask)
  2373. return torch.stack(noneos_masks, dim=0)
  2374. def expected_mean_g_value(self, vocab_size: int, coinflip_prob: float = 0.5) -> float:
  2375. """
  2376. Compute expected mean g-value after watermarking, assuming uniform LM dist.
  2377. This is the theoretical expected value for single-layer watermarking.
  2378. Args:
  2379. vocab_size (`int`):
  2380. The size of the vocabulary.
  2381. coinflip_prob arg_name (`float`, *optional*, defaults to 0.5):
  2382. Probability of 1 in boolean prf.
  2383. Returns:
  2384. The expected mean g-value for watermarked text.
  2385. """
  2386. return coinflip_prob + coinflip_prob * (1 - coinflip_prob) * (1 - (1 / vocab_size))