tf_utils.py 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import copy
  17. import inspect
  18. import warnings
  19. from dataclasses import dataclass
  20. from typing import Any, Optional, Union
  21. import numpy as np
  22. import tensorflow as tf
  23. from tensorflow.compiler.tf2xla.python.xla import dynamic_update_slice
  24. from ..modeling_tf_outputs import TFCausalLMOutputWithPast, TFSeq2SeqLMOutput
  25. from ..models.auto import (
  26. TF_MODEL_FOR_CAUSAL_LM_MAPPING,
  27. TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
  28. TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
  29. TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
  30. )
  31. from ..tf_utils import shape_list, stable_softmax
  32. from ..utils import ModelOutput, logging
  33. from .configuration_utils import GenerationConfig
  34. from .tf_logits_process import (
  35. TFForcedBOSTokenLogitsProcessor,
  36. TFForcedEOSTokenLogitsProcessor,
  37. TFForceTokensLogitsProcessor,
  38. TFLogitsProcessorList,
  39. TFMinLengthLogitsProcessor,
  40. TFNoBadWordsLogitsProcessor,
  41. TFNoRepeatNGramLogitsProcessor,
  42. TFRepetitionPenaltyLogitsProcessor,
  43. TFSuppressTokensAtBeginLogitsProcessor,
  44. TFSuppressTokensLogitsProcessor,
  45. TFTemperatureLogitsWarper,
  46. TFTopKLogitsWarper,
  47. TFTopPLogitsWarper,
  48. )
  49. logger = logging.get_logger(__name__)
  50. @dataclass
  51. class TFGreedySearchDecoderOnlyOutput(ModelOutput):
  52. """
  53. Base class for outputs of decoder-only generation models using greedy search.
  54. Args:
  55. sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  56. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  57. if all batches finished early due to the `eos_token_id`.
  58. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  59. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  60. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  61. generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  62. attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  63. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  64. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  65. hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  66. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  67. `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
  68. """
  69. sequences: Optional[tf.Tensor] = None
  70. scores: Optional[tuple[tf.Tensor]] = None
  71. attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  72. hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  73. @dataclass
  74. class TFGreedySearchEncoderDecoderOutput(ModelOutput):
  75. """
  76. Base class for outputs of encoder-decoder generation models using greedy search. Hidden states and attention
  77. weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
  78. encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
  79. Args:
  80. sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  81. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  82. if all batches finished early due to the `eos_token_id`.
  83. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  84. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  85. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  86. generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  87. encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  88. Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
  89. sequence_length)`.
  90. encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  91. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  92. `(batch_size, sequence_length, hidden_size)`.
  93. decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  94. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  95. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  96. cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  97. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  98. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  99. decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  100. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  101. `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
  102. """
  103. sequences: Optional[tf.Tensor] = None
  104. scores: Optional[tuple[tf.Tensor]] = None
  105. encoder_attentions: Optional[tuple[tf.Tensor]] = None
  106. encoder_hidden_states: Optional[tuple[tf.Tensor]] = None
  107. decoder_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  108. cross_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  109. decoder_hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  110. @dataclass
  111. class TFSampleDecoderOnlyOutput(ModelOutput):
  112. """
  113. Base class for outputs of decoder-only generation models using sampling.
  114. Args:
  115. sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  116. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  117. if all batches finished early due to the `eos_token_id`.
  118. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  119. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  120. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  121. generated token), with each tensor of shape `(batch_size*num_return_sequences, config.vocab_size)`.
  122. attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  123. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  124. `tf.Tensor` of shape `(num_return_sequences*batch_size, num_heads, generated_length, sequence_length)`.
  125. hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  126. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  127. `tf.Tensor` of shape `(num_return_sequences*batch_size, generated_length, hidden_size)`.
  128. """
  129. sequences: Optional[tf.Tensor] = None
  130. scores: Optional[tuple[tf.Tensor]] = None
  131. attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  132. hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  133. @dataclass
  134. class TFSampleEncoderDecoderOutput(ModelOutput):
  135. """
  136. Base class for outputs of encoder-decoder generation models using sampling. Hidden states and attention weights of
  137. the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states
  138. attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
  139. Args:
  140. sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  141. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  142. if all batches finished early due to the `eos_token_id`.
  143. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  144. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  145. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  146. generated token), with each tensor of shape `(batch_size*num_return_sequences, config.vocab_size)`.
  147. encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  148. Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size*num_return_sequences,
  149. num_heads, sequence_length, sequence_length)`.
  150. encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  151. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  152. `(batch_size*num_return_sequences, sequence_length, hidden_size)`.
  153. decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  154. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  155. `tf.Tensor` of shape `(batch_size*num_return_sequences, num_heads, generated_length, sequence_length)`.
  156. cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  157. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  158. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  159. decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  160. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  161. `tf.Tensor` of shape `(batch_size*num_return_sequences, generated_length, hidden_size)`.
  162. """
  163. sequences: Optional[tf.Tensor] = None
  164. scores: Optional[tuple[tf.Tensor]] = None
  165. encoder_attentions: Optional[tuple[tf.Tensor]] = None
  166. encoder_hidden_states: Optional[tuple[tf.Tensor]] = None
  167. decoder_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  168. cross_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  169. decoder_hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  170. @dataclass
  171. class TFBeamSearchDecoderOnlyOutput(ModelOutput):
  172. """
  173. Base class for outputs of decoder-only generation models using beam search.
  174. Args:
  175. sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  176. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  177. if all batches finished early due to the `eos_token_id`.
  178. sequences_scores (`tf.Tensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  179. Final beam scores of the generated `sequences`.
  180. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  181. Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
  182. softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
  183. beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
  184. with each tensor of shape `(batch_size*num_beams*num_return_sequences, config.vocab_size)`.
  185. beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  186. Beam indices of generated token id at each generation step. `tf.Tensor` of shape
  187. `(batch_size*num_return_sequences, sequence_length)`.
  188. attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  189. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  190. `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
  191. hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  192. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  193. `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  194. """
  195. sequences: Optional[tf.Tensor] = None
  196. sequences_scores: Optional[tf.Tensor] = None
  197. scores: Optional[tuple[tf.Tensor]] = None
  198. beam_indices: Optional[tf.Tensor] = None
  199. attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  200. hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  201. @dataclass
  202. class TFBeamSearchEncoderDecoderOutput(ModelOutput):
  203. """
  204. Base class for outputs of encoder-decoder generation models using beam search. Hidden states and attention weights
  205. of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states
  206. attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
  207. Args:
  208. sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  209. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  210. if all batches finished early due to the `eos_token_id`.
  211. sequences_scores (`tf.Tensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  212. Final beam scores of the generated `sequences`.
  213. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  214. Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
  215. softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
  216. beam. `Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
  217. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  218. beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  219. Beam indices of generated token id at each generation step. `tf.Tensor` of shape
  220. `(batch_size*num_return_sequences, sequence_length)`.
  221. encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  222. Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
  223. sequence_length)`.
  224. encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  225. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  226. `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
  227. decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  228. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  229. `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
  230. sequence_length)`.
  231. cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  232. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  233. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  234. decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  235. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  236. `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
  237. """
  238. sequences: Optional[tf.Tensor] = None
  239. sequences_scores: Optional[tf.Tensor] = None
  240. scores: Optional[tuple[tf.Tensor]] = None
  241. beam_indices: Optional[tf.Tensor] = None
  242. encoder_attentions: Optional[tuple[tf.Tensor]] = None
  243. encoder_hidden_states: Optional[tuple[tf.Tensor]] = None
  244. decoder_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  245. cross_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  246. decoder_hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  247. @dataclass
  248. class TFBeamSampleDecoderOnlyOutput(ModelOutput):
  249. """
  250. Base class for outputs of decoder-only generation models using beam sample.
  251. Args:
  252. sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
  253. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  254. if all batches finished early due to the `eos_token_id`.
  255. sequences_scores (`tf.Tensor` of shape `(batch_size * num_return_sequence)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  256. Final beam scores of the generated `sequences`.
  257. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  258. Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
  259. softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
  260. beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
  261. with each tensor of shape `(batch_size*num_beams*num_return_sequences, config.vocab_size)`.
  262. beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  263. Beam indices of generated token id at each generation step. `tf.Tensor` of shape
  264. `(batch_size*num_return_sequences, sequence_length)`.
  265. attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  266. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  267. `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
  268. hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  269. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  270. `tf.Tensor` of shape `(batch_size*num_beams, generated_length, hidden_size)`.
  271. """
  272. sequences: Optional[tf.Tensor] = None
  273. sequences_scores: Optional[tf.Tensor] = None
  274. scores: Optional[tuple[tf.Tensor]] = None
  275. beam_indices: Optional[tf.Tensor] = None
  276. attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  277. hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  278. @dataclass
  279. class TFBeamSampleEncoderDecoderOutput(ModelOutput):
  280. """
  281. Base class for outputs of encoder-decoder generation models using beam sampling. Hidden states and attention
  282. weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
  283. encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
  284. Args:
  285. sequences (`tf.Tensor` of shape `(batch_size*num_beams, sequence_length)`):
  286. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  287. if all batches finished early due to the `eos_token_id`.
  288. sequences_scores (`tf.Tensor` of shape `(batch_size * num_return_sequence)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  289. Final beam scores of the generated `sequences`.
  290. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  291. Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
  292. softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
  293. beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
  294. with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  295. beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  296. Beam indices of generated token id at each generation step. `tf.Tensor` of shape
  297. `(batch_size*num_return_sequences, sequence_length)`.
  298. encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  299. Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
  300. sequence_length)`.
  301. encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  302. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  303. `(batch_size*num_beams, sequence_length, hidden_size)`.
  304. decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  305. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  306. `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
  307. cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  308. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  309. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  310. decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  311. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  312. `tf.Tensor` of shape `(batch_size*num_beams, generated_length, hidden_size)`.
  313. """
  314. sequences: Optional[tf.Tensor] = None
  315. sequences_scores: Optional[tf.Tensor] = None
  316. scores: Optional[tuple[tf.Tensor]] = None
  317. beam_indices: Optional[tf.Tensor] = None
  318. encoder_attentions: Optional[tuple[tf.Tensor]] = None
  319. encoder_hidden_states: Optional[tuple[tf.Tensor]] = None
  320. decoder_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  321. cross_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  322. decoder_hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  323. @dataclass
  324. class TFContrastiveSearchDecoderOnlyOutput(ModelOutput):
  325. """
  326. Base class for outputs of decoder-only generation models using contrastive search.
  327. Args:
  328. sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  329. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  330. if all batches finished early due to the `eos_token_id`.
  331. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  332. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  333. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  334. generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  335. attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  336. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  337. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  338. hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  339. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  340. `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
  341. """
  342. sequences: Optional[tf.Tensor] = None
  343. scores: Optional[tuple[tf.Tensor]] = None
  344. attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  345. hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  346. @dataclass
  347. class TFContrastiveSearchEncoderDecoderOutput(ModelOutput):
  348. """
  349. Base class for outputs of encoder-decoder generation models using contrastive search. Hidden states and attention
  350. weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
  351. encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
  352. Args:
  353. sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  354. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
  355. if all batches finished early due to the `eos_token_id`.
  356. scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
  357. Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
  358. at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
  359. generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
  360. encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  361. Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
  362. sequence_length)`.
  363. encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  364. Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
  365. `(batch_size, sequence_length, hidden_size)`.
  366. decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  367. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  368. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  369. cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
  370. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  371. `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
  372. decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  373. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
  374. `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
  375. """
  376. sequences: Optional[tf.Tensor] = None
  377. scores: Optional[tuple[tf.Tensor]] = None
  378. encoder_attentions: Optional[tuple[tf.Tensor]] = None
  379. encoder_hidden_states: Optional[tuple[tf.Tensor]] = None
  380. decoder_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  381. cross_attentions: Optional[tuple[tuple[tf.Tensor]]] = None
  382. decoder_hidden_states: Optional[tuple[tuple[tf.Tensor]]] = None
  383. TFGreedySearchOutput = Union[TFGreedySearchEncoderDecoderOutput, TFGreedySearchDecoderOnlyOutput]
  384. TFSampleOutput = Union[TFSampleEncoderDecoderOutput, TFSampleDecoderOnlyOutput]
  385. TFBeamSearchOutput = Union[TFBeamSearchEncoderDecoderOutput, TFBeamSearchDecoderOnlyOutput]
  386. TFBeamSampleOutput = Union[TFBeamSampleEncoderDecoderOutput, TFBeamSampleDecoderOnlyOutput]
  387. TFContrastiveSearchOutput = Union[TFContrastiveSearchEncoderDecoderOutput, TFContrastiveSearchDecoderOnlyOutput]
  388. TFGenerateOutput = Union[
  389. TFGreedySearchOutput, TFSampleOutput, TFBeamSearchOutput, TFBeamSampleOutput, TFContrastiveSearchOutput
  390. ]
  391. class TFGenerationMixin:
  392. """
  393. A class containing all of the functions supporting generation, to be used as a mixin in [`TFPreTrainedModel`].
  394. The class exposes [`~generation.TFGenerationMixin.generate`], which can be used for:
  395. - *greedy decoding* by calling [`~generation.TFGenerationMixin.greedy_search`] if `num_beams=1` and
  396. `do_sample=False`
  397. - *contrastive search* by calling [`~generation.TFGenerationMixin.contrastive_search`] if `penalty_alpha>0` and
  398. `top_k>1`
  399. - *multinomial sampling* by calling [`~generation.TFGenerationMixin.sample`] if `num_beams=1` and
  400. `do_sample=True`
  401. - *beam-search decoding* by calling [`~generation.TFGenerationMixin.beam_search`] if `num_beams>1`
  402. You do not need to call any of the above methods directly. Pass custom parameter values to 'generate' instead. To
  403. learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
  404. """
  405. _seed_generator = None
  406. @property
  407. def seed_generator(self):
  408. warnings.warn("`seed_generator` is deprecated and will be removed in a future version.", UserWarning)
  409. if self._seed_generator is None:
  410. self._seed_generator = tf.random.Generator.from_non_deterministic_state()
  411. return self._seed_generator
  412. supports_xla_generation = True
  413. def prepare_inputs_for_generation(self, *args, **kwargs):
  414. raise NotImplementedError(
  415. "A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
  416. )
  417. def compute_transition_scores(
  418. self,
  419. sequences: tf.Tensor,
  420. scores: tuple[tf.Tensor],
  421. beam_indices: Optional[tf.Tensor] = None,
  422. normalize_logits: bool = False,
  423. ) -> tf.Tensor:
  424. """
  425. Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
  426. used). This is a convenient method to quickly obtain the scores of the selected tokens at generation time.
  427. Parameters:
  428. sequences (`tf.Tensor`):
  429. The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
  430. shorter if all batches finished early due to the `eos_token_id`.
  431. scores (`tuple(tf.Tensor)`):
  432. Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
  433. of log probabilities of tokens conditioned on log softmax of previously generated tokens Tuple of
  434. `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token), with each
  435. tensor of shape `(batch_size*num_beams, config.vocab_size)`.
  436. beam_indices (`tf.Tensor`, *optional*):
  437. Beam indices of generated token id at each generation step. `tf.Tensor` of shape
  438. `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
  439. generate-time.
  440. normalize_logits (`bool`, *optional*, defaults to `False`):
  441. Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
  442. Return:
  443. `tf.Tensor`: A `tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
  444. the transition scores (logits)
  445. Examples:
  446. ```python
  447. >>> from transformers import GPT2Tokenizer, TFAutoModelForCausalLM
  448. >>> import numpy as np
  449. >>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
  450. >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  451. >>> tokenizer.pad_token_id = tokenizer.eos_token_id
  452. >>> inputs = tokenizer(["Today is"], return_tensors="tf")
  453. >>> # Example 1: Print the scores for each token generated with Greedy Search
  454. >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
  455. >>> transition_scores = model.compute_transition_scores(
  456. ... outputs.sequences, outputs.scores, normalize_logits=True
  457. ... )
  458. >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
  459. >>> # encoder-decoder models, like BART or T5.
  460. >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
  461. >>> generated_tokens = outputs.sequences[:, input_length:]
  462. >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
  463. ... # | token | token string | logits | probability
  464. ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
  465. | 262 | the | -1.414 | 24.33%
  466. | 1110 | day | -2.609 | 7.36%
  467. | 618 | when | -2.010 | 13.40%
  468. | 356 | we | -1.859 | 15.58%
  469. | 460 | can | -2.508 | 8.14%
  470. >>> # Example 2: Reconstruct the sequence scores from Beam Search
  471. >>> outputs = model.generate(
  472. ... **inputs,
  473. ... max_new_tokens=5,
  474. ... num_beams=4,
  475. ... num_return_sequences=4,
  476. ... return_dict_in_generate=True,
  477. ... output_scores=True,
  478. ... )
  479. >>> transition_scores = model.compute_transition_scores(
  480. ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
  481. ... )
  482. >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
  483. >>> # Tip: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
  484. >>> # use case, you might want to recompute it with `normalize_logits=True`.
  485. >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
  486. >>> length_penalty = model.generation_config.length_penalty
  487. >>> reconstructed_scores = np.sum(transition_scores, axis=1) / (output_length**length_penalty)
  488. >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
  489. True
  490. ```"""
  491. # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
  492. # to a beam search approach were the first (and only) beam is always selected
  493. if beam_indices is None:
  494. beam_indices = tf.tile(tf.expand_dims(tf.range(scores[0].shape[0]), axis=1), [1, len(scores)])
  495. # 2. reshape scores as [batch_size, vocab_size, # generation steps] with # generation steps being
  496. # seq_len - input_length
  497. scores = tf.transpose(tf.reshape(tf.stack(scores), (len(scores), -1)), (1, 0))
  498. scores = tf.reshape(scores, (-1, self.config.vocab_size, scores.shape[-1]))
  499. # 3. Optionally normalize the logits (across the vocab dimension)
  500. if normalize_logits:
  501. scores = tf.nn.log_softmax(scores, axis=1)
  502. # 4. cut beam_indices to longest beam length
  503. beam_indices_mask = beam_indices < 0
  504. max_beam_length = tf.math.reduce_max(
  505. tf.math.reduce_sum((1 - tf.cast(beam_indices_mask, dtype=tf.int32)), axis=-1)
  506. )
  507. beam_indices = beam_indices[:, -max_beam_length:]
  508. beam_indices_mask = beam_indices_mask[:, -max_beam_length:]
  509. # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
  510. beam_indices = tf.where(beam_indices_mask, 0, beam_indices)
  511. # 6. Define which indices contributed to scores
  512. cut_idx = sequences.shape[-1] - max_beam_length
  513. token_indices = sequences[:, cut_idx:]
  514. gen_step_idx = tf.broadcast_to(tf.range(scores.shape[-1]), token_indices.shape)
  515. indices = tf.stack([beam_indices, token_indices, gen_step_idx], axis=-1)
  516. # 7. Compute scores
  517. transition_scores = tf.gather_nd(scores, indices)
  518. # 8. Mask out transition_scores of beams that stopped early
  519. transition_scores = tf.where(beam_indices_mask, 0, transition_scores)
  520. return transition_scores
  521. def _validate_model_class(self):
  522. """
  523. Confirms that the model class is compatible with generation. If not, raises an exception that points to the
  524. right class to use.
  525. """
  526. if not self.can_generate():
  527. generate_compatible_mappings = [
  528. TF_MODEL_FOR_CAUSAL_LM_MAPPING,
  529. TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
  530. TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
  531. TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
  532. ]
  533. generate_compatible_classes = set()
  534. for model_mapping in generate_compatible_mappings:
  535. supported_models = model_mapping.get(type(self.config), default=None)
  536. if supported_models is not None:
  537. generate_compatible_classes.add(supported_models.__name__)
  538. exception_message = (
  539. f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
  540. "it doesn't have a language model head."
  541. )
  542. if generate_compatible_classes:
  543. exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
  544. raise TypeError(exception_message)
  545. def _validate_model_kwargs(self, model_kwargs: dict[str, Any]):
  546. """Validates model kwargs for generation. Generate argument typos will also be caught here."""
  547. # Excludes arguments that are handled before calling any model function
  548. if self.config.is_encoder_decoder:
  549. for key in ["decoder_input_ids"]:
  550. model_kwargs.pop(key, None)
  551. unused_model_args = []
  552. model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
  553. # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
  554. # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
  555. if "kwargs" in model_args or "model_kwargs" in model_args:
  556. model_args |= set(inspect.signature(self.call).parameters)
  557. for key, value in model_kwargs.items():
  558. if value is not None and key not in model_args:
  559. unused_model_args.append(key)
  560. if unused_model_args:
  561. raise ValueError(
  562. f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
  563. " generate arguments will also show up in this list)"
  564. )
  565. def generate(
  566. self,
  567. inputs: Optional[tf.Tensor] = None,
  568. generation_config: Optional[GenerationConfig] = None,
  569. logits_processor: Optional[TFLogitsProcessorList] = None,
  570. seed=None,
  571. **kwargs,
  572. ) -> Union[TFGenerateOutput, tf.Tensor]:
  573. r"""
  574. Generates sequences of token ids for models with a language modeling head.
  575. <Tip warning={true}>
  576. Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
  577. model's default generation configuration. You can override any `generation_config` by passing the corresponding
  578. parameters to generate, e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
  579. For an overview of generation strategies and code examples, check out the [following
  580. guide](../generation_strategies).
  581. </Tip>
  582. Parameters:
  583. inputs (`tf.Tensor` of varying shape depending on the modality, *optional*):
  584. The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
  585. method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
  586. should of in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
  587. `input_ids`, `input_values`, `input_features`, or `pixel_values`.
  588. generation_config (`~generation.GenerationConfig`, *optional*):
  589. The generation configuration to be used as base parametrization for the generation call. `**kwargs`
  590. passed to generate matching the attributes of `generation_config` will override them. If
  591. `generation_config` is not provided, the default will be used, which had the following loading
  592. priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
  593. configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
  594. default values, whose documentation should be checked to parameterize generation.
  595. logits_processor (`LogitsProcessorList`, *optional*):
  596. Custom logits processors that complement the default logits processors built from arguments and
  597. generation config. If a logit processor is passed that is already created with the arguments or a
  598. generation config an error is thrown. This feature is intended for advanced users.
  599. seed (`list[int]`, *optional*):
  600. Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
  601. `seed` argument from stateless functions in `tf.random`.
  602. kwargs (`dict[str, Any]`, *optional*):
  603. Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
  604. forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
  605. specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
  606. Return:
  607. [`~utils.ModelOutput`] or `tf.Tensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True` or when
  608. `config.return_dict_in_generate=True`) or a `tf.Tensor`.
  609. If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
  610. [`~utils.ModelOutput`] types are:
  611. - [`~generation.TFGreedySearchDecoderOnlyOutput`],
  612. - [`~generation.TFSampleDecoderOnlyOutput`],
  613. - [`~generation.TFBeamSearchDecoderOnlyOutput`],
  614. - [`~generation.TFBeamSampleDecoderOnlyOutput`]
  615. If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
  616. [`~utils.ModelOutput`] types are:
  617. - [`~generation.TFGreedySearchEncoderDecoderOutput`],
  618. - [`~generation.TFSampleEncoderDecoderOutput`],
  619. - [`~generation.TFBeamSearchEncoderDecoderOutput`],
  620. - [`~generation.TFBeamSampleEncoderDecoderOutput`]
  621. """
  622. # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
  623. self._validate_model_class()
  624. # priority: `generation_config` argument > `model.generation_config` (the default generation config)
  625. if generation_config is None:
  626. # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
  627. # two conditions must be met
  628. # 1) the generation config must have been created from the model config (`_from_model_config` field);
  629. # 2) the generation config must have seen no modification since its creation (the hash is the same).
  630. if self.generation_config._from_model_config and self.generation_config._original_object_hash == hash(
  631. self.generation_config
  632. ):
  633. new_generation_config = GenerationConfig.from_model_config(self.config)
  634. if new_generation_config != self.generation_config:
  635. warnings.warn(
  636. "You have modified the pretrained model configuration to control generation. This is a"
  637. " deprecated strategy to control generation and will be removed soon, in a future version."
  638. " Please use and modify the model generation configuration (see"
  639. " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )"
  640. )
  641. self.generation_config = new_generation_config
  642. generation_config = self.generation_config
  643. generation_config = copy.deepcopy(generation_config)
  644. model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
  645. self._validate_model_kwargs(model_kwargs.copy())
  646. # 2. Cast input dtypes to tf.int32 unless they're floats (which happens for some image models)
  647. if inputs is not None:
  648. if isinstance(inputs, tf.Tensor) and inputs.dtype.is_floating:
  649. pass
  650. elif isinstance(inputs, np.ndarray) and np.issubdtype(inputs.dtype, np.floating):
  651. pass
  652. else:
  653. inputs = tf.cast(inputs, tf.int32)
  654. if model_kwargs.get("attention_mask") is not None:
  655. model_kwargs["attention_mask"] = tf.cast(model_kwargs["attention_mask"], tf.int32)
  656. if "decoder_input_ids" in model_kwargs:
  657. if (
  658. isinstance(model_kwargs["decoder_input_ids"], tf.Tensor)
  659. and model_kwargs["decoder_input_ids"].dtype.is_floating
  660. ):
  661. pass
  662. elif isinstance(model_kwargs["decoder_input_ids"], np.ndarray) and np.issubdtype(
  663. model_kwargs["decoder_input_ids"].dtype, np.floating
  664. ):
  665. pass
  666. else:
  667. model_kwargs["decoder_input_ids"] = tf.cast(model_kwargs["decoder_input_ids"], tf.int32)
  668. # 3. Set generation parameters if not already defined
  669. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  670. if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
  671. if model_kwargs.get("attention_mask") is None:
  672. logger.warning(
  673. "The attention mask and the pad token id were not set. As a consequence, you may observe "
  674. "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
  675. )
  676. eos_token_id = generation_config.eos_token_id
  677. if isinstance(eos_token_id, list):
  678. eos_token_id = eos_token_id[0]
  679. generation_config.pad_token_id = eos_token_id
  680. use_xla = not tf.executing_eagerly()
  681. if use_xla and not self.supports_xla_generation:
  682. raise ValueError(
  683. "The selected model does not support Graph mode nor XLA generation (e.g. from tf.function())"
  684. )
  685. # 4. Define model inputs
  686. inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
  687. inputs, generation_config.bos_token_id, model_kwargs
  688. )
  689. # inputs_ids now has to be defined and cannot be None anymore
  690. batch_size = shape_list(inputs_tensor)[0]
  691. # 5. Prepare other model kwargs
  692. model_kwargs["output_attentions"] = generation_config.output_attentions
  693. model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
  694. model_kwargs["use_cache"] = generation_config.use_cache
  695. accepts_attention_mask = "attention_mask" in set(inspect.signature(self.call).parameters.keys())
  696. requires_attention_mask = "encoder_outputs" not in model_kwargs
  697. if model_kwargs.get("attention_mask", None) is None and requires_attention_mask and accepts_attention_mask:
  698. model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
  699. inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
  700. )
  701. # decoder-only models should use left-padding for generation
  702. if not self.config.is_encoder_decoder:
  703. if generation_config.pad_token_id is not None and tf.math.reduce_any(
  704. inputs_tensor[:, -1] == generation_config.pad_token_id
  705. ):
  706. logger.warning(
  707. "A decoder-only architecture is being used, but right-padding was detected! For correct "
  708. "generation results, please set `padding_side='left'` when initializing the tokenizer."
  709. )
  710. if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
  711. # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
  712. model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
  713. inputs_tensor, model_kwargs, model_input_name
  714. )
  715. # 6. Prepare model inputs which will be used for auto-regressive generation
  716. if self.config.is_encoder_decoder:
  717. input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
  718. batch_size=batch_size,
  719. model_input_name=model_input_name,
  720. model_kwargs=model_kwargs,
  721. decoder_start_token_id=generation_config.decoder_start_token_id,
  722. bos_token_id=generation_config.bos_token_id,
  723. )
  724. else:
  725. input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
  726. # 7. Prepare `max_length` depending on other stopping criteria.
  727. input_ids_seq_length = shape_list(input_ids)[-1]
  728. has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
  729. if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
  730. # 20 is the default max_length of the generation config
  731. warnings.warn(
  732. f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
  733. "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
  734. UserWarning,
  735. )
  736. elif generation_config.max_new_tokens is not None:
  737. if not has_default_max_length and generation_config.max_length is not None:
  738. logger.warning(
  739. f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
  740. f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
  741. "Please refer to the documentation for more information. "
  742. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  743. )
  744. generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
  745. # If the input length is a tensor (i.e. dynamic length), skip length checks
  746. if not isinstance(input_ids_seq_length, tf.Tensor):
  747. if (
  748. generation_config.min_length is not None
  749. and generation_config.min_length > generation_config.max_length
  750. ):
  751. raise ValueError(
  752. f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger"
  753. f" than the maximum length ({generation_config.max_length})"
  754. )
  755. if input_ids_seq_length >= generation_config.max_length:
  756. input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  757. logger.warning(
  758. f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
  759. f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
  760. " increasing`max_new_tokens`."
  761. )
  762. # 8. determine generation mode
  763. is_contrastive_search_gen_mode = (
  764. generation_config.top_k is not None
  765. and generation_config.top_k > 1
  766. and generation_config.do_sample is False
  767. and generation_config.penalty_alpha is not None
  768. and generation_config.penalty_alpha > 0
  769. )
  770. is_greedy_gen_mode = (
  771. not is_contrastive_search_gen_mode
  772. and (generation_config.num_beams == 1)
  773. and generation_config.do_sample is False
  774. )
  775. is_beam_gen_mode = (
  776. not is_contrastive_search_gen_mode
  777. and (generation_config.num_beams > 1)
  778. and generation_config.do_sample is False
  779. )
  780. is_sample_gen_mode = (generation_config.num_beams == 1) and generation_config.do_sample is True
  781. is_beam_sample_gen_mode = (generation_config.num_beams > 1) and generation_config.do_sample is True
  782. # 9. prepare distribution pre_processing samplers
  783. logits_processor = self._get_logits_processor(
  784. generation_config=generation_config,
  785. input_ids_seq_length=input_ids_seq_length,
  786. logits_processor=logits_processor,
  787. )
  788. # 10. go into different generation modes
  789. if is_greedy_gen_mode:
  790. if generation_config.num_return_sequences > 1:
  791. raise ValueError(
  792. f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
  793. " greedy search."
  794. )
  795. # 11. run greedy search
  796. return self.greedy_search(
  797. input_ids,
  798. max_length=generation_config.max_length,
  799. pad_token_id=generation_config.pad_token_id,
  800. eos_token_id=generation_config.eos_token_id,
  801. logits_processor=logits_processor,
  802. output_scores=generation_config.output_scores,
  803. return_dict_in_generate=generation_config.return_dict_in_generate,
  804. **model_kwargs,
  805. )
  806. elif is_contrastive_search_gen_mode:
  807. if generation_config.num_return_sequences > 1:
  808. raise ValueError(
  809. f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
  810. " contrastive search."
  811. )
  812. # 11. run contrastive search
  813. return self.contrastive_search(
  814. input_ids,
  815. top_k=generation_config.top_k,
  816. penalty_alpha=generation_config.penalty_alpha,
  817. logits_processor=logits_processor,
  818. max_length=generation_config.max_length,
  819. pad_token_id=generation_config.pad_token_id,
  820. eos_token_id=generation_config.eos_token_id,
  821. output_scores=generation_config.output_scores,
  822. return_dict_in_generate=generation_config.return_dict_in_generate,
  823. **model_kwargs,
  824. )
  825. elif is_sample_gen_mode:
  826. # 11. prepare logits warper
  827. logits_warper = self._get_logits_warper(generation_config=generation_config)
  828. # 12. expand input_ids with `num_return_sequences` additional sequences per batch
  829. input_ids, model_kwargs = self._expand_inputs_for_generation(
  830. input_ids=input_ids,
  831. expand_size=generation_config.num_return_sequences,
  832. is_encoder_decoder=self.config.is_encoder_decoder,
  833. **model_kwargs,
  834. )
  835. # 13. run sample
  836. return self.sample(
  837. input_ids,
  838. logits_processor=logits_processor,
  839. logits_warper=logits_warper,
  840. max_length=generation_config.max_length,
  841. pad_token_id=generation_config.pad_token_id,
  842. eos_token_id=generation_config.eos_token_id,
  843. seed=seed,
  844. output_scores=generation_config.output_scores,
  845. return_dict_in_generate=generation_config.return_dict_in_generate,
  846. **model_kwargs,
  847. )
  848. elif is_beam_gen_mode:
  849. if generation_config.num_beams < generation_config.num_return_sequences:
  850. raise ValueError(
  851. "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
  852. f" num_return_sequences, got {generation_config.num_beams} and"
  853. f" {generation_config.num_return_sequences} (respectively)"
  854. )
  855. # 11. broadcast inputs to the desired number of beams
  856. input_ids, model_kwargs = self._expand_inputs_for_generation(
  857. input_ids=input_ids,
  858. expand_size=generation_config.num_beams,
  859. is_encoder_decoder=self.config.is_encoder_decoder,
  860. expand_in_new_axis=True,
  861. **model_kwargs,
  862. )
  863. # 12. run beam search
  864. return self.beam_search(
  865. input_ids,
  866. max_length=generation_config.max_length,
  867. pad_token_id=generation_config.pad_token_id,
  868. eos_token_id=generation_config.eos_token_id,
  869. length_penalty=generation_config.length_penalty,
  870. early_stopping=generation_config.early_stopping,
  871. logits_processor=logits_processor,
  872. output_scores=generation_config.output_scores,
  873. return_dict_in_generate=generation_config.return_dict_in_generate,
  874. num_return_sequences=generation_config.num_return_sequences,
  875. **model_kwargs,
  876. )
  877. elif is_beam_sample_gen_mode:
  878. if generation_config.num_beams < generation_config.num_return_sequences:
  879. raise ValueError(
  880. "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
  881. f" num_return_sequences, got {generation_config.num_beams} and"
  882. f" {generation_config.num_return_sequences} (respectively)"
  883. )
  884. # 11. prepare logits warper
  885. logits_warper = self._get_logits_warper(generation_config=generation_config)
  886. # 12. broadcast inputs to the desired number of beams
  887. input_ids, model_kwargs = self._expand_inputs_for_generation(
  888. input_ids=input_ids,
  889. expand_size=generation_config.num_beams,
  890. is_encoder_decoder=self.config.is_encoder_decoder,
  891. expand_in_new_axis=True,
  892. **model_kwargs,
  893. )
  894. # 13. run beam sample (beam search with sampling)
  895. return self.beam_search(
  896. input_ids,
  897. do_sample=True,
  898. max_length=generation_config.max_length,
  899. pad_token_id=generation_config.pad_token_id,
  900. eos_token_id=generation_config.eos_token_id,
  901. length_penalty=generation_config.length_penalty,
  902. early_stopping=generation_config.early_stopping,
  903. logits_processor=logits_processor,
  904. logits_warper=logits_warper,
  905. output_scores=generation_config.output_scores,
  906. return_dict_in_generate=generation_config.return_dict_in_generate,
  907. num_return_sequences=generation_config.num_return_sequences,
  908. **model_kwargs,
  909. )
  910. def _prepare_attention_mask_for_generation(
  911. self,
  912. inputs: tf.Tensor,
  913. pad_token_id: Optional[int],
  914. eos_token_id: Optional[int],
  915. ) -> tf.Tensor:
  916. is_input_ids = len(inputs.shape) == 2 and inputs.dtype in (tf.int32, tf.int64)
  917. is_pad_token_in_inputs = (pad_token_id is not None) and tf.math.reduce_any(inputs == pad_token_id)
  918. is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or (pad_token_id != eos_token_id)
  919. # Check if input is input_ids and padded -> only then is attention_mask defined
  920. if is_input_ids and is_pad_token_in_inputs and is_pad_token_not_equal_to_eos_token_id:
  921. return tf.cast(tf.math.not_equal(inputs, pad_token_id), dtype=tf.int32)
  922. else:
  923. return tf.ones(inputs.shape[:2], dtype=tf.int32)
  924. def _prepare_encoder_decoder_kwargs_for_generation(
  925. self, inputs_tensor: tf.Tensor, model_kwargs, model_input_name: Optional[str] = None
  926. ) -> dict[str, Any]:
  927. # 1. get encoder and store encoder outputs
  928. encoder = self.get_encoder()
  929. # 2. prepare encoder args and encoder kwargs from model kwargs
  930. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
  931. encoder_kwargs = {
  932. argument: value
  933. for argument, value in model_kwargs.items()
  934. if not any(argument.startswith(p) for p in irrelevant_prefix)
  935. }
  936. encoder_signature = set(inspect.signature(encoder.call).parameters)
  937. encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
  938. if not encoder_accepts_wildcard:
  939. encoder_kwargs = {
  940. argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
  941. }
  942. # 3. vision models don't use `attention_mask`.
  943. encoder_kwargs["return_dict"] = True
  944. encoder_kwargs[model_input_name] = inputs_tensor
  945. if model_input_name != self.main_input_name: # in Keras, the first input must always be passed
  946. encoder_kwargs[self.main_input_name] = None
  947. encoder_outputs = encoder(**encoder_kwargs)
  948. model_kwargs["encoder_outputs"] = encoder_outputs
  949. return model_kwargs
  950. def _prepare_decoder_input_ids_for_generation(
  951. self,
  952. batch_size: int,
  953. model_input_name: str,
  954. model_kwargs: dict[str, tf.Tensor],
  955. decoder_start_token_id: Optional[int] = None,
  956. bos_token_id: Optional[int] = None,
  957. ) -> tuple[tf.Tensor, dict[str, tf.Tensor]]:
  958. """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
  959. # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
  960. # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
  961. if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
  962. decoder_input_ids = model_kwargs.pop("decoder_input_ids")
  963. elif "input_ids" in model_kwargs and model_input_name != "input_ids":
  964. decoder_input_ids = model_kwargs.pop("input_ids")
  965. else:
  966. decoder_input_ids = None
  967. # 2. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
  968. decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
  969. decoder_input_ids_start = tf.ones((batch_size, 1), dtype=tf.int32) * decoder_start_token_id
  970. # no user input -> use decoder_start_token_id as decoder_input_ids
  971. if decoder_input_ids is None:
  972. decoder_input_ids = decoder_input_ids_start
  973. # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
  974. # decoder_attention_mask if provided)
  975. elif tf.reduce_all(decoder_input_ids[:, 0] != decoder_start_token_id):
  976. decoder_input_ids = tf.concat([decoder_input_ids_start, decoder_input_ids], axis=-1)
  977. if "decoder_attention_mask" in model_kwargs:
  978. decoder_attention_mask = model_kwargs["decoder_attention_mask"]
  979. decoder_attention_mask = tf.concat(
  980. (tf.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
  981. axis=-1,
  982. )
  983. model_kwargs["decoder_attention_mask"] = decoder_attention_mask
  984. return decoder_input_ids, model_kwargs
  985. def _get_decoder_start_token_id(
  986. self, decoder_start_token_id: Optional[int] = None, bos_token_id: Optional[int] = None
  987. ) -> int:
  988. # retrieve decoder_start_token_id for encoder-decoder models
  989. # fall back to bos_token_id if necessary
  990. decoder_start_token_id = (
  991. decoder_start_token_id
  992. if decoder_start_token_id is not None
  993. else self.generation_config.decoder_start_token_id
  994. )
  995. bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
  996. if decoder_start_token_id is not None:
  997. return decoder_start_token_id
  998. elif bos_token_id is not None:
  999. return bos_token_id
  1000. raise ValueError(
  1001. "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
  1002. )
  1003. @staticmethod
  1004. def _expand_inputs_for_generation(
  1005. expand_size: int = 1,
  1006. is_encoder_decoder: bool = False,
  1007. input_ids: Optional[tf.Tensor] = None,
  1008. expand_in_new_axis: bool = False,
  1009. **model_kwargs,
  1010. ) -> tuple[tf.Tensor, dict[str, Any]]:
  1011. """
  1012. Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...] or [batch_size, expand_size, ...],
  1013. depending on `expand_in_new_axis`. Beam-based approaches expect this function to be used with
  1014. `expand_in_new_axis=True`
  1015. """
  1016. def _expand_tensor(tensor: tf.Tensor):
  1017. if expand_in_new_axis:
  1018. shape = shape_list(tensor)
  1019. return tf.broadcast_to(tensor[:, None], (shape[0], expand_size) + tuple(shape[1:]))
  1020. else:
  1021. return tf.repeat(tensor, expand_size, axis=0)
  1022. def _expand_dict_for_generation(dict_to_expand):
  1023. for key in dict_to_expand:
  1024. if dict_to_expand[key] is not None and isinstance(dict_to_expand[key], tf.Tensor):
  1025. dict_to_expand[key] = _expand_tensor(dict_to_expand[key])
  1026. return dict_to_expand
  1027. if input_ids is not None:
  1028. input_ids = _expand_tensor(input_ids)
  1029. model_kwargs = _expand_dict_for_generation(model_kwargs)
  1030. if is_encoder_decoder:
  1031. if model_kwargs.get("encoder_outputs") is None:
  1032. raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
  1033. model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
  1034. return input_ids, model_kwargs
  1035. def _prepare_model_inputs(
  1036. self,
  1037. inputs: Optional[tf.Tensor] = None,
  1038. bos_token_id: Optional[int] = None,
  1039. model_kwargs: Optional[dict[str, tf.Tensor]] = None,
  1040. ) -> tuple[tf.Tensor, Optional[str], dict[str, tf.Tensor]]:
  1041. """
  1042. This function extracts the model-specific `inputs` for generation.
  1043. """
  1044. # 1. retrieve all kwargs that are non-None or non-model input related.
  1045. # some encoder-decoder models have different names for model and encoder
  1046. if (
  1047. self.config.is_encoder_decoder
  1048. and hasattr(self, "encoder")
  1049. and hasattr(self.encoder, "main_input_name")
  1050. and self.encoder.main_input_name != self.main_input_name
  1051. ):
  1052. input_name = self.encoder.main_input_name
  1053. else:
  1054. input_name = self.main_input_name
  1055. model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
  1056. # 2. check whether model_input_name is passed as kwarg
  1057. # if yes and `inputs` is None use kwarg inputs
  1058. inputs_kwarg = model_kwargs.pop(input_name, None)
  1059. if inputs_kwarg is not None and inputs is not None:
  1060. raise ValueError(
  1061. f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
  1062. f"Make sure to either pass {inputs} or {input_name}=..."
  1063. )
  1064. elif inputs_kwarg is not None:
  1065. inputs = inputs_kwarg
  1066. # 3. In the presence of `inputs_embeds` for text models:
  1067. # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
  1068. # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
  1069. # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
  1070. # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
  1071. # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
  1072. if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
  1073. if not self.config.is_encoder_decoder:
  1074. has_inputs_embeds_forwarding = "inputs_embeds" in set(
  1075. inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
  1076. )
  1077. if not has_inputs_embeds_forwarding:
  1078. raise ValueError(
  1079. f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
  1080. "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
  1081. "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
  1082. )
  1083. # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
  1084. # the attention mask) can rely on the actual model input.
  1085. model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
  1086. inputs, bos_token_id, model_kwargs=model_kwargs
  1087. )
  1088. else:
  1089. if inputs is not None:
  1090. raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
  1091. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  1092. # 4. if `inputs` is still None, try to create `input_ids` from BOS token
  1093. inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
  1094. return inputs, input_name, model_kwargs
  1095. def _maybe_initialize_input_ids_for_generation(
  1096. self,
  1097. inputs: Optional[tf.Tensor] = None,
  1098. bos_token_id: Optional[int] = None,
  1099. model_kwargs: Optional[dict[str, tf.Tensor]] = None,
  1100. ) -> tf.Tensor:
  1101. """Initializes input ids for generation, if necessary."""
  1102. if inputs is not None:
  1103. return inputs
  1104. encoder_outputs = model_kwargs.get("encoder_outputs")
  1105. if self.config.is_encoder_decoder and encoder_outputs is not None:
  1106. # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
  1107. shape = encoder_outputs.last_hidden_state.shape[:-1]
  1108. return tf.ones(shape, dtype=tf.int32) * -100
  1109. if bos_token_id is None:
  1110. raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
  1111. # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
  1112. # soft-prompting or in multimodal implementations built on top of decoder-only language models.
  1113. batch_size = 1
  1114. for value in model_kwargs.values():
  1115. if isinstance(value, tf.Tensor):
  1116. batch_size = value.shape[0]
  1117. break
  1118. return tf.ones((batch_size, 1), dtype=tf.int32) * bos_token_id
  1119. @staticmethod
  1120. def _extract_past_from_model_output(outputs: ModelOutput):
  1121. past_key_values = None
  1122. if "past_key_values" in outputs:
  1123. past_key_values = outputs.past_key_values
  1124. elif "mems" in outputs:
  1125. past_key_values = outputs.mems
  1126. elif "past_buckets_states" in outputs:
  1127. past_key_values = outputs.past_buckets_states
  1128. return past_key_values
  1129. def _update_model_kwargs_for_generation(
  1130. self, outputs: ModelOutput, model_kwargs: dict[str, Any], is_encoder_decoder: bool = False
  1131. ) -> dict[str, Any]:
  1132. # update past_key_values
  1133. model_kwargs["past_key_values"] = self._extract_past_from_model_output(outputs)
  1134. # update attention mask
  1135. if not is_encoder_decoder:
  1136. if "attention_mask" in model_kwargs:
  1137. attention_mask = model_kwargs["attention_mask"]
  1138. model_kwargs["attention_mask"] = tf.concat(
  1139. [attention_mask, tf.ones((shape_list(attention_mask)[0], 1), dtype=tf.int32)], axis=-1
  1140. )
  1141. return model_kwargs
  1142. def _update_model_kwargs_for_xla_generation(
  1143. self,
  1144. model_outputs: ModelOutput,
  1145. model_kwargs: dict[str, Any],
  1146. cur_len: int,
  1147. max_length: int,
  1148. batch_size: int,
  1149. is_encoder_decoder: bool = False,
  1150. batch_axis: int = 0,
  1151. ):
  1152. def _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder):
  1153. """initializes the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
  1154. if is_encoder_decoder:
  1155. # One 1 for decoder_start_token_id, 0s for the currently-unfilled locations in the past_key_values tensor,
  1156. # 1s for the actual input_ids
  1157. decoder_attention_mask = tf.concat(
  1158. [
  1159. tf.ones((batch_size, 1), dtype=tf.int32),
  1160. tf.zeros((batch_size, num_padding_values), dtype=tf.int32),
  1161. tf.ones((batch_size, 1), dtype=tf.int32),
  1162. ],
  1163. axis=1,
  1164. )
  1165. mask = {"decoder_attention_mask": decoder_attention_mask}
  1166. else:
  1167. attention_mask = model_kwargs.pop("attention_mask")
  1168. # 0s for the currently-unfilled locations in the past_key_values tensor, 1s for the actual input_ids
  1169. attention_mask = tf.concat(
  1170. [
  1171. attention_mask,
  1172. tf.zeros((batch_size, num_padding_values), dtype=attention_mask.dtype),
  1173. tf.ones((batch_size, 1), dtype=attention_mask.dtype),
  1174. ],
  1175. axis=1,
  1176. )
  1177. mask = {"attention_mask": attention_mask}
  1178. return mask
  1179. def _update_attention(model_kwargs, new_past_index, is_encoder_decoder):
  1180. """updates the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
  1181. update_start = tf.constant([0, 1], dtype=tf.int32) * new_past_index
  1182. if is_encoder_decoder:
  1183. decoder_attention_mask = model_kwargs.pop("decoder_attention_mask")
  1184. decoder_attention_mask_update_slice = tf.ones((batch_size, 1), dtype=decoder_attention_mask.dtype)
  1185. decoder_attention_mask = dynamic_update_slice(
  1186. decoder_attention_mask, decoder_attention_mask_update_slice, update_start
  1187. )
  1188. mask = {"decoder_attention_mask": decoder_attention_mask}
  1189. else:
  1190. attention_mask = model_kwargs.pop("attention_mask")
  1191. attention_mask_update_slice = tf.ones((batch_size, 1), dtype=attention_mask.dtype)
  1192. attention_mask = dynamic_update_slice(attention_mask, attention_mask_update_slice, update_start)
  1193. mask = {"attention_mask": attention_mask}
  1194. return mask
  1195. def _initialize_past(past_key_values, num_padding_values, batch_axis):
  1196. """initialize past_key_values with zeros -- the structure depends on `batch_axis`"""
  1197. if batch_axis == 0:
  1198. padding_values = tf.constant([[0, 0], [0, 0], [0, num_padding_values], [0, 0]], dtype=tf.int32)
  1199. new_past = ()
  1200. for past_layer in past_key_values:
  1201. new_past_layer = list(past_layer)
  1202. for i in range(len(new_past_layer[:2])):
  1203. new_past_layer[i] = tf.pad(past_layer[i], padding_values)
  1204. new_past += (tuple(new_past_layer),)
  1205. else:
  1206. padding_values = tf.scatter_nd(indices=[[3, 1]], updates=[num_padding_values], shape=(5, 2))
  1207. new_past = list(past_key_values)
  1208. for i in range(len(past_key_values)):
  1209. new_past[i] = tf.pad(past_key_values[i], padding_values)
  1210. return new_past
  1211. def _update_past(past_key_values, new_past_index, batch_axis):
  1212. if batch_axis == 0:
  1213. slice_start_base = tf.constant([0, 0, 1, 0])
  1214. new_past = ()
  1215. for past_layer in past_key_values:
  1216. new_past_layer = list(past_layer)
  1217. for i in range(len(new_past_layer[:2])):
  1218. update_slice = past_layer[i][:, :, -1:]
  1219. # Write the last slice to the first open location in the padded past_key_values array
  1220. # and then truncate the last slice off the array
  1221. new_past_layer[i] = dynamic_update_slice(
  1222. past_layer[i][:, :, :-1], update_slice, slice_start_base * new_past_index
  1223. )
  1224. new_past += (tuple(new_past_layer),)
  1225. else:
  1226. slice_start_base = tf.constant([0, 0, 0, 1, 0])
  1227. new_past = [None for _ in range(len(past_key_values))]
  1228. for i in range(len(past_key_values)):
  1229. update_slice = past_key_values[i][:, :, :, -1:]
  1230. # Write the last slice to the first open location in the padded past_key_values array
  1231. # and then truncate the last slice off the array
  1232. new_past[i] = dynamic_update_slice(
  1233. past_key_values[i][:, :, :, :-1], update_slice, slice_start_base * new_past_index
  1234. )
  1235. return new_past
  1236. past_key_values = self._extract_past_from_model_output(model_outputs)
  1237. if past_key_values is None:
  1238. raise ValueError(
  1239. "No known `past_key_values variable` found in model outputs (model outputs keys:"
  1240. f" {list(model_outputs.keys())})"
  1241. )
  1242. is_past_initialized = model_kwargs.pop("past_key_values", None) is not None
  1243. if not is_past_initialized:
  1244. # The padded version of `past_key_values` has a length of `max_length - 1`, as `past_key_values` holds information relative to
  1245. # previous autoregressive generation steps (step 0 has no past_key_values, step 1 has 1 past_key_values value, ..., the last step
  1246. # has `max_length - 1` past_key_values values).
  1247. num_padding_values = max_length - cur_len - 1
  1248. mask = _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder)
  1249. new_past = _initialize_past(past_key_values, num_padding_values, batch_axis)
  1250. else:
  1251. # The new index of past_key_values to be filled corresponds to the current length of the sequence, with two
  1252. # subtractions: -1 because past_key_values holds information regarding previous generation steps (read comment above)
  1253. # and -1 again because in an array the index is the length of the array minus 1.
  1254. new_past_index = cur_len - 2
  1255. mask = _update_attention(model_kwargs, new_past_index, is_encoder_decoder)
  1256. new_past = _update_past(past_key_values, new_past_index, batch_axis)
  1257. # sets the updated variables (mask and past_key_values)
  1258. model_kwargs.update(mask)
  1259. model_kwargs["past_key_values"] = tuple(new_past)
  1260. return model_kwargs
  1261. def _get_logits_warper(
  1262. self,
  1263. generation_config: GenerationConfig,
  1264. ) -> TFLogitsProcessorList:
  1265. """
  1266. This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsWarper`]
  1267. instances used for multinomial sampling.
  1268. """
  1269. # instantiate warpers list
  1270. warpers = TFLogitsProcessorList()
  1271. # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
  1272. # better score (i.e. keep len(generation_config.eos_token_id) + 1)
  1273. if generation_config.num_beams > 1:
  1274. if isinstance(generation_config.eos_token_id, list):
  1275. min_tokens_to_keep = len(generation_config.eos_token_id) + 1
  1276. else:
  1277. min_tokens_to_keep = 2
  1278. else:
  1279. min_tokens_to_keep = 1
  1280. if generation_config.temperature is not None and generation_config.temperature != 1.0:
  1281. warpers.append(TFTemperatureLogitsWarper(generation_config.temperature))
  1282. if generation_config.top_k is not None and generation_config.top_k != 0:
  1283. warpers.append(TFTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep))
  1284. if generation_config.top_p is not None and generation_config.top_p < 1.0:
  1285. warpers.append(TFTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep))
  1286. return warpers
  1287. def _get_logits_processor(
  1288. self,
  1289. generation_config: GenerationConfig,
  1290. input_ids_seq_length: int,
  1291. logits_processor: Optional[TFLogitsProcessorList],
  1292. ) -> TFLogitsProcessorList:
  1293. """
  1294. This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsProcessor`]
  1295. instances used to modify the scores of the language model head.
  1296. """
  1297. processors = TFLogitsProcessorList()
  1298. # instantiate processors list
  1299. if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
  1300. processors.append(TFRepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
  1301. if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
  1302. processors.append(TFNoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
  1303. if generation_config.bad_words_ids is not None:
  1304. processors.append(
  1305. TFNoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)
  1306. )
  1307. if (
  1308. generation_config.min_length is not None
  1309. and generation_config.eos_token_id is not None
  1310. and generation_config.min_length > 0
  1311. ):
  1312. processors.append(TFMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id))
  1313. if generation_config.forced_bos_token_id is not None:
  1314. processors.append(TFForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
  1315. if generation_config.forced_eos_token_id is not None:
  1316. processors.append(
  1317. TFForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
  1318. )
  1319. if generation_config.suppress_tokens is not None:
  1320. processors.append(TFSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
  1321. if generation_config.begin_suppress_tokens is not None:
  1322. begin_index = input_ids_seq_length
  1323. begin_index = (
  1324. begin_index
  1325. if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
  1326. else begin_index + 1
  1327. )
  1328. if getattr(generation_config, "forced_decoder_ids", None) is not None:
  1329. begin_index += generation_config.forced_decoder_ids[-1][
  1330. 0
  1331. ] # generation starts after the last token that is forced
  1332. processors.append(
  1333. TFSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
  1334. )
  1335. if getattr(generation_config, "forced_decoder_ids", None) is not None:
  1336. processors.append(TFForceTokensLogitsProcessor(generation_config.forced_decoder_ids))
  1337. processors = self._merge_criteria_processor_list(processors, logits_processor)
  1338. return processors
  1339. def _merge_criteria_processor_list(
  1340. self,
  1341. default_list: TFLogitsProcessorList,
  1342. custom_list: TFLogitsProcessorList,
  1343. ) -> TFLogitsProcessorList:
  1344. if len(custom_list) == 0:
  1345. return default_list
  1346. for default in default_list:
  1347. for custom in custom_list:
  1348. if type(custom) is type(default):
  1349. object_type = "logits processor"
  1350. raise ValueError(
  1351. f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
  1352. f" `generate`, but it has already been created with the values {default}. {default} has been"
  1353. " created by passing the corresponding arguments to generate or by the model's config default"
  1354. f" values. If you just want to change the default values of {object_type} consider passing"
  1355. f" them as arguments to `generate` instead of using a custom {object_type}."
  1356. )
  1357. default_list.extend(custom_list)
  1358. return default_list
  1359. def greedy_search(
  1360. self,
  1361. input_ids: tf.Tensor,
  1362. max_length: Optional[int] = None,
  1363. pad_token_id: Optional[int] = None,
  1364. eos_token_id: Optional[int] = None,
  1365. logits_processor: Optional[TFLogitsProcessorList] = None,
  1366. output_attentions: Optional[bool] = None,
  1367. output_hidden_states: Optional[bool] = None,
  1368. output_scores: Optional[bool] = None,
  1369. return_dict_in_generate: Optional[bool] = None,
  1370. **model_kwargs,
  1371. ) -> Union[TFGreedySearchOutput, tf.Tensor]:
  1372. r"""
  1373. Generates sequences for models with a language modeling head using greedy decoding.
  1374. Parameters:
  1375. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1376. The sequence used as a prompt for the generation.
  1377. logits_processor (`TFLogitsProcessorList`, *optional*):
  1378. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1379. used to modify the prediction scores of the language modeling head applied at each generation step.
  1380. max_length (`int`, *optional*, defaults to 20):
  1381. The maximum length of the sequence to be generated.
  1382. pad_token_id (`int`, *optional*):
  1383. The id of the *padding* token.
  1384. eos_token_id (`Union[int, list[int]]`, *optional*):
  1385. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1386. output_attentions (`bool`, *optional*, defaults to `False`):
  1387. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1388. returned tensors for more details.
  1389. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1390. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1391. for more details.
  1392. output_scores (`bool`, *optional*, defaults to `False`):
  1393. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  1394. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1395. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1396. model_kwargs:
  1397. Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
  1398. model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  1399. Return:
  1400. [`~generation.TFGreedySearchDecoderOnlyOutput`], [`~generation.TFGreedySearchEncoderDecoderOutput`] or
  1401. `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
  1402. [`~generation.TFGreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1403. `return_dict_in_generate=True` or a [`~generation.TFGreedySearchEncoderDecoderOutput`] if
  1404. `model.config.is_encoder_decoder=True`.
  1405. Examples:
  1406. ```python
  1407. >>> from transformers import (
  1408. ... AutoTokenizer,
  1409. ... TFAutoModelForCausalLM,
  1410. ... TFLogitsProcessorList,
  1411. ... TFMinLengthLogitsProcessor,
  1412. ... )
  1413. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1414. >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1415. >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
  1416. >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
  1417. >>> input_prompt = "Today is a beautiful day, and"
  1418. >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
  1419. >>> # instantiate logits processors
  1420. >>> logits_processor = TFLogitsProcessorList(
  1421. ... [
  1422. ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
  1423. ... ]
  1424. ... )
  1425. >>> outputs = model.greedy_search(input_ids, logits_processor=logits_processor)
  1426. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1427. ["Today is a beautiful day, and I'm so happy to be here. I'm so happy to"]
  1428. ```"""
  1429. # 1. init greedy_search values
  1430. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1431. max_length = max_length if max_length is not None else self.generation_config.max_length
  1432. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1433. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1434. if isinstance(eos_token_id, int):
  1435. eos_token_id = [eos_token_id]
  1436. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1437. output_attentions = (
  1438. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1439. )
  1440. output_hidden_states = (
  1441. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1442. )
  1443. return_dict_in_generate = (
  1444. return_dict_in_generate
  1445. if return_dict_in_generate is not None
  1446. else self.generation_config.return_dict_in_generate
  1447. )
  1448. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  1449. use_xla = not tf.executing_eagerly()
  1450. # TODO (Joao): fix cache format or find programmatic way to detect cache index
  1451. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  1452. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  1453. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  1454. # some models, like XLNet, need more than the last token in the presence of past_key_values
  1455. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  1456. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  1457. scores = [] if (return_dict_in_generate and output_scores) else None
  1458. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1459. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1460. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  1461. # 3. init tensors to use for "xla-compileable" generate function
  1462. batch_size, cur_len = shape_list(input_ids)
  1463. # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
  1464. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  1465. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  1466. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  1467. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  1468. # define condition fn
  1469. def greedy_search_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
  1470. """state termination condition fn."""
  1471. return ~tf.reduce_all(finished_sequences)
  1472. # define condition fn
  1473. def greedy_search_body_fn(generated, finished_sequences, cur_len, model_kwargs):
  1474. """state update fn."""
  1475. if model_kwargs.get("past_key_values") is None or needs_full_input:
  1476. input_ids = generated[:, :cur_len]
  1477. else:
  1478. input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
  1479. model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
  1480. # forward pass to get next token logits
  1481. model_outputs = self(
  1482. **model_inputs,
  1483. return_dict=True,
  1484. output_attentions=output_attentions,
  1485. output_hidden_states=output_hidden_states,
  1486. )
  1487. next_token_logits = model_outputs.logits[:, -1]
  1488. # pre-process distribution
  1489. next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
  1490. # Store scores, attentions and hidden_states when required
  1491. if not use_xla and return_dict_in_generate:
  1492. if output_scores:
  1493. scores.append(next_tokens_scores)
  1494. if output_attentions and self.config.is_encoder_decoder:
  1495. decoder_attentions.append(model_outputs.decoder_attentions)
  1496. elif output_attentions and not self.config.is_encoder_decoder:
  1497. decoder_attentions.append(model_outputs.attentions)
  1498. if self.config.is_encoder_decoder:
  1499. cross_attentions.append(model_outputs.cross_attentions)
  1500. if output_hidden_states and self.config.is_encoder_decoder:
  1501. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  1502. elif output_hidden_states and self.config.is_encoder_decoder:
  1503. decoder_hidden_states.append(model_outputs.hidden_states)
  1504. # argmax
  1505. next_tokens = tf.argmax(next_tokens_scores, axis=-1, output_type=tf.int32)
  1506. if eos_token_id is not None:
  1507. if pad_token_id is None:
  1508. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  1509. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  1510. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  1511. next_token_is_eos = tf.math.reduce_any(
  1512. tf.equal(
  1513. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  1514. ),
  1515. axis=0,
  1516. )
  1517. finished_sequences = finished_sequences | next_token_is_eos
  1518. # update `generated` and `cur_len`
  1519. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  1520. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  1521. cur_len += 1
  1522. # update model_kwargs
  1523. if use_xla:
  1524. model_kwargs = self._update_model_kwargs_for_xla_generation(
  1525. model_outputs=model_outputs,
  1526. model_kwargs=model_kwargs,
  1527. cur_len=cur_len,
  1528. max_length=max_length,
  1529. batch_size=batch_size,
  1530. is_encoder_decoder=self.config.is_encoder_decoder,
  1531. batch_axis=cache_batch_axis,
  1532. )
  1533. else:
  1534. model_kwargs = self._update_model_kwargs_for_generation(
  1535. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  1536. )
  1537. # if we don't cache past_key_values key values we need the whole input
  1538. if model_kwargs.get("past_key_values", None) is None:
  1539. # let's throw out `past_key_values` since we don't want `None` tensors
  1540. model_kwargs.pop("past_key_values", None)
  1541. return generated, finished_sequences, cur_len, model_kwargs
  1542. # 5. run generation
  1543. # 1st generation step has to be run before to initialize `past_key_values`
  1544. generated, finished_sequences, cur_len, model_kwargs = greedy_search_body_fn(
  1545. generated, finished_sequences, cur_len, model_kwargs
  1546. )
  1547. # 2-to-n generation steps can then be run in autoregressive fashion
  1548. # only in case 1st generation step does NOT yield EOS token though
  1549. maximum_iterations = max_length - cur_len
  1550. generated, _, cur_len, _ = tf.while_loop(
  1551. greedy_search_cond_fn,
  1552. greedy_search_body_fn,
  1553. (generated, finished_sequences, cur_len, model_kwargs),
  1554. maximum_iterations=maximum_iterations,
  1555. )
  1556. # 6. prepare outputs
  1557. if not use_xla:
  1558. # cut for backward compatibility
  1559. generated = generated[:, :cur_len]
  1560. if return_dict_in_generate:
  1561. if self.config.is_encoder_decoder:
  1562. # if model is an encoder-decoder, retrieve encoder attention weights
  1563. # and hidden states
  1564. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  1565. encoder_hidden_states = (
  1566. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  1567. )
  1568. scores = tuple(scores) if scores is not None else None
  1569. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  1570. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  1571. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  1572. return TFGreedySearchEncoderDecoderOutput(
  1573. sequences=generated,
  1574. scores=scores,
  1575. encoder_attentions=encoder_attentions,
  1576. encoder_hidden_states=encoder_hidden_states,
  1577. decoder_attentions=decoder_attentions,
  1578. cross_attentions=cross_attentions,
  1579. decoder_hidden_states=decoder_hidden_states,
  1580. )
  1581. else:
  1582. return TFGreedySearchDecoderOnlyOutput(
  1583. sequences=generated,
  1584. scores=scores,
  1585. attentions=decoder_attentions,
  1586. hidden_states=decoder_hidden_states,
  1587. )
  1588. else:
  1589. return generated
  1590. def sample(
  1591. self,
  1592. input_ids: tf.Tensor,
  1593. logits_processor: Optional[TFLogitsProcessorList] = None,
  1594. logits_warper: Optional[TFLogitsProcessorList] = None,
  1595. max_length: Optional[int] = None,
  1596. pad_token_id: Optional[int] = None,
  1597. eos_token_id: Optional[int] = None,
  1598. seed: Optional[tuple[int, int]] = None,
  1599. output_attentions: Optional[bool] = None,
  1600. output_hidden_states: Optional[bool] = None,
  1601. output_scores: Optional[bool] = None,
  1602. return_dict_in_generate: Optional[bool] = None,
  1603. **model_kwargs,
  1604. ) -> Union[TFSampleOutput, tf.Tensor]:
  1605. r"""
  1606. Generates sequences for models with a language modeling head using multinomial sampling.
  1607. Parameters:
  1608. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1609. The sequence used as a prompt for the generation.
  1610. logits_processor (`TFLogitsProcessorList`, *optional*):
  1611. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1612. used to modify the prediction scores of the language modeling head applied at each generation step.
  1613. logits_warper (`TFLogitsProcessorList`, *optional*):
  1614. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  1615. used to warp the prediction score distribution of the language modeling head applied before multinomial
  1616. sampling at each generation step.
  1617. max_length (`int`, *optional*, defaults to 20):
  1618. The maximum length of the sequence to be generated.
  1619. pad_token_id (`int`, *optional*):
  1620. The id of the *padding* token.
  1621. eos_token_id (`Union[int, list[int]]`, *optional*):
  1622. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1623. seed (`list[int]`, *optional*):
  1624. Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
  1625. `seed` argument from stateless functions in `tf.random`.
  1626. output_attentions (`bool`, *optional*, defaults to `False`):
  1627. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1628. returned tensors for more details.
  1629. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1630. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1631. for more details.
  1632. output_scores (`bool`, *optional*, defaults to `False`):
  1633. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  1634. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1635. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1636. model_kwargs:
  1637. Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
  1638. encoder-decoder model the kwargs should include `encoder_outputs`.
  1639. Return:
  1640. [`~generation.TFSampleDecoderOnlyOutput`], [`~generation.TFSampleEncoderDecoderOutput`] or `tf.Tensor`: A
  1641. `tf.Tensor` containing the generated tokens (default behaviour) or a
  1642. [`~generation.TFSampleDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1643. `return_dict_in_generate=True` or a [`~generation.TFSampleEncoderDecoderOutput`] if
  1644. `model.config.is_encoder_decoder=True`.
  1645. Examples:
  1646. ```python
  1647. >>> import tensorflow as tf
  1648. >>> from transformers import (
  1649. ... AutoTokenizer,
  1650. ... TFAutoModelForCausalLM,
  1651. ... TFLogitsProcessorList,
  1652. ... TFMinLengthLogitsProcessor,
  1653. ... TFTopKLogitsWarper,
  1654. ... TFTemperatureLogitsWarper,
  1655. ... )
  1656. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1657. >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1658. >>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
  1659. >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
  1660. >>> input_prompt = "Today is a beautiful day, and"
  1661. >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
  1662. >>> # instantiate logits processors
  1663. >>> logits_processor = TFLogitsProcessorList(
  1664. ... [
  1665. ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
  1666. ... ]
  1667. ... )
  1668. >>> # instantiate logits processors
  1669. >>> logits_warper = TFLogitsProcessorList(
  1670. ... [
  1671. ... TFTopKLogitsWarper(50),
  1672. ... TFTemperatureLogitsWarper(0.7),
  1673. ... ]
  1674. ... )
  1675. >>> tf.random.set_seed(0)
  1676. >>> outputs = model.sample(input_ids, logits_processor=logits_processor, logits_warper=logits_warper)
  1677. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1678. ['Today is a beautiful day, and I love my country. But when I look at Donald Trump,']
  1679. ```"""
  1680. # 1. init greedy_search values
  1681. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1682. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  1683. max_length = max_length if max_length is not None else self.generation_config.max_length
  1684. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1685. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1686. if isinstance(eos_token_id, int):
  1687. eos_token_id = [eos_token_id]
  1688. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1689. output_attentions = (
  1690. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1691. )
  1692. output_hidden_states = (
  1693. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1694. )
  1695. return_dict_in_generate = (
  1696. return_dict_in_generate
  1697. if return_dict_in_generate is not None
  1698. else self.generation_config.return_dict_in_generate
  1699. )
  1700. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  1701. use_xla = not tf.executing_eagerly()
  1702. # TODO (Joao): fix cache format or find programmatic way to detect cache index
  1703. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  1704. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  1705. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  1706. # some models, like XLNet, need more than the last token in the presence of past_key_values
  1707. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  1708. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  1709. scores = [] if (return_dict_in_generate and output_scores) else None
  1710. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1711. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1712. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  1713. # 3. init tensors to use for "xla-compileable" generate function
  1714. batch_size, cur_len = shape_list(input_ids)
  1715. # initialize `generated` (pre-populated with `pad_token_id`), `finished_sequences`
  1716. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  1717. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  1718. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  1719. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  1720. def sample_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
  1721. return ~tf.reduce_all(finished_sequences)
  1722. def sample_body_fn(generated, finished_sequences, cur_len, model_kwargs):
  1723. if model_kwargs.get("past_key_values") is None or needs_full_input:
  1724. input_ids = generated[:, :cur_len]
  1725. else:
  1726. input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
  1727. model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
  1728. # forward pass to get next token logits
  1729. model_outputs = self(
  1730. **model_inputs,
  1731. return_dict=True,
  1732. output_attentions=output_attentions,
  1733. output_hidden_states=output_hidden_states,
  1734. )
  1735. next_token_logits = model_outputs.logits[:, -1]
  1736. # pre-process distribution
  1737. next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
  1738. next_tokens_scores = logits_warper(generated, next_tokens_scores, cur_len)
  1739. # Store scores, attentions and hidden_states when required
  1740. if not use_xla and return_dict_in_generate:
  1741. if output_scores:
  1742. scores.append(next_tokens_scores)
  1743. if output_attentions and self.config.is_encoder_decoder:
  1744. decoder_attentions.append(model_outputs.decoder_attentions)
  1745. elif output_attentions and not self.config.is_encoder_decoder:
  1746. decoder_attentions.append(model_outputs.attentions)
  1747. if self.config.is_encoder_decoder:
  1748. cross_attentions.append(model_outputs.cross_attentions)
  1749. if output_hidden_states and self.config.is_encoder_decoder:
  1750. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  1751. elif output_hidden_states and self.config.is_encoder_decoder:
  1752. decoder_hidden_states.append(model_outputs.hidden_states)
  1753. # sample
  1754. if seed is not None:
  1755. sample_seed = seed
  1756. else:
  1757. sample_seed = tf.experimental.numpy.random.randint(tf.int32.min, tf.int32.max, (2,), dtype=tf.int32)
  1758. next_tokens = tf.squeeze(
  1759. tf.random.stateless_categorical(
  1760. logits=next_tokens_scores, num_samples=1, seed=sample_seed, dtype=tf.int32
  1761. ),
  1762. axis=1,
  1763. )
  1764. if eos_token_id is not None:
  1765. if pad_token_id is None:
  1766. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  1767. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  1768. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  1769. next_token_is_eos = tf.math.reduce_any(
  1770. tf.equal(
  1771. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  1772. ),
  1773. axis=0,
  1774. )
  1775. finished_sequences = finished_sequences | next_token_is_eos
  1776. # update `generated` and `cur_len`
  1777. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  1778. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  1779. cur_len += 1
  1780. # update model_kwargs
  1781. if use_xla:
  1782. model_kwargs = self._update_model_kwargs_for_xla_generation(
  1783. model_outputs=model_outputs,
  1784. model_kwargs=model_kwargs,
  1785. cur_len=cur_len,
  1786. max_length=max_length,
  1787. batch_size=batch_size,
  1788. is_encoder_decoder=self.config.is_encoder_decoder,
  1789. batch_axis=cache_batch_axis,
  1790. )
  1791. else:
  1792. model_kwargs = self._update_model_kwargs_for_generation(
  1793. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  1794. )
  1795. # if we don't cache past_key_values key values we need the whole input
  1796. if model_kwargs.get("past_key_values", None) is None:
  1797. # let's throw out `past_key_values` since we don't want `None` tensors
  1798. model_kwargs.pop("past_key_values", None)
  1799. return generated, finished_sequences, cur_len, model_kwargs
  1800. # 5. run generation
  1801. # 1st generation step has to be run before to initialize `past_key_values`
  1802. generated, finished_sequences, cur_len, model_kwargs = sample_body_fn(
  1803. generated, finished_sequences, cur_len, model_kwargs
  1804. )
  1805. # 2-to-n generation steps can then be run in autoregressive fashion
  1806. # only in case 1st generation step does NOT yield EOS token though
  1807. maximum_iterations = max_length - cur_len
  1808. generated, _, cur_len, _ = tf.while_loop(
  1809. sample_cond_fn,
  1810. sample_body_fn,
  1811. (generated, finished_sequences, cur_len, model_kwargs),
  1812. maximum_iterations=maximum_iterations,
  1813. )
  1814. # 6. prepare outputs
  1815. if not use_xla:
  1816. # cut for backward compatibility
  1817. generated = generated[:, :cur_len]
  1818. if return_dict_in_generate:
  1819. if self.config.is_encoder_decoder:
  1820. # if model is an encoder-decoder, retrieve encoder attention weights
  1821. # and hidden states
  1822. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  1823. encoder_hidden_states = (
  1824. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  1825. )
  1826. scores = tuple(scores) if scores is not None else None
  1827. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  1828. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  1829. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  1830. return TFSampleEncoderDecoderOutput(
  1831. sequences=generated,
  1832. scores=scores,
  1833. encoder_attentions=encoder_attentions,
  1834. encoder_hidden_states=encoder_hidden_states,
  1835. decoder_attentions=decoder_attentions,
  1836. cross_attentions=cross_attentions,
  1837. decoder_hidden_states=decoder_hidden_states,
  1838. )
  1839. else:
  1840. return TFSampleDecoderOnlyOutput(
  1841. sequences=generated,
  1842. scores=scores,
  1843. attentions=decoder_attentions,
  1844. hidden_states=decoder_hidden_states,
  1845. )
  1846. else:
  1847. return generated
  1848. @staticmethod
  1849. def _gather_beams(nested, beam_indices, batch_axis=0):
  1850. """Gathers the beam slices indexed by beam_indices into new beam array."""
  1851. def gather_fn(tensor):
  1852. if batch_axis > 0:
  1853. # pushes all dimensions before the batch to the end, so we get (batch, beam_id, ...)
  1854. perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
  1855. tensor = tf.transpose(tensor, perm=perm)
  1856. gathered_tensor = tf.gather(params=tensor, indices=beam_indices, axis=1, batch_dims=1)
  1857. if batch_axis > 0:
  1858. # transposes back to the original dimensions
  1859. perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
  1860. perm = tf.math.invert_permutation(perm)
  1861. gathered_tensor = tf.transpose(gathered_tensor, perm=perm)
  1862. return gathered_tensor
  1863. return tf.nest.map_structure(gather_fn, nested)
  1864. def beam_search(
  1865. self,
  1866. input_ids: tf.Tensor,
  1867. do_sample: bool = False,
  1868. max_length: Optional[int] = None,
  1869. pad_token_id: Optional[int] = None,
  1870. eos_token_id: Optional[int] = None,
  1871. length_penalty: Optional[float] = None,
  1872. early_stopping: Optional[Union[bool, str]] = None,
  1873. logits_processor: Optional[TFLogitsProcessorList] = None,
  1874. logits_warper: Optional[TFLogitsProcessorList] = None,
  1875. num_return_sequences: Optional[int] = None,
  1876. output_attentions: Optional[bool] = None,
  1877. output_hidden_states: Optional[bool] = None,
  1878. output_scores: Optional[bool] = None,
  1879. return_dict_in_generate: Optional[bool] = None,
  1880. **model_kwargs,
  1881. ) -> Union[TFBeamSearchOutput, TFBeamSampleOutput, tf.Tensor]:
  1882. r"""
  1883. Generates sequences for models with a language modeling head using beam search. If `do_sample` is `False`, uses
  1884. a greedy approach, otherwise does multinomial sampling without replacement.
  1885. Parameters:
  1886. input_ids (`tf.Tensor` of shape `(batch_size, num_beams, sequence_length)`):
  1887. The sequence used as a prompt for the generation.
  1888. do_sample (`bool`, *optional*, defaults to `False`):
  1889. Whether or not to use sampling ; use greedy decoding otherwise.
  1890. max_length (`int`, *optional*, defaults to 20):
  1891. The maximum length of the sequence to be generated.
  1892. pad_token_id (`int`, *optional*):
  1893. The id of the *padding* token.
  1894. eos_token_id (`Union[int, list[int]]`, *optional*):
  1895. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1896. length_penalty (`float`, *optional*, defaults to 1.0):
  1897. Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent
  1898. to the sequence length, which in turn is used to divide the score of the sequence. Since the score is
  1899. the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences,
  1900. while `length_penalty` < 0.0 encourages shorter sequences.
  1901. early_stopping (`bool` or `str`, *optional*, defaults to `False`):
  1902. Controls the stopping condition for beam-based methods, like beam-search. It accepts the following
  1903. values: `True`, where the generation stops as soon as there are `num_beams` complete candidates;
  1904. `False`, where an heuristic is applied and the generation stops when is it very unlikely to find better
  1905. candidates; `"never"`, where the beam search procedure only stops when there cannot be better
  1906. candidates (canonical beam search algorithm).
  1907. logits_processor (`[TFLogitsProcessorList]`, *optional*):
  1908. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1909. used to modify the prediction scores of the language modeling head applied at each generation step.
  1910. logits_warper (`TFLogitsProcessorList`, *optional*):
  1911. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  1912. used to warp the prediction score distribution of the language modeling head applied before multinomial
  1913. sampling at each generation step.
  1914. num_return_sequences(`int`, *optional*, defaults to 1):
  1915. The number of independently computed returned sequences for each element in the batch.
  1916. output_attentions (`bool`, *optional*, defaults to `False`):
  1917. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1918. returned tensors for more details.
  1919. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1920. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1921. for more details.
  1922. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1923. Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
  1924. model_kwargs:
  1925. Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
  1926. encoder-decoder model the kwargs should include `encoder_outputs`.
  1927. Return:
  1928. [`~generation.TFBeamSearchDecoderOnlyOutput`], [`~generation.TFBeamSearchEncoderDecoderOutput`] or
  1929. `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
  1930. [`~generation.TFBeamSearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1931. `return_dict_in_generate=True` or a [`~generation.TFBeamSearchEncoderDecoderOutput`] if
  1932. `model.config.is_encoder_decoder=True`.
  1933. Examples:
  1934. ```python
  1935. >>> from transformers import (
  1936. ... AutoTokenizer,
  1937. ... TFAutoModelForSeq2SeqLM,
  1938. ... TFLogitsProcessorList,
  1939. ... TFMinLengthLogitsProcessor,
  1940. ... )
  1941. >>> import tensorflow as tf
  1942. >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
  1943. >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
  1944. >>> encoder_input_str = "translate English to German: How old are you?"
  1945. >>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="tf").input_ids
  1946. >>> # lets run beam search using 3 beams
  1947. >>> num_beams = 3
  1948. >>> # define decoder start token ids
  1949. >>> input_ids = tf.ones((1, num_beams, 1), dtype=tf.int32)
  1950. >>> input_ids = input_ids * model.generation_config.decoder_start_token_id
  1951. >>> # add encoder_outputs to model keyword arguments
  1952. >>> encoder_outputs = model.get_encoder()(encoder_input_ids, return_dict=True)
  1953. >>> encoder_outputs.last_hidden_state = tf.repeat(
  1954. ... tf.expand_dims(encoder_outputs.last_hidden_state, axis=0), num_beams, axis=1
  1955. ... )
  1956. >>> model_kwargs = {"encoder_outputs": encoder_outputs}
  1957. >>> # instantiate logits processors
  1958. >>> logits_processor = TFLogitsProcessorList(
  1959. ... [TFMinLengthLogitsProcessor(5, eos_token_id=model.generation_config.eos_token_id)]
  1960. ... )
  1961. >>> outputs = model.beam_search(input_ids, logits_processor=logits_processor, **model_kwargs)
  1962. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1963. ['Wie alt bist du?']
  1964. ```"""
  1965. def flatten_beam_dim(tensor, batch_axis=0):
  1966. """Flattens the first two dimensions of a non-scalar array."""
  1967. shape = shape_list(tensor)
  1968. return tf.reshape(
  1969. tensor,
  1970. shape[:batch_axis] + [shape[batch_axis] * shape[batch_axis + 1]] + shape[batch_axis + 2 :],
  1971. )
  1972. def unflatten_beam_dim(tensor, num_beams, batch_axis=0):
  1973. """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
  1974. shape = shape_list(tensor)
  1975. return tf.reshape(tensor, shape[:batch_axis] + [-1, num_beams] + shape[batch_axis + 1 :])
  1976. # 1. init beam_search values
  1977. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1978. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  1979. max_length = max_length if max_length is not None else self.generation_config.max_length
  1980. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1981. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1982. if isinstance(eos_token_id, int):
  1983. eos_token_id = [eos_token_id]
  1984. num_return_sequences = (
  1985. num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
  1986. )
  1987. output_attentions = (
  1988. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1989. )
  1990. output_hidden_states = (
  1991. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1992. )
  1993. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1994. return_dict_in_generate = (
  1995. return_dict_in_generate
  1996. if return_dict_in_generate is not None
  1997. else self.generation_config.return_dict_in_generate
  1998. )
  1999. length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
  2000. early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
  2001. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  2002. use_xla = not tf.executing_eagerly()
  2003. # TODO (Joao): fix cache format or find programmatic way to detect cache index
  2004. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  2005. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  2006. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  2007. # some models, like XLNet, need more than the last token in the presence of past_key_values
  2008. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  2009. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  2010. all_scores = [] if (return_dict_in_generate and output_scores) else None
  2011. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2012. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2013. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  2014. # 3. init tensors to use for "xla-compileable" generate function
  2015. batch_size, num_beams, cur_len = shape_list(input_ids)
  2016. # store the prompt length of decoder
  2017. decoder_prompt_len = cur_len
  2018. # per batch, beam-item holding current token in loop, pre-populated with `pad_token_id`
  2019. input_ids_padding = tf.ones((batch_size, num_beams, max_length - cur_len), dtype=tf.int32) * (
  2020. pad_token_id or 0
  2021. )
  2022. running_sequences = tf.concat([input_ids, input_ids_padding], axis=-1)
  2023. sequences = tf.ones((batch_size, num_beams, max_length), dtype=tf.int32) * (pad_token_id or 0)
  2024. # per batch,beam-item state bit indicating if sentence has finished.
  2025. is_sent_finished = tf.zeros((batch_size, num_beams), dtype=tf.bool)
  2026. # per batch, beam-item score, logprobs
  2027. running_scores = tf.tile(
  2028. tf.expand_dims(tf.convert_to_tensor([0.0] + [-1.0e9] * (num_beams - 1)), axis=0), [batch_size, 1]
  2029. )
  2030. scores = tf.ones((batch_size, num_beams)) * -1.0e9
  2031. # per batch beam indices
  2032. running_beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
  2033. beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
  2034. # flatten beam dim
  2035. if "encoder_outputs" in model_kwargs:
  2036. model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
  2037. model_kwargs["encoder_outputs"]["last_hidden_state"]
  2038. )
  2039. if "attention_mask" in model_kwargs:
  2040. model_kwargs["attention_mask"] = flatten_beam_dim(model_kwargs["attention_mask"])
  2041. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  2042. # define stop-condition and auto-regressive function
  2043. def beam_search_cond_fn(
  2044. cur_len,
  2045. running_sequences,
  2046. running_scores,
  2047. running_beam_indices,
  2048. sequences,
  2049. scores,
  2050. beam_indices,
  2051. is_sent_finished,
  2052. decoder_prompt_len,
  2053. model_kwargs,
  2054. ):
  2055. """
  2056. Beam Search termination condition function -- halts the generation loop if any of these conditions becomes
  2057. False
  2058. """
  2059. # 1. is less than max length?
  2060. not_max_length_yet = cur_len < max_length
  2061. # 2. can the new beams still improve?
  2062. # early_stopping == False -> apply heuristic = always get the best score from `cur_len - decoder_prompt_len`. See the discussion
  2063. # below for more details.
  2064. # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
  2065. # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
  2066. # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
  2067. if early_stopping == "never" and length_penalty > 0.0:
  2068. best_running_score = running_scores[:, :1] / ((max_length - decoder_prompt_len) ** length_penalty)
  2069. else:
  2070. best_running_score = running_scores[:, :1] / (
  2071. tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty
  2072. )
  2073. worst_finished_score = tf.where(
  2074. is_sent_finished, tf.math.reduce_min(scores, axis=1, keepdims=True), -1.0e9
  2075. )
  2076. improvement_still_possible = tf.math.reduce_any(best_running_score > worst_finished_score)
  2077. # 3. is there still a beam that has not finished?
  2078. still_open_beam = ~(tf.math.reduce_all(is_sent_finished) & (early_stopping is True))
  2079. return not_max_length_yet & still_open_beam & improvement_still_possible
  2080. def beam_search_body_fn(
  2081. cur_len,
  2082. running_sequences,
  2083. running_scores,
  2084. running_beam_indices,
  2085. sequences,
  2086. scores,
  2087. beam_indices,
  2088. is_sent_finished,
  2089. decoder_prompt_len,
  2090. model_kwargs,
  2091. ):
  2092. """
  2093. Beam Search iterative update function -- each iteration adds a new token and updates the best sequences
  2094. seen so far
  2095. """
  2096. # 1. Forward current tokens
  2097. if model_kwargs.get("past_key_values") is None or needs_full_input:
  2098. input_ids = running_sequences[:, :, :cur_len]
  2099. else:
  2100. input_ids = tf.expand_dims(running_sequences[:, :, cur_len - 1], -1)
  2101. model_inputs = self.prepare_inputs_for_generation(
  2102. flatten_beam_dim(input_ids), use_cache=use_cache, **model_kwargs
  2103. )
  2104. model_outputs = self(
  2105. **model_inputs,
  2106. return_dict=True,
  2107. output_attentions=output_attentions,
  2108. output_hidden_states=output_hidden_states,
  2109. )
  2110. logits = unflatten_beam_dim(model_outputs.logits[:, -1], num_beams)
  2111. # 2. Compute log probs
  2112. # get log probabilities from logits, process logits with processors (*e.g.* min_length, ...), and
  2113. # add new logprobs to existing running logprobs scores.
  2114. log_probs = tf.nn.log_softmax(logits)
  2115. log_probs = logits_processor(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
  2116. log_probs = unflatten_beam_dim(log_probs, num_beams)
  2117. if do_sample:
  2118. log_probs = logits_warper(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
  2119. log_probs = unflatten_beam_dim(log_probs, num_beams)
  2120. log_probs_processed = log_probs
  2121. log_probs = log_probs + tf.expand_dims(running_scores, axis=2)
  2122. vocab_size = log_probs.shape[2]
  2123. log_probs = tf.reshape(log_probs, (batch_size, num_beams * vocab_size))
  2124. # Store scores, attentions and hidden_states when required
  2125. if not use_xla and return_dict_in_generate:
  2126. if output_scores:
  2127. all_scores.append(
  2128. logits_warper(
  2129. flatten_beam_dim(running_sequences),
  2130. flatten_beam_dim(log_probs_processed),
  2131. cur_len,
  2132. )
  2133. )
  2134. if output_attentions and self.config.is_encoder_decoder:
  2135. decoder_attentions.append(model_outputs.decoder_attentions)
  2136. elif output_attentions and not self.config.is_encoder_decoder:
  2137. decoder_attentions.append(model_outputs.attentions)
  2138. if self.config.is_encoder_decoder:
  2139. cross_attentions.append(model_outputs.cross_attentions)
  2140. if output_hidden_states and self.config.is_encoder_decoder:
  2141. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  2142. elif output_hidden_states and self.config.is_encoder_decoder:
  2143. decoder_hidden_states.append(model_outputs.hidden_states)
  2144. # 3. Retrieve top-K
  2145. # Each item in batch has num_beams * vocab_size candidate sequences. For each item, get the top 2*k
  2146. # candidates with the highest log-probabilities. We gather the top 2*K beams here so that even if the
  2147. # best K sequences reach EOS simultaneously, we have another K sequences remaining to continue the live
  2148. # beam search.
  2149. # Gather the top 2*K scores from _all_ beams.
  2150. # Gather 2*k top beams.
  2151. # Recover the beam index by floor division.
  2152. # Recover token id by modulo division and expand Id array for broadcasting.
  2153. # Update sequences for the 2*K top-k new sequences.
  2154. beams_to_keep = 2 * num_beams
  2155. if do_sample:
  2156. topk_indices = sample_without_replacement(log_probs, beams_to_keep)
  2157. topk_log_probs = tf.gather(log_probs, topk_indices, axis=1, batch_dims=1)
  2158. else:
  2159. topk_log_probs, topk_indices = tf.math.top_k(log_probs, k=beams_to_keep)
  2160. topk_current_beam_indices = topk_indices // vocab_size
  2161. topk_running_beam_indices = self._gather_beams(running_beam_indices, topk_current_beam_indices)
  2162. topk_running_sequences = self._gather_beams(running_sequences, topk_current_beam_indices)
  2163. topk_ids = topk_indices % vocab_size
  2164. # writes the new token
  2165. indices_batch = tf.repeat(tf.range(batch_size), [beams_to_keep])
  2166. indices_beam = tf.tile(tf.range(beams_to_keep), [batch_size])
  2167. update_indices = tf.stack(
  2168. [indices_batch, indices_beam, tf.broadcast_to(cur_len, [batch_size * beams_to_keep])], axis=-1
  2169. )
  2170. topk_sequences = tf.tensor_scatter_nd_update(
  2171. tensor=topk_running_sequences,
  2172. indices=update_indices,
  2173. updates=tf.reshape(topk_ids, [batch_size * beams_to_keep]),
  2174. )
  2175. # we want to store the beam indices with batch information -> real beam index = beam index % num beams
  2176. batch_modified_indices = topk_current_beam_indices + tf.broadcast_to(
  2177. tf.expand_dims(tf.range(batch_size) * num_beams, axis=1), topk_current_beam_indices.shape
  2178. )
  2179. update_indices = tf.stack(
  2180. [
  2181. indices_batch,
  2182. indices_beam,
  2183. tf.broadcast_to(cur_len - decoder_prompt_len, [batch_size * beams_to_keep]),
  2184. ],
  2185. axis=-1,
  2186. )
  2187. topk_beam_indices = tf.tensor_scatter_nd_update(
  2188. tensor=topk_running_beam_indices,
  2189. indices=update_indices,
  2190. updates=tf.reshape(batch_modified_indices, [batch_size * beams_to_keep]),
  2191. )
  2192. # 4. Check which sequences have ended
  2193. # Update current sequences: Did the top `num_beams` sequences reach an end marker?
  2194. # To prevent these just finished sequences from being added to the current sequences
  2195. # set of active beam search sequences, set their log probs to a very large negative value.
  2196. if eos_token_id is None:
  2197. eos_in_next_token = tf.zeros(topk_sequences[:, :, cur_len].shape, dtype=tf.bool)
  2198. else:
  2199. eos_in_next_token = tf.math.reduce_any(
  2200. tf.equal(
  2201. tf.broadcast_to(
  2202. topk_sequences[:, :, cur_len],
  2203. [len(eos_token_id)] + topk_sequences[:, :, cur_len].shape,
  2204. ),
  2205. tf.expand_dims(tf.expand_dims(eos_token_id, -1), -1),
  2206. ),
  2207. axis=0,
  2208. )
  2209. did_topk_just_finished = eos_in_next_token & tf.broadcast_to(
  2210. tf.concat((tf.ones((num_beams), dtype=tf.bool), tf.zeros((num_beams), dtype=tf.bool)), axis=0),
  2211. shape_list(eos_in_next_token),
  2212. )
  2213. # non-top `num_beams` eos tokens can't be used to finish a beam, but the others can't be used in the next
  2214. # running sentences either
  2215. running_topk_log_probs = topk_log_probs + tf.cast(eos_in_next_token, tf.float32) * -1.0e9
  2216. # 5. Get running sequences scores for next
  2217. # Determine the top k beam indices (from top 2*k beams) from log probs and gather top k beams
  2218. # (from top 2*k beams).
  2219. next_topk_indices = tf.math.top_k(running_topk_log_probs, k=num_beams)[1]
  2220. next_running_sequences, next_running_scores, next_running_beam_indices = self._gather_beams(
  2221. [topk_sequences, running_topk_log_probs, topk_beam_indices], next_topk_indices
  2222. )
  2223. # 6. Process topk logits
  2224. # Further process log probs:
  2225. # - add length penalty
  2226. # - make sure no scores can be added anymore if beam is full
  2227. # - make sure still running sequences cannot be chosen as finalized beam
  2228. topk_log_probs = topk_log_probs / (
  2229. tf.cast(cur_len + 1 - decoder_prompt_len, dtype=tf.float32) ** length_penalty
  2230. )
  2231. beams_in_batch_are_full = tf.broadcast_to(
  2232. tf.math.reduce_all(is_sent_finished, axis=-1, keepdims=True), shape_list(did_topk_just_finished)
  2233. ) & (early_stopping is True)
  2234. add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
  2235. topk_log_probs += tf.cast(add_penalty, tf.float32) * -1.0e9
  2236. # 7. Get scores, sequences, is sentence finished for next.
  2237. # Combine sequences, scores, and flags along the beam dimension and compare new finished sequence scores
  2238. # to existing finished scores and select the best from the new set of beams
  2239. merged_sequences = tf.concat([sequences, topk_sequences], axis=1)
  2240. merged_scores = tf.concat([scores, topk_log_probs], axis=1)
  2241. merged_beams = tf.concat([beam_indices, topk_beam_indices], axis=1)
  2242. merged_is_sent_finished = tf.concat([is_sent_finished, did_topk_just_finished], axis=1)
  2243. topk_merged_indices = tf.math.top_k(merged_scores, k=num_beams)[1]
  2244. next_sequences, next_scores, next_beam_indices, next_is_sent_finished = self._gather_beams(
  2245. [merged_sequences, merged_scores, merged_beams, merged_is_sent_finished], topk_merged_indices
  2246. )
  2247. # 8. Prepare data for the next iteration
  2248. # Determine the top k beam indices from the original set of all beams. With these, gather the top k
  2249. # beam-associated caches.
  2250. cur_len = cur_len + 1
  2251. if "past_key_values" in model_outputs:
  2252. cache = tf.nest.map_structure(
  2253. lambda tensor: unflatten_beam_dim(tensor, num_beams, batch_axis=cache_batch_axis),
  2254. model_outputs.past_key_values,
  2255. )
  2256. next_running_indices = self._gather_beams(topk_current_beam_indices, next_topk_indices)
  2257. next_cache = self._gather_beams(cache, next_running_indices, batch_axis=cache_batch_axis)
  2258. model_outputs["past_key_values"] = tf.nest.map_structure(
  2259. lambda tensor: flatten_beam_dim(tensor, batch_axis=cache_batch_axis), next_cache
  2260. )
  2261. if use_xla:
  2262. next_model_kwargs = self._update_model_kwargs_for_xla_generation(
  2263. model_outputs=model_outputs,
  2264. model_kwargs=model_kwargs,
  2265. cur_len=cur_len,
  2266. max_length=max_length,
  2267. batch_size=(batch_size * num_beams),
  2268. is_encoder_decoder=self.config.is_encoder_decoder,
  2269. batch_axis=cache_batch_axis,
  2270. )
  2271. else:
  2272. next_model_kwargs = self._update_model_kwargs_for_generation(
  2273. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2274. )
  2275. # if we don't cache past_key_values key values we need the whole input
  2276. if model_kwargs.get("past_key_values", None) is None:
  2277. # let's throw out `past_key_values` since we don't want `None` tensors
  2278. model_kwargs.pop("past_key_values", None)
  2279. return (
  2280. cur_len,
  2281. next_running_sequences,
  2282. next_running_scores,
  2283. next_running_beam_indices,
  2284. next_sequences,
  2285. next_scores,
  2286. next_beam_indices,
  2287. next_is_sent_finished,
  2288. decoder_prompt_len,
  2289. next_model_kwargs,
  2290. )
  2291. # 5. run generation
  2292. # 1st generation step has to be run before to initialize `past_key_values` (if active)
  2293. (
  2294. cur_len,
  2295. running_sequences,
  2296. running_scores,
  2297. running_beam_indices,
  2298. sequences,
  2299. scores,
  2300. beam_indices,
  2301. is_sent_finished,
  2302. decoder_prompt_len,
  2303. model_kwargs,
  2304. ) = beam_search_body_fn(
  2305. cur_len,
  2306. running_sequences,
  2307. running_scores,
  2308. running_beam_indices,
  2309. sequences,
  2310. scores,
  2311. beam_indices,
  2312. is_sent_finished,
  2313. decoder_prompt_len,
  2314. model_kwargs,
  2315. )
  2316. # 2-to-n generation steps can then be run in autoregressive fashion (only in case 1st generation step does
  2317. # NOT yield EOS token though)
  2318. maximum_iterations = max_length - cur_len
  2319. (
  2320. cur_len,
  2321. running_sequences,
  2322. running_scores,
  2323. running_beam_indices,
  2324. sequences,
  2325. scores,
  2326. beam_indices,
  2327. is_sent_finished,
  2328. decoder_prompt_len,
  2329. _,
  2330. ) = tf.while_loop(
  2331. beam_search_cond_fn,
  2332. beam_search_body_fn,
  2333. (
  2334. cur_len,
  2335. running_sequences,
  2336. running_scores,
  2337. running_beam_indices,
  2338. sequences,
  2339. scores,
  2340. beam_indices,
  2341. is_sent_finished,
  2342. decoder_prompt_len,
  2343. model_kwargs,
  2344. ),
  2345. maximum_iterations=maximum_iterations,
  2346. )
  2347. # 6. prepare outputs
  2348. # Account for the edge-case where there are no finished sequences for a particular batch item. If so, return
  2349. # running sequences for that batch item.
  2350. none_finished = tf.math.reduce_any(is_sent_finished, axis=1)
  2351. sequences = tf.where(none_finished[:, None, None], sequences, running_sequences)
  2352. beam_indices = tf.where(none_finished[:, None, None], beam_indices, running_beam_indices)
  2353. # Apply the length penalty so that running scores match the finalized scores if they are used
  2354. running_scores = running_scores / (tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty)
  2355. scores = tf.where(none_finished[:, None], scores, running_scores)
  2356. # Take best beams for each batch (the score is sorted in descending order)
  2357. sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
  2358. scores = flatten_beam_dim(scores[:, :num_return_sequences])
  2359. beam_indices = flatten_beam_dim(beam_indices[:, :num_return_sequences, :])
  2360. if not use_xla:
  2361. # Cut for backward compatibility
  2362. sequences = sequences[:, :cur_len]
  2363. beam_indices = beam_indices[:, : cur_len - decoder_prompt_len]
  2364. if return_dict_in_generate:
  2365. if self.config.is_encoder_decoder:
  2366. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2367. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2368. encoder_hidden_states = (
  2369. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2370. )
  2371. output_cls = TFBeamSampleEncoderDecoderOutput if do_sample else TFBeamSearchEncoderDecoderOutput
  2372. return output_cls(
  2373. sequences=sequences,
  2374. sequences_scores=scores,
  2375. scores=all_scores,
  2376. beam_indices=beam_indices,
  2377. encoder_attentions=encoder_attentions,
  2378. encoder_hidden_states=encoder_hidden_states,
  2379. decoder_attentions=decoder_attentions,
  2380. cross_attentions=cross_attentions,
  2381. decoder_hidden_states=decoder_hidden_states,
  2382. )
  2383. else:
  2384. output_cls = TFBeamSampleDecoderOnlyOutput if do_sample else TFBeamSearchDecoderOnlyOutput
  2385. return output_cls(
  2386. sequences=sequences,
  2387. sequences_scores=scores,
  2388. scores=all_scores,
  2389. beam_indices=beam_indices,
  2390. attentions=decoder_attentions,
  2391. hidden_states=decoder_hidden_states,
  2392. )
  2393. else:
  2394. return sequences
  2395. def contrastive_search(
  2396. self,
  2397. input_ids: tf.Tensor,
  2398. top_k: Optional[int] = 1,
  2399. penalty_alpha: Optional[float] = 0,
  2400. logits_processor: Optional[TFLogitsProcessorList] = None,
  2401. logits_warper: Optional[TFLogitsProcessorList] = None,
  2402. max_length: Optional[int] = None,
  2403. pad_token_id: Optional[int] = None,
  2404. eos_token_id: Optional[int] = None,
  2405. output_attentions: Optional[bool] = None,
  2406. output_hidden_states: Optional[bool] = None,
  2407. output_scores: Optional[bool] = None,
  2408. return_dict_in_generate: Optional[bool] = None,
  2409. **model_kwargs,
  2410. ) -> Union[TFContrastiveSearchOutput, tf.Tensor]:
  2411. r"""
  2412. Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
  2413. be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2414. Parameters:
  2415. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  2416. The sequence used as a prompt for the generation.
  2417. top_k (`int`, *optional*, defaults to 1):
  2418. The size of the candidate set that is used to re-rank for contrastive search
  2419. penalty_alpha (`float`, *optional*, defaults to 0):
  2420. The degeneration penalty for contrastive search; activate when it is larger than 0
  2421. logits_processor (`TFLogitsProcessorList`, *optional*):
  2422. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  2423. used to modify the prediction scores of the language modeling head applied at each generation step.
  2424. logits_warper (`TFLogitsProcessorList`, *optional*):
  2425. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  2426. used to warp the prediction score distribution of the language modeling head applied before multinomial
  2427. sampling at each generation step.
  2428. max_length (`int`, *optional*, defaults to 20):
  2429. The maximum length of the sequence to be generated.
  2430. pad_token_id (`int`, *optional*):
  2431. The id of the *padding* token.
  2432. eos_token_id (`Union[int, list[int]]`, *optional*):
  2433. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  2434. output_attentions (`bool`, *optional*, defaults to `False`):
  2435. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  2436. returned tensors for more details.
  2437. output_hidden_states (`bool`, *optional*, defaults to `False`):
  2438. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  2439. for more details.
  2440. output_scores (`bool`, *optional*, defaults to `False`):
  2441. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  2442. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  2443. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  2444. model_kwargs:
  2445. Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
  2446. model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  2447. Return:
  2448. [`~generation.TFContrastiveSearchDecoderOnlyOutput`],
  2449. [`~generation.TFContrastiveSearchEncoderDecoderOutput`] or `tf.Tensor`: A `tf.Tensor` containing the
  2450. generated tokens (default behaviour) or a [`~generation.TFContrastiveySearchDecoderOnlyOutput`] if
  2451. `model.config.is_encoder_decoder=False` and `return_dict_in_generate=True` or a
  2452. [`~generation.TFContrastiveSearchEncoderDecoderOutput`] if `model.config.is_encoder_decoder=True`.
  2453. Examples:
  2454. ```python
  2455. >>> from transformers import AutoTokenizer, TFAutoModelForCausalLM
  2456. >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
  2457. >>> model = TFAutoModelForCausalLM.from_pretrained("facebook/opt-125m")
  2458. >>> # set pad_token_id to eos_token_id because OPT does not have a PAD token
  2459. >>> model.config.pad_token_id = model.config.eos_token_id
  2460. >>> input_prompt = "DeepMind Company is"
  2461. >>> input_ids = tokenizer(input_prompt, return_tensors="tf")
  2462. >>> outputs = model.contrastive_search(**input_ids, penalty_alpha=0.6, top_k=4, max_length=64)
  2463. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  2464. ['DeepMind Company is a company that focuses on the development and commercialization of artificial intelligence (AI). DeepMind’s mission is to help people understand and solve problems that are difficult to solve in the world today.\n\nIn this post, we talk about the benefits of deep learning in business and how it']
  2465. ```"""
  2466. def gather_best_candidate(nested, selected_idx_stacked, batch_axis=0):
  2467. """Gathers the slices indexed by selected_idx_stacked from a potentially nested structure of tensors."""
  2468. def gather_fn(tensor):
  2469. gathered_tensor = tf.gather(params=tensor, indices=selected_idx_stacked, axis=batch_axis)
  2470. return gathered_tensor
  2471. return tf.nest.map_structure(gather_fn, nested)
  2472. # 1. init greedy_search values
  2473. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  2474. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  2475. max_length = max_length if max_length is not None else self.generation_config.max_length
  2476. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  2477. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  2478. if isinstance(eos_token_id, int):
  2479. eos_token_id = [eos_token_id]
  2480. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  2481. output_attentions = (
  2482. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  2483. )
  2484. output_hidden_states = (
  2485. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  2486. )
  2487. return_dict_in_generate = (
  2488. return_dict_in_generate
  2489. if return_dict_in_generate is not None
  2490. else self.generation_config.return_dict_in_generate
  2491. )
  2492. use_cache = True # In contrastive search, we always use cache
  2493. model_kwargs.pop("use_cache", None)
  2494. use_xla = not tf.executing_eagerly()
  2495. # TODO (Joao): fix cache format or find programmatic way to detect cache index
  2496. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  2497. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  2498. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  2499. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  2500. scores = [] if (return_dict_in_generate and output_scores) else None
  2501. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2502. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2503. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  2504. # 3. init tensors to use for "xla-compileable" generate function
  2505. batch_size, cur_len = shape_list(input_ids)
  2506. # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
  2507. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  2508. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  2509. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  2510. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  2511. # define condition fn
  2512. def contrastive_search_cond_fn(
  2513. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2514. ):
  2515. """state termination condition fn."""
  2516. return ~tf.reduce_all(finished_sequences)
  2517. # define condition fn
  2518. def contrastive_search_body_fn(
  2519. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2520. ):
  2521. """state update fn."""
  2522. # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
  2523. # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
  2524. if model_kwargs.get("past_key_values") is None:
  2525. # prepare inputs
  2526. model_inputs = self.prepare_inputs_for_generation(
  2527. generated[:, :cur_len], use_cache=use_cache, **model_kwargs
  2528. )
  2529. # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
  2530. # the `encoder_outputs`
  2531. outputs = self(
  2532. **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
  2533. )
  2534. # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
  2535. # previous tokens)
  2536. if self.config.is_encoder_decoder:
  2537. last_hidden_states = outputs.decoder_hidden_states[-1]
  2538. else:
  2539. last_hidden_states = outputs.hidden_states[-1]
  2540. # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
  2541. # iterations (with fixed shapes)
  2542. if use_xla:
  2543. last_hidden_states = tf.pad(last_hidden_states, [[0, 0], [0, max_length - cur_len], [0, 0]])
  2544. # next logit for contrastive search to select top-k candidate tokens
  2545. logit_for_next_step = outputs.logits[:, -1, :]
  2546. if use_xla:
  2547. model_kwargs = self._update_model_kwargs_for_xla_generation(
  2548. model_outputs=outputs,
  2549. model_kwargs=model_kwargs,
  2550. cur_len=cur_len,
  2551. max_length=max_length,
  2552. batch_size=batch_size,
  2553. is_encoder_decoder=self.config.is_encoder_decoder,
  2554. batch_axis=cache_batch_axis,
  2555. )
  2556. else:
  2557. model_kwargs = self._update_model_kwargs_for_generation(
  2558. outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2559. )
  2560. # Expands model inputs top_k times, for batched forward passes (akin to beam search).
  2561. _, model_kwargs = self._expand_inputs_for_generation(
  2562. expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
  2563. )
  2564. past_key_values = model_kwargs.get("past_key_values")
  2565. if past_key_values is None:
  2566. raise ValueError(
  2567. f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
  2568. "for contrastive search."
  2569. )
  2570. elif (
  2571. not isinstance(past_key_values[0], (tuple, tf.Tensor))
  2572. or past_key_values[0][0].shape[0] != batch_size
  2573. ):
  2574. raise ValueError(
  2575. f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
  2576. "used for contrastive search without further modifications."
  2577. )
  2578. else:
  2579. logit_for_next_step = next_step_cached_variables["logit_for_next_step"]
  2580. last_hidden_states = next_step_cached_variables["last_hidden_states"]
  2581. outputs = next_step_cached_variables["outputs"]
  2582. # contrastive_search main logic start:
  2583. # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
  2584. # degeneration penalty
  2585. logit_for_next_step = logits_processor(generated, logit_for_next_step, cur_len)
  2586. logit_for_next_step = logits_warper(generated, logit_for_next_step, cur_len)
  2587. next_probs = stable_softmax(logit_for_next_step, axis=-1)
  2588. top_k_probs, top_k_ids = tf.math.top_k(next_probs, k=top_k)
  2589. # Store scores, attentions and hidden_states when required
  2590. if not use_xla and return_dict_in_generate:
  2591. if output_scores:
  2592. scores.append(logit_for_next_step)
  2593. if output_attentions and self.config.is_encoder_decoder:
  2594. decoder_attentions.append(outputs.decoder_attentions)
  2595. elif output_attentions and not self.config.is_encoder_decoder:
  2596. decoder_attentions.append(outputs.attentions)
  2597. if self.config.is_encoder_decoder:
  2598. cross_attentions.append(outputs.cross_attentions)
  2599. if output_hidden_states and self.config.is_encoder_decoder:
  2600. decoder_hidden_states.append(outputs.decoder_hidden_states)
  2601. elif output_hidden_states and self.config.is_encoder_decoder:
  2602. decoder_hidden_states.append(outputs.hidden_states)
  2603. # Replicates the new past_key_values to match the `top_k` candidates
  2604. model_kwargs["past_key_values"] = tf.nest.map_structure(
  2605. lambda tensor: tf.repeat(tensor, top_k, axis=cache_batch_axis), model_kwargs["past_key_values"]
  2606. )
  2607. # compute the candidate tokens by the language model and collects their hidden_states
  2608. next_model_inputs = self.prepare_inputs_for_generation(
  2609. tf.reshape(top_k_ids, [-1, 1]), use_cache=use_cache, **model_kwargs
  2610. )
  2611. outputs = self(
  2612. **next_model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
  2613. )
  2614. next_past_key_values = self._extract_past_from_model_output(outputs)
  2615. logits = outputs.logits[:, -1, :]
  2616. # name is different for encoder-decoder and decoder-only models
  2617. if self.config.is_encoder_decoder:
  2618. next_hidden = outputs.decoder_hidden_states[-1]
  2619. full_hidden_states = outputs.decoder_hidden_states
  2620. else:
  2621. next_hidden = outputs.hidden_states[-1]
  2622. full_hidden_states = outputs.hidden_states
  2623. context_hidden = tf.repeat(last_hidden_states[:, :cur_len, :], top_k, axis=0)
  2624. # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
  2625. # model confidence
  2626. selected_idx = _ranking_fast(context_hidden, next_hidden, top_k_probs, penalty_alpha, top_k)
  2627. # converts indices to a dimension of top_k to the stacked top_k * batch_size dimension, for indexing
  2628. # without a need to reshape on tensors that have these two dimensions stacked
  2629. selected_idx_stacked = selected_idx + tf.range(selected_idx.shape[0], dtype=tf.int64) * top_k
  2630. # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
  2631. # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
  2632. # (model confidence minus degeneration penalty); (6) decoder hidden_states
  2633. next_tokens = tf.gather(top_k_ids, selected_idx, axis=1, batch_dims=1)
  2634. next_hidden = gather_best_candidate(next_hidden, selected_idx_stacked)
  2635. # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
  2636. # iterations (with fixed shapes)
  2637. if use_xla:
  2638. last_hidden_states = dynamic_update_slice(last_hidden_states, next_hidden, [0, cur_len, 0])
  2639. else:
  2640. last_hidden_states = tf.concat([last_hidden_states, next_hidden], axis=1)
  2641. next_decoder_hidden_states = gather_best_candidate(full_hidden_states, selected_idx_stacked)
  2642. next_past_key_values = gather_best_candidate(
  2643. next_past_key_values, selected_idx_stacked, batch_axis=cache_batch_axis
  2644. )
  2645. logit_for_next_step = gather_best_candidate(logits, selected_idx_stacked)
  2646. # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
  2647. if self.config.is_encoder_decoder:
  2648. next_step_cross_attentions = ()
  2649. next_step_decoder_attentions = ()
  2650. if output_attentions:
  2651. next_step_cross_attentions = gather_best_candidate(outputs.cross_attentions, selected_idx_stacked)
  2652. next_step_decoder_attentions = gather_best_candidate(
  2653. outputs.decoder_attentions, selected_idx_stacked
  2654. )
  2655. outputs = TFSeq2SeqLMOutput(
  2656. past_key_values=next_past_key_values,
  2657. decoder_hidden_states=next_decoder_hidden_states,
  2658. decoder_attentions=next_step_decoder_attentions or None,
  2659. cross_attentions=next_step_cross_attentions or None,
  2660. )
  2661. else:
  2662. next_step_attentions = ()
  2663. if output_attentions:
  2664. next_step_attentions = gather_best_candidate(outputs.attentions, selected_idx_stacked)
  2665. outputs = TFCausalLMOutputWithPast(
  2666. past_key_values=next_past_key_values,
  2667. hidden_states=next_decoder_hidden_states,
  2668. attentions=next_step_attentions or None,
  2669. )
  2670. # contrastive_search main logic end
  2671. if eos_token_id is not None:
  2672. if pad_token_id is None:
  2673. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  2674. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  2675. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  2676. next_token_is_eos = tf.math.reduce_any(
  2677. tf.equal(
  2678. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  2679. ),
  2680. axis=0,
  2681. )
  2682. finished_sequences = finished_sequences | next_token_is_eos
  2683. # update `generated` and `cur_len`
  2684. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  2685. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  2686. cur_len += 1
  2687. if use_xla:
  2688. # NOTE: 1) relative to other generation strategies, contrastive search is always running forward
  2689. # passes one step ahead -- hence the `cur_len=cur_len + 1`; 2) the attention mask here is expanded from
  2690. # [batch_size, ...] to [batch_size*top_k, ...] -- hence the `batch_size=batch_size * top_k`
  2691. model_kwargs = self._update_model_kwargs_for_xla_generation(
  2692. model_outputs=outputs,
  2693. model_kwargs=model_kwargs,
  2694. cur_len=cur_len + 1,
  2695. max_length=max_length,
  2696. batch_size=batch_size * top_k,
  2697. is_encoder_decoder=self.config.is_encoder_decoder,
  2698. batch_axis=cache_batch_axis,
  2699. )
  2700. else:
  2701. model_kwargs = self._update_model_kwargs_for_generation(
  2702. outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2703. )
  2704. next_step_cached_variables = {
  2705. "logit_for_next_step": logit_for_next_step,
  2706. "last_hidden_states": last_hidden_states,
  2707. "outputs": outputs,
  2708. }
  2709. return generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2710. # 5. run generation
  2711. # 1st generation step has to be run before to initialize `past_key_values`
  2712. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables = contrastive_search_body_fn(
  2713. generated, finished_sequences, cur_len, model_kwargs, None
  2714. )
  2715. # 2-to-n generation steps can then be run in autoregressive fashion
  2716. # only in case 1st generation step does NOT yield EOS token though
  2717. maximum_iterations = max_length - cur_len
  2718. generated, _, cur_len, _, _ = tf.while_loop(
  2719. contrastive_search_cond_fn,
  2720. contrastive_search_body_fn,
  2721. (generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables),
  2722. maximum_iterations=maximum_iterations,
  2723. )
  2724. # 6. prepare outputs
  2725. if not use_xla:
  2726. # cut for backward compatibility
  2727. generated = generated[:, :cur_len]
  2728. if return_dict_in_generate:
  2729. if self.config.is_encoder_decoder:
  2730. # if model is an encoder-decoder, retrieve encoder attention weights
  2731. # and hidden states
  2732. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2733. encoder_hidden_states = (
  2734. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2735. )
  2736. scores = tuple(scores) if scores is not None else None
  2737. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  2738. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  2739. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  2740. return TFContrastiveSearchEncoderDecoderOutput(
  2741. sequences=generated,
  2742. scores=scores,
  2743. encoder_attentions=encoder_attentions,
  2744. encoder_hidden_states=encoder_hidden_states,
  2745. decoder_attentions=decoder_attentions,
  2746. cross_attentions=cross_attentions,
  2747. decoder_hidden_states=decoder_hidden_states,
  2748. )
  2749. else:
  2750. return TFContrastiveSearchDecoderOnlyOutput(
  2751. sequences=generated,
  2752. scores=scores,
  2753. attentions=decoder_attentions,
  2754. hidden_states=decoder_hidden_states,
  2755. )
  2756. else:
  2757. return generated
  2758. def scatter_values_on_batch_indices(values, batch_indices):
  2759. shape = shape_list(batch_indices)
  2760. # broadcast batch dim to shape
  2761. broad_casted_batch_dims = tf.reshape(tf.broadcast_to(tf.expand_dims(tf.range(shape[0]), axis=-1), shape), [1, -1])
  2762. # transform batch_indices to pair_indices
  2763. pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0))
  2764. # scatter values to pair indices
  2765. return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), shape)
  2766. def sample_without_replacement(logits, num_samples):
  2767. """
  2768. categorical sampling without replacement is currently not implemented the gumbel-max trick will do for now see
  2769. https://github.com/tensorflow/tensorflow/issues/9260 for more info
  2770. """
  2771. z = -tf.math.log(-tf.math.log(tf.random.uniform(shape_list(logits), 0, 1)))
  2772. _, indices = tf.nn.top_k(logits + z, num_samples)
  2773. return indices
  2774. def _ranking_fast(
  2775. context_hidden: tf.Tensor,
  2776. next_hidden: tf.Tensor,
  2777. next_top_k_probs: tf.Tensor,
  2778. alpha: float,
  2779. beam_width: int,
  2780. ) -> tf.Tensor:
  2781. """
  2782. Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
  2783. in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
  2784. row in the batch.
  2785. """
  2786. norm_context_hidden = context_hidden / tf.norm(context_hidden, axis=2, keepdims=True)
  2787. norm_next_hidden = next_hidden / tf.norm(next_hidden, axis=2, keepdims=True)
  2788. cosine_matrix = tf.squeeze(tf.linalg.matmul(norm_context_hidden, norm_next_hidden, transpose_b=True), axis=-1)
  2789. degeneration_penalty = tf.reduce_max(cosine_matrix, axis=-1)
  2790. next_top_k_probs = tf.reshape(next_top_k_probs, shape=[-1])
  2791. contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
  2792. contrastive_score = tf.reshape(contrastive_score, shape=[-1, beam_width])
  2793. selected_idx = tf.argmax(contrastive_score, axis=1)
  2794. return selected_idx