tf_utils.py 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131
  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, Dict, Optional, Tuple, 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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 quicky 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. logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.")
  680. generation_config.pad_token_id = eos_token_id
  681. use_xla = not tf.executing_eagerly()
  682. if use_xla and not self.supports_xla_generation:
  683. raise ValueError(
  684. "The selected model does not support Graph mode nor XLA generation (e.g. from tf.function())"
  685. )
  686. # 4. Define model inputs
  687. inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
  688. inputs, generation_config.bos_token_id, model_kwargs
  689. )
  690. # inputs_ids now has to be defined and cannot be None anymore
  691. batch_size = shape_list(inputs_tensor)[0]
  692. # 5. Prepare other model kwargs
  693. model_kwargs["output_attentions"] = generation_config.output_attentions
  694. model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
  695. model_kwargs["use_cache"] = generation_config.use_cache
  696. accepts_attention_mask = "attention_mask" in set(inspect.signature(self.call).parameters.keys())
  697. requires_attention_mask = "encoder_outputs" not in model_kwargs
  698. if model_kwargs.get("attention_mask", None) is None and requires_attention_mask and accepts_attention_mask:
  699. model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
  700. inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
  701. )
  702. # decoder-only models should use left-padding for generation
  703. if not self.config.is_encoder_decoder:
  704. if generation_config.pad_token_id is not None and tf.math.reduce_any(
  705. inputs_tensor[:, -1] == generation_config.pad_token_id
  706. ):
  707. logger.warning(
  708. "A decoder-only architecture is being used, but right-padding was detected! For correct "
  709. "generation results, please set `padding_side='left'` when initializing the tokenizer."
  710. )
  711. if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
  712. # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
  713. model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
  714. inputs_tensor, model_kwargs, model_input_name
  715. )
  716. # 6. Prepare model inputs which will be used for auto-regressive generation
  717. if self.config.is_encoder_decoder:
  718. input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
  719. batch_size=batch_size,
  720. model_input_name=model_input_name,
  721. model_kwargs=model_kwargs,
  722. decoder_start_token_id=generation_config.decoder_start_token_id,
  723. bos_token_id=generation_config.bos_token_id,
  724. )
  725. else:
  726. input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
  727. # 7. Prepare `max_length` depending on other stopping criteria.
  728. input_ids_seq_length = shape_list(input_ids)[-1]
  729. has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
  730. if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
  731. # 20 is the default max_length of the generation config
  732. warnings.warn(
  733. f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
  734. "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
  735. UserWarning,
  736. )
  737. elif generation_config.max_new_tokens is not None:
  738. if not has_default_max_length and generation_config.max_length is not None:
  739. logger.warning(
  740. f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
  741. f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
  742. "Please refer to the documentation for more information. "
  743. "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
  744. )
  745. generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
  746. # If the input length is a tensor (i.e. dynamic length), skip length checks
  747. if not isinstance(input_ids_seq_length, tf.Tensor):
  748. if (
  749. generation_config.min_length is not None
  750. and generation_config.min_length > generation_config.max_length
  751. ):
  752. raise ValueError(
  753. f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger"
  754. f" than the maximum length ({generation_config.max_length})"
  755. )
  756. if input_ids_seq_length >= generation_config.max_length:
  757. input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  758. logger.warning(
  759. f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
  760. f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
  761. " increasing`max_new_tokens`."
  762. )
  763. # 8. determine generation mode
  764. is_contrastive_search_gen_mode = (
  765. generation_config.top_k is not None
  766. and generation_config.top_k > 1
  767. and generation_config.do_sample is False
  768. and generation_config.penalty_alpha is not None
  769. and generation_config.penalty_alpha > 0
  770. )
  771. is_greedy_gen_mode = (
  772. not is_contrastive_search_gen_mode
  773. and (generation_config.num_beams == 1)
  774. and generation_config.do_sample is False
  775. )
  776. is_beam_gen_mode = (
  777. not is_contrastive_search_gen_mode
  778. and (generation_config.num_beams > 1)
  779. and generation_config.do_sample is False
  780. )
  781. is_sample_gen_mode = (generation_config.num_beams == 1) and generation_config.do_sample is True
  782. is_beam_sample_gen_mode = (generation_config.num_beams > 1) and generation_config.do_sample is True
  783. # 9. prepare distribution pre_processing samplers
  784. logits_processor = self._get_logits_processor(
  785. generation_config=generation_config,
  786. input_ids_seq_length=input_ids_seq_length,
  787. logits_processor=logits_processor,
  788. )
  789. # 10. go into different generation modes
  790. if is_greedy_gen_mode:
  791. if generation_config.num_return_sequences > 1:
  792. raise ValueError(
  793. f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
  794. " greedy search."
  795. )
  796. # 11. run greedy search
  797. return self.greedy_search(
  798. input_ids,
  799. max_length=generation_config.max_length,
  800. pad_token_id=generation_config.pad_token_id,
  801. eos_token_id=generation_config.eos_token_id,
  802. logits_processor=logits_processor,
  803. output_scores=generation_config.output_scores,
  804. return_dict_in_generate=generation_config.return_dict_in_generate,
  805. **model_kwargs,
  806. )
  807. elif is_contrastive_search_gen_mode:
  808. if generation_config.num_return_sequences > 1:
  809. raise ValueError(
  810. f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
  811. " contrastive search."
  812. )
  813. # 11. run contrastive search
  814. return self.contrastive_search(
  815. input_ids,
  816. top_k=generation_config.top_k,
  817. penalty_alpha=generation_config.penalty_alpha,
  818. logits_processor=logits_processor,
  819. max_length=generation_config.max_length,
  820. pad_token_id=generation_config.pad_token_id,
  821. eos_token_id=generation_config.eos_token_id,
  822. output_scores=generation_config.output_scores,
  823. return_dict_in_generate=generation_config.return_dict_in_generate,
  824. **model_kwargs,
  825. )
  826. elif is_sample_gen_mode:
  827. # 11. prepare logits warper
  828. logits_warper = self._get_logits_warper(generation_config=generation_config)
  829. # 12. expand input_ids with `num_return_sequences` additional sequences per batch
  830. input_ids, model_kwargs = self._expand_inputs_for_generation(
  831. input_ids=input_ids,
  832. expand_size=generation_config.num_return_sequences,
  833. is_encoder_decoder=self.config.is_encoder_decoder,
  834. **model_kwargs,
  835. )
  836. # 13. run sample
  837. return self.sample(
  838. input_ids,
  839. logits_processor=logits_processor,
  840. logits_warper=logits_warper,
  841. max_length=generation_config.max_length,
  842. pad_token_id=generation_config.pad_token_id,
  843. eos_token_id=generation_config.eos_token_id,
  844. seed=seed,
  845. output_scores=generation_config.output_scores,
  846. return_dict_in_generate=generation_config.return_dict_in_generate,
  847. **model_kwargs,
  848. )
  849. elif is_beam_gen_mode:
  850. if generation_config.num_beams < generation_config.num_return_sequences:
  851. raise ValueError(
  852. "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
  853. f" num_return_sequences, got {generation_config.num_beams} and"
  854. f" {generation_config.num_return_sequences} (respectivelly)"
  855. )
  856. # 11. broadcast inputs to the desired number of beams
  857. input_ids, model_kwargs = self._expand_inputs_for_generation(
  858. input_ids=input_ids,
  859. expand_size=generation_config.num_beams,
  860. is_encoder_decoder=self.config.is_encoder_decoder,
  861. expand_in_new_axis=True,
  862. **model_kwargs,
  863. )
  864. # 12. run beam search
  865. return self.beam_search(
  866. input_ids,
  867. max_length=generation_config.max_length,
  868. pad_token_id=generation_config.pad_token_id,
  869. eos_token_id=generation_config.eos_token_id,
  870. length_penalty=generation_config.length_penalty,
  871. early_stopping=generation_config.early_stopping,
  872. logits_processor=logits_processor,
  873. output_scores=generation_config.output_scores,
  874. return_dict_in_generate=generation_config.return_dict_in_generate,
  875. num_return_sequences=generation_config.num_return_sequences,
  876. **model_kwargs,
  877. )
  878. elif is_beam_sample_gen_mode:
  879. if generation_config.num_beams < generation_config.num_return_sequences:
  880. raise ValueError(
  881. "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
  882. f" num_return_sequences, got {generation_config.num_beams} and"
  883. f" {generation_config.num_return_sequences} (respectivelly)"
  884. )
  885. # 11. prepare logits warper
  886. logits_warper = self._get_logits_warper(generation_config=generation_config)
  887. # 12. broadcast inputs to the desired number of beams
  888. input_ids, model_kwargs = self._expand_inputs_for_generation(
  889. input_ids=input_ids,
  890. expand_size=generation_config.num_beams,
  891. is_encoder_decoder=self.config.is_encoder_decoder,
  892. expand_in_new_axis=True,
  893. **model_kwargs,
  894. )
  895. # 13. run beam sample (beam search with sampling)
  896. return self.beam_search(
  897. input_ids,
  898. do_sample=True,
  899. max_length=generation_config.max_length,
  900. pad_token_id=generation_config.pad_token_id,
  901. eos_token_id=generation_config.eos_token_id,
  902. length_penalty=generation_config.length_penalty,
  903. early_stopping=generation_config.early_stopping,
  904. logits_processor=logits_processor,
  905. logits_warper=logits_warper,
  906. output_scores=generation_config.output_scores,
  907. return_dict_in_generate=generation_config.return_dict_in_generate,
  908. num_return_sequences=generation_config.num_return_sequences,
  909. **model_kwargs,
  910. )
  911. def _prepare_attention_mask_for_generation(
  912. self,
  913. inputs: tf.Tensor,
  914. pad_token_id: Optional[int],
  915. eos_token_id: Optional[int],
  916. ) -> tf.Tensor:
  917. is_input_ids = len(inputs.shape) == 2 and inputs.dtype in (tf.int32, tf.int64)
  918. is_pad_token_in_inputs = (pad_token_id is not None) and tf.math.reduce_any(inputs == pad_token_id)
  919. is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or (pad_token_id != eos_token_id)
  920. # Check if input is input_ids and padded -> only then is attention_mask defined
  921. if is_input_ids and is_pad_token_in_inputs and is_pad_token_not_equal_to_eos_token_id:
  922. return tf.cast(tf.math.not_equal(inputs, pad_token_id), dtype=tf.int32)
  923. else:
  924. return tf.ones(inputs.shape[:2], dtype=tf.int32)
  925. def _prepare_encoder_decoder_kwargs_for_generation(
  926. self, inputs_tensor: tf.Tensor, model_kwargs, model_input_name: Optional[str] = None
  927. ) -> Dict[str, Any]:
  928. # 1. get encoder and store encoder outputs
  929. encoder = self.get_encoder()
  930. # 2. prepare encoder args and encoder kwargs from model kwargs
  931. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
  932. encoder_kwargs = {
  933. argument: value
  934. for argument, value in model_kwargs.items()
  935. if not any(argument.startswith(p) for p in irrelevant_prefix)
  936. }
  937. encoder_signature = set(inspect.signature(encoder.call).parameters)
  938. encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
  939. if not encoder_accepts_wildcard:
  940. encoder_kwargs = {
  941. argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
  942. }
  943. # 3. vision models don't use `attention_mask`.
  944. encoder_kwargs["return_dict"] = True
  945. encoder_kwargs[model_input_name] = inputs_tensor
  946. if model_input_name != self.main_input_name: # in Keras, the first input must always be passed
  947. encoder_kwargs[self.main_input_name] = None
  948. encoder_outputs = encoder(**encoder_kwargs)
  949. model_kwargs["encoder_outputs"] = encoder_outputs
  950. return model_kwargs
  951. def _prepare_decoder_input_ids_for_generation(
  952. self,
  953. batch_size: int,
  954. model_input_name: str,
  955. model_kwargs: Dict[str, tf.Tensor],
  956. decoder_start_token_id: int = None,
  957. bos_token_id: int = None,
  958. ) -> Tuple[tf.Tensor, Dict[str, tf.Tensor]]:
  959. """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
  960. # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
  961. # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
  962. if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
  963. decoder_input_ids = model_kwargs.pop("decoder_input_ids")
  964. elif "input_ids" in model_kwargs and model_input_name != "input_ids":
  965. decoder_input_ids = model_kwargs.pop("input_ids")
  966. else:
  967. decoder_input_ids = None
  968. # 2. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
  969. decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
  970. decoder_input_ids_start = tf.ones((batch_size, 1), dtype=tf.int32) * decoder_start_token_id
  971. # no user input -> use decoder_start_token_id as decoder_input_ids
  972. if decoder_input_ids is None:
  973. decoder_input_ids = decoder_input_ids_start
  974. # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
  975. # decoder_attention_mask if provided)
  976. elif tf.reduce_all(decoder_input_ids[:, 0] != decoder_start_token_id):
  977. decoder_input_ids = tf.concat([decoder_input_ids_start, decoder_input_ids], axis=-1)
  978. if "decoder_attention_mask" in model_kwargs:
  979. decoder_attention_mask = model_kwargs["decoder_attention_mask"]
  980. decoder_attention_mask = tf.concat(
  981. (tf.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
  982. axis=-1,
  983. )
  984. model_kwargs["decoder_attention_mask"] = decoder_attention_mask
  985. return decoder_input_ids, model_kwargs
  986. def _get_decoder_start_token_id(self, decoder_start_token_id: int = None, bos_token_id: int = None) -> int:
  987. # retrieve decoder_start_token_id for encoder-decoder models
  988. # fall back to bos_token_id if necessary
  989. decoder_start_token_id = (
  990. decoder_start_token_id
  991. if decoder_start_token_id is not None
  992. else self.generation_config.decoder_start_token_id
  993. )
  994. bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
  995. if decoder_start_token_id is not None:
  996. return decoder_start_token_id
  997. elif bos_token_id is not None:
  998. return bos_token_id
  999. raise ValueError(
  1000. "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
  1001. )
  1002. @staticmethod
  1003. def _expand_inputs_for_generation(
  1004. expand_size: int = 1,
  1005. is_encoder_decoder: bool = False,
  1006. input_ids: Optional[tf.Tensor] = None,
  1007. expand_in_new_axis: bool = False,
  1008. **model_kwargs,
  1009. ) -> Tuple[tf.Tensor, Dict[str, Any]]:
  1010. """
  1011. Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...] or [batch_size, expand_size, ...],
  1012. depending on `expand_in_new_axis`. Beam-based approaches expect this function to be used with
  1013. `expand_in_new_axis=True`
  1014. """
  1015. def _expand_tensor(tensor: tf.Tensor):
  1016. if expand_in_new_axis:
  1017. shape = shape_list(tensor)
  1018. return tf.broadcast_to(tensor[:, None], (shape[0], expand_size) + tuple(shape[1:]))
  1019. else:
  1020. return tf.repeat(tensor, expand_size, axis=0)
  1021. def _expand_dict_for_generation(dict_to_expand):
  1022. for key in dict_to_expand:
  1023. if dict_to_expand[key] is not None and isinstance(dict_to_expand[key], tf.Tensor):
  1024. dict_to_expand[key] = _expand_tensor(dict_to_expand[key])
  1025. return dict_to_expand
  1026. if input_ids is not None:
  1027. input_ids = _expand_tensor(input_ids)
  1028. model_kwargs = _expand_dict_for_generation(model_kwargs)
  1029. if is_encoder_decoder:
  1030. if model_kwargs.get("encoder_outputs") is None:
  1031. raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
  1032. model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
  1033. return input_ids, model_kwargs
  1034. def _prepare_model_inputs(
  1035. self,
  1036. inputs: Optional[tf.Tensor] = None,
  1037. bos_token_id: Optional[int] = None,
  1038. model_kwargs: Optional[Dict[str, tf.Tensor]] = None,
  1039. ) -> Tuple[tf.Tensor, Optional[str], Dict[str, tf.Tensor]]:
  1040. """
  1041. This function extracts the model-specific `inputs` for generation.
  1042. """
  1043. # 1. retrieve all kwargs that are non-None or non-model input related.
  1044. # some encoder-decoder models have different names for model and encoder
  1045. if (
  1046. self.config.is_encoder_decoder
  1047. and hasattr(self, "encoder")
  1048. and hasattr(self.encoder, "main_input_name")
  1049. and self.encoder.main_input_name != self.main_input_name
  1050. ):
  1051. input_name = self.encoder.main_input_name
  1052. else:
  1053. input_name = self.main_input_name
  1054. model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
  1055. # 2. check whether model_input_name is passed as kwarg
  1056. # if yes and `inputs` is None use kwarg inputs
  1057. inputs_kwarg = model_kwargs.pop(input_name, None)
  1058. if inputs_kwarg is not None and inputs is not None:
  1059. raise ValueError(
  1060. f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
  1061. f"Make sure to either pass {inputs} or {input_name}=..."
  1062. )
  1063. elif inputs_kwarg is not None:
  1064. inputs = inputs_kwarg
  1065. # 3. In the presence of `inputs_embeds` for text models:
  1066. # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
  1067. # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
  1068. # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
  1069. # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
  1070. # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
  1071. if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
  1072. if not self.config.is_encoder_decoder:
  1073. has_inputs_embeds_forwarding = "inputs_embeds" in set(
  1074. inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
  1075. )
  1076. if not has_inputs_embeds_forwarding:
  1077. raise ValueError(
  1078. f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
  1079. "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
  1080. "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
  1081. )
  1082. # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
  1083. # the attention mask) can rely on the actual model input.
  1084. model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
  1085. inputs, bos_token_id, model_kwargs=model_kwargs
  1086. )
  1087. else:
  1088. if inputs is not None:
  1089. raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
  1090. inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
  1091. # 4. if `inputs` is still None, try to create `input_ids` from BOS token
  1092. inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
  1093. return inputs, input_name, model_kwargs
  1094. def _maybe_initialize_input_ids_for_generation(
  1095. self,
  1096. inputs: Optional[tf.Tensor] = None,
  1097. bos_token_id: Optional[int] = None,
  1098. model_kwargs: Optional[Dict[str, tf.Tensor]] = None,
  1099. ) -> tf.Tensor:
  1100. """Initializes input ids for generation, if necessary."""
  1101. if inputs is not None:
  1102. return inputs
  1103. encoder_outputs = model_kwargs.get("encoder_outputs")
  1104. if self.config.is_encoder_decoder and encoder_outputs is not None:
  1105. # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
  1106. shape = encoder_outputs.last_hidden_state.shape[:-1]
  1107. return tf.ones(shape, dtype=tf.int32) * -100
  1108. if bos_token_id is None:
  1109. raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
  1110. # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
  1111. # soft-prompting or in multimodal implementations built on top of decoder-only language models.
  1112. batch_size = 1
  1113. for value in model_kwargs.values():
  1114. if isinstance(value, tf.Tensor):
  1115. batch_size = value.shape[0]
  1116. break
  1117. return tf.ones((batch_size, 1), dtype=tf.int32) * bos_token_id
  1118. @staticmethod
  1119. def _extract_past_from_model_output(outputs: ModelOutput):
  1120. past_key_values = None
  1121. if "past_key_values" in outputs:
  1122. past_key_values = outputs.past_key_values
  1123. elif "mems" in outputs:
  1124. past_key_values = outputs.mems
  1125. elif "past_buckets_states" in outputs:
  1126. past_key_values = outputs.past_buckets_states
  1127. return past_key_values
  1128. def _update_model_kwargs_for_generation(
  1129. self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False
  1130. ) -> Dict[str, Any]:
  1131. # update past_key_values
  1132. model_kwargs["past_key_values"] = self._extract_past_from_model_output(outputs)
  1133. # update attention mask
  1134. if not is_encoder_decoder:
  1135. if "attention_mask" in model_kwargs:
  1136. attention_mask = model_kwargs["attention_mask"]
  1137. model_kwargs["attention_mask"] = tf.concat(
  1138. [attention_mask, tf.ones((shape_list(attention_mask)[0], 1), dtype=tf.int32)], axis=-1
  1139. )
  1140. return model_kwargs
  1141. def _update_model_kwargs_for_xla_generation(
  1142. self,
  1143. model_outputs: ModelOutput,
  1144. model_kwargs: Dict[str, Any],
  1145. cur_len: int,
  1146. max_length: int,
  1147. batch_size: int,
  1148. is_encoder_decoder: bool = False,
  1149. batch_axis: int = 0,
  1150. ):
  1151. def _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder):
  1152. """initializes the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
  1153. if is_encoder_decoder:
  1154. # One 1 for decoder_start_token_id, 0s for the currently-unfilled locations in the past_key_values tensor,
  1155. # 1s for the actual input_ids
  1156. decoder_attention_mask = tf.concat(
  1157. [
  1158. tf.ones((batch_size, 1), dtype=tf.int32),
  1159. tf.zeros((batch_size, num_padding_values), dtype=tf.int32),
  1160. tf.ones((batch_size, 1), dtype=tf.int32),
  1161. ],
  1162. axis=1,
  1163. )
  1164. mask = {"decoder_attention_mask": decoder_attention_mask}
  1165. else:
  1166. attention_mask = model_kwargs.pop("attention_mask")
  1167. # 0s for the currently-unfilled locations in the past_key_values tensor, 1s for the actual input_ids
  1168. attention_mask = tf.concat(
  1169. [
  1170. attention_mask,
  1171. tf.zeros((batch_size, num_padding_values), dtype=attention_mask.dtype),
  1172. tf.ones((batch_size, 1), dtype=attention_mask.dtype),
  1173. ],
  1174. axis=1,
  1175. )
  1176. mask = {"attention_mask": attention_mask}
  1177. return mask
  1178. def _update_attention(model_kwargs, new_past_index, is_encoder_decoder):
  1179. """updates the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
  1180. update_start = tf.constant([0, 1], dtype=tf.int32) * new_past_index
  1181. if is_encoder_decoder:
  1182. decoder_attention_mask = model_kwargs.pop("decoder_attention_mask")
  1183. decoder_attention_mask_update_slice = tf.ones((batch_size, 1), dtype=decoder_attention_mask.dtype)
  1184. decoder_attention_mask = dynamic_update_slice(
  1185. decoder_attention_mask, decoder_attention_mask_update_slice, update_start
  1186. )
  1187. mask = {"decoder_attention_mask": decoder_attention_mask}
  1188. else:
  1189. attention_mask = model_kwargs.pop("attention_mask")
  1190. attention_mask_update_slice = tf.ones((batch_size, 1), dtype=attention_mask.dtype)
  1191. attention_mask = dynamic_update_slice(attention_mask, attention_mask_update_slice, update_start)
  1192. mask = {"attention_mask": attention_mask}
  1193. return mask
  1194. def _initialize_past(past_key_values, num_padding_values, batch_axis):
  1195. """initialize past_key_values with zeros -- the structure depends on `batch_axis`"""
  1196. if batch_axis == 0:
  1197. padding_values = tf.constant([[0, 0], [0, 0], [0, num_padding_values], [0, 0]], dtype=tf.int32)
  1198. new_past = ()
  1199. for past_layer in past_key_values:
  1200. new_past_layer = list(past_layer)
  1201. for i in range(len(new_past_layer[:2])):
  1202. new_past_layer[i] = tf.pad(past_layer[i], padding_values)
  1203. new_past += (tuple(new_past_layer),)
  1204. else:
  1205. padding_values = tf.scatter_nd(indices=[[3, 1]], updates=[num_padding_values], shape=(5, 2))
  1206. new_past = list(past_key_values)
  1207. for i in range(len(past_key_values)):
  1208. new_past[i] = tf.pad(past_key_values[i], padding_values)
  1209. return new_past
  1210. def _update_past(past_key_values, new_past_index, batch_axis):
  1211. if batch_axis == 0:
  1212. slice_start_base = tf.constant([0, 0, 1, 0])
  1213. new_past = ()
  1214. for past_layer in past_key_values:
  1215. new_past_layer = list(past_layer)
  1216. for i in range(len(new_past_layer[:2])):
  1217. update_slice = past_layer[i][:, :, -1:]
  1218. # Write the last slice to the first open location in the padded past_key_values array
  1219. # and then truncate the last slice off the array
  1220. new_past_layer[i] = dynamic_update_slice(
  1221. past_layer[i][:, :, :-1], update_slice, slice_start_base * new_past_index
  1222. )
  1223. new_past += (tuple(new_past_layer),)
  1224. else:
  1225. slice_start_base = tf.constant([0, 0, 0, 1, 0])
  1226. new_past = [None for _ in range(len(past_key_values))]
  1227. for i in range(len(past_key_values)):
  1228. update_slice = past_key_values[i][:, :, :, -1:]
  1229. # Write the last slice to the first open location in the padded past_key_values array
  1230. # and then truncate the last slice off the array
  1231. new_past[i] = dynamic_update_slice(
  1232. past_key_values[i][:, :, :, :-1], update_slice, slice_start_base * new_past_index
  1233. )
  1234. return new_past
  1235. past_key_values = self._extract_past_from_model_output(model_outputs)
  1236. if past_key_values is None:
  1237. raise ValueError(
  1238. "No known `past_key_values variable` found in model outputs (model outputs keys:"
  1239. f" {list(model_outputs.keys())})"
  1240. )
  1241. is_past_initialized = model_kwargs.pop("past_key_values", None) is not None
  1242. if not is_past_initialized:
  1243. # The padded version of `past_key_values` has a length of `max_length - 1`, as `past_key_values` holds information relative to
  1244. # previous autoregressive generation steps (step 0 has no past_key_values, step 1 has 1 past_key_values value, ..., the last step
  1245. # has `max_length - 1` past_key_values values).
  1246. num_padding_values = max_length - cur_len - 1
  1247. mask = _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder)
  1248. new_past = _initialize_past(past_key_values, num_padding_values, batch_axis)
  1249. else:
  1250. # The new index of past_key_values to be filled corresponds to the current length of the sequence, with two
  1251. # subtractions: -1 because past_key_values holds information regarding previous generation steps (read comment above)
  1252. # and -1 again because in an array the index is the length of the array minus 1.
  1253. new_past_index = cur_len - 2
  1254. mask = _update_attention(model_kwargs, new_past_index, is_encoder_decoder)
  1255. new_past = _update_past(past_key_values, new_past_index, batch_axis)
  1256. # sets the updated variables (mask and past_key_values)
  1257. model_kwargs.update(mask)
  1258. model_kwargs["past_key_values"] = tuple(new_past)
  1259. return model_kwargs
  1260. def _get_logits_warper(
  1261. self,
  1262. generation_config: GenerationConfig,
  1263. ) -> TFLogitsProcessorList:
  1264. """
  1265. This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsWarper`]
  1266. instances used for multinomial sampling.
  1267. """
  1268. # instantiate warpers list
  1269. warpers = TFLogitsProcessorList()
  1270. # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
  1271. # better score (i.e. keep len(generation_config.eos_token_id) + 1)
  1272. if generation_config.num_beams > 1:
  1273. if isinstance(generation_config.eos_token_id, list):
  1274. min_tokens_to_keep = len(generation_config.eos_token_id) + 1
  1275. else:
  1276. min_tokens_to_keep = 2
  1277. else:
  1278. min_tokens_to_keep = 1
  1279. if generation_config.temperature is not None and generation_config.temperature != 1.0:
  1280. warpers.append(TFTemperatureLogitsWarper(generation_config.temperature))
  1281. if generation_config.top_k is not None and generation_config.top_k != 0:
  1282. warpers.append(TFTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep))
  1283. if generation_config.top_p is not None and generation_config.top_p < 1.0:
  1284. warpers.append(TFTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep))
  1285. return warpers
  1286. def _get_logits_processor(
  1287. self,
  1288. generation_config: GenerationConfig,
  1289. input_ids_seq_length: int,
  1290. logits_processor: Optional[TFLogitsProcessorList],
  1291. ) -> TFLogitsProcessorList:
  1292. """
  1293. This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsProcessor`]
  1294. instances used to modify the scores of the language model head.
  1295. """
  1296. processors = TFLogitsProcessorList()
  1297. # instantiate processors list
  1298. if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
  1299. processors.append(TFRepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
  1300. if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
  1301. processors.append(TFNoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
  1302. if generation_config.bad_words_ids is not None:
  1303. processors.append(
  1304. TFNoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)
  1305. )
  1306. if (
  1307. generation_config.min_length is not None
  1308. and generation_config.eos_token_id is not None
  1309. and generation_config.min_length > 0
  1310. ):
  1311. processors.append(TFMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id))
  1312. if generation_config.forced_bos_token_id is not None:
  1313. processors.append(TFForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
  1314. if generation_config.forced_eos_token_id is not None:
  1315. processors.append(
  1316. TFForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
  1317. )
  1318. if generation_config.suppress_tokens is not None:
  1319. processors.append(TFSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
  1320. if generation_config.begin_suppress_tokens is not None:
  1321. begin_index = input_ids_seq_length
  1322. begin_index = (
  1323. begin_index
  1324. if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
  1325. else begin_index + 1
  1326. )
  1327. if generation_config.forced_decoder_ids is not None:
  1328. begin_index += generation_config.forced_decoder_ids[-1][
  1329. 0
  1330. ] # generation starts after the last token that is forced
  1331. processors.append(
  1332. TFSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
  1333. )
  1334. if generation_config.forced_decoder_ids is not None:
  1335. processors.append(TFForceTokensLogitsProcessor(generation_config.forced_decoder_ids))
  1336. processors = self._merge_criteria_processor_list(processors, logits_processor)
  1337. return processors
  1338. def _merge_criteria_processor_list(
  1339. self,
  1340. default_list: TFLogitsProcessorList,
  1341. custom_list: TFLogitsProcessorList,
  1342. ) -> TFLogitsProcessorList:
  1343. if len(custom_list) == 0:
  1344. return default_list
  1345. for default in default_list:
  1346. for custom in custom_list:
  1347. if type(custom) is type(default):
  1348. object_type = "logits processor"
  1349. raise ValueError(
  1350. f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
  1351. f" `generate`, but it has already been created with the values {default}. {default} has been"
  1352. " created by passing the corresponding arguments to generate or by the model's config default"
  1353. f" values. If you just want to change the default values of {object_type} consider passing"
  1354. f" them as arguments to `generate` instead of using a custom {object_type}."
  1355. )
  1356. default_list.extend(custom_list)
  1357. return default_list
  1358. def greedy_search(
  1359. self,
  1360. input_ids: tf.Tensor,
  1361. max_length: Optional[int] = None,
  1362. pad_token_id: Optional[int] = None,
  1363. eos_token_id: Optional[int] = None,
  1364. logits_processor: Optional[TFLogitsProcessorList] = None,
  1365. output_attentions: Optional[bool] = None,
  1366. output_hidden_states: Optional[bool] = None,
  1367. output_scores: Optional[bool] = None,
  1368. return_dict_in_generate: Optional[bool] = None,
  1369. **model_kwargs,
  1370. ) -> Union[TFGreedySearchOutput, tf.Tensor]:
  1371. r"""
  1372. Generates sequences for models with a language modeling head using greedy decoding.
  1373. Parameters:
  1374. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1375. The sequence used as a prompt for the generation.
  1376. logits_processor (`TFLogitsProcessorList`, *optional*):
  1377. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1378. used to modify the prediction scores of the language modeling head applied at each generation step.
  1379. max_length (`int`, *optional*, defaults to 20):
  1380. The maximum length of the sequence to be generated.
  1381. pad_token_id (`int`, *optional*):
  1382. The id of the *padding* token.
  1383. eos_token_id (`Union[int, List[int]]`, *optional*):
  1384. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1385. output_attentions (`bool`, *optional*, defaults to `False`):
  1386. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1387. returned tensors for more details.
  1388. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1389. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1390. for more details.
  1391. output_scores (`bool`, *optional*, defaults to `False`):
  1392. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  1393. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1394. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1395. model_kwargs:
  1396. Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
  1397. model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  1398. Return:
  1399. [`~generation.TFGreedySearchDecoderOnlyOutput`], [`~generation.TFGreedySearchEncoderDecoderOutput`] or
  1400. `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
  1401. [`~generation.TFGreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1402. `return_dict_in_generate=True` or a [`~generation.TFGreedySearchEncoderDecoderOutput`] if
  1403. `model.config.is_encoder_decoder=True`.
  1404. Examples:
  1405. ```python
  1406. >>> from transformers import (
  1407. ... AutoTokenizer,
  1408. ... TFAutoModelForCausalLM,
  1409. ... TFLogitsProcessorList,
  1410. ... TFMinLengthLogitsProcessor,
  1411. ... )
  1412. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1413. >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1414. >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
  1415. >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
  1416. >>> input_prompt = "Today is a beautiful day, and"
  1417. >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
  1418. >>> # instantiate logits processors
  1419. >>> logits_processor = TFLogitsProcessorList(
  1420. ... [
  1421. ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
  1422. ... ]
  1423. ... )
  1424. >>> outputs = model.greedy_search(input_ids, logits_processor=logits_processor)
  1425. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1426. ["Today is a beautiful day, and I'm so happy to be here. I'm so happy to"]
  1427. ```"""
  1428. # 1. init greedy_search values
  1429. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1430. max_length = max_length if max_length is not None else self.generation_config.max_length
  1431. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1432. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1433. if isinstance(eos_token_id, int):
  1434. eos_token_id = [eos_token_id]
  1435. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1436. output_attentions = (
  1437. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1438. )
  1439. output_hidden_states = (
  1440. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1441. )
  1442. return_dict_in_generate = (
  1443. return_dict_in_generate
  1444. if return_dict_in_generate is not None
  1445. else self.generation_config.return_dict_in_generate
  1446. )
  1447. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  1448. use_xla = not tf.executing_eagerly()
  1449. # TODO (Joao): fix cache format or find programatic way to detect cache index
  1450. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  1451. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  1452. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  1453. # some models, like XLNet, need more than the last token in the presence of past_key_values
  1454. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  1455. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  1456. scores = [] if (return_dict_in_generate and output_scores) else None
  1457. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1458. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1459. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  1460. # 3. init tensors to use for "xla-compileable" generate function
  1461. batch_size, cur_len = shape_list(input_ids)
  1462. # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
  1463. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  1464. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  1465. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  1466. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  1467. # define condition fn
  1468. def greedy_search_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
  1469. """state termination condition fn."""
  1470. return ~tf.reduce_all(finished_sequences)
  1471. # define condition fn
  1472. def greedy_search_body_fn(generated, finished_sequences, cur_len, model_kwargs):
  1473. """state update fn."""
  1474. if model_kwargs.get("past_key_values") is None or needs_full_input:
  1475. input_ids = generated[:, :cur_len]
  1476. else:
  1477. input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
  1478. model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
  1479. # forward pass to get next token logits
  1480. model_outputs = self(
  1481. **model_inputs,
  1482. return_dict=True,
  1483. output_attentions=output_attentions,
  1484. output_hidden_states=output_hidden_states,
  1485. )
  1486. next_token_logits = model_outputs.logits[:, -1]
  1487. # pre-process distribution
  1488. next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
  1489. # Store scores, attentions and hidden_states when required
  1490. if not use_xla and return_dict_in_generate:
  1491. if output_scores:
  1492. scores.append(next_tokens_scores)
  1493. if output_attentions and self.config.is_encoder_decoder:
  1494. decoder_attentions.append(model_outputs.decoder_attentions)
  1495. elif output_attentions and not self.config.is_encoder_decoder:
  1496. decoder_attentions.append(model_outputs.attentions)
  1497. if self.config.is_encoder_decoder:
  1498. cross_attentions.append(model_outputs.cross_attentions)
  1499. if output_hidden_states and self.config.is_encoder_decoder:
  1500. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  1501. elif output_hidden_states and self.config.is_encoder_decoder:
  1502. decoder_hidden_states.append(model_outputs.hidden_states)
  1503. # argmax
  1504. next_tokens = tf.argmax(next_tokens_scores, axis=-1, output_type=tf.int32)
  1505. if eos_token_id is not None:
  1506. if pad_token_id is None:
  1507. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  1508. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  1509. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  1510. next_token_is_eos = tf.math.reduce_any(
  1511. tf.equal(
  1512. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  1513. ),
  1514. axis=0,
  1515. )
  1516. finished_sequences = finished_sequences | next_token_is_eos
  1517. # update `generated` and `cur_len`
  1518. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  1519. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  1520. cur_len += 1
  1521. # update model_kwargs
  1522. if use_xla:
  1523. model_kwargs = self._update_model_kwargs_for_xla_generation(
  1524. model_outputs=model_outputs,
  1525. model_kwargs=model_kwargs,
  1526. cur_len=cur_len,
  1527. max_length=max_length,
  1528. batch_size=batch_size,
  1529. is_encoder_decoder=self.config.is_encoder_decoder,
  1530. batch_axis=cache_batch_axis,
  1531. )
  1532. else:
  1533. model_kwargs = self._update_model_kwargs_for_generation(
  1534. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  1535. )
  1536. # if we don't cache past_key_values key values we need the whole input
  1537. if model_kwargs.get("past_key_values", None) is None:
  1538. # let's throw out `past_key_values` since we don't want `None` tensors
  1539. model_kwargs.pop("past_key_values", None)
  1540. return generated, finished_sequences, cur_len, model_kwargs
  1541. # 5. run generation
  1542. # 1st generation step has to be run before to initialize `past_key_values`
  1543. generated, finished_sequences, cur_len, model_kwargs = greedy_search_body_fn(
  1544. generated, finished_sequences, cur_len, model_kwargs
  1545. )
  1546. # 2-to-n generation steps can then be run in autoregressive fashion
  1547. # only in case 1st generation step does NOT yield EOS token though
  1548. maximum_iterations = max_length - cur_len
  1549. generated, _, cur_len, _ = tf.while_loop(
  1550. greedy_search_cond_fn,
  1551. greedy_search_body_fn,
  1552. (generated, finished_sequences, cur_len, model_kwargs),
  1553. maximum_iterations=maximum_iterations,
  1554. )
  1555. # 6. prepare outputs
  1556. if not use_xla:
  1557. # cut for backward compatibility
  1558. generated = generated[:, :cur_len]
  1559. if return_dict_in_generate:
  1560. if self.config.is_encoder_decoder:
  1561. # if model is an encoder-decoder, retrieve encoder attention weights
  1562. # and hidden states
  1563. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  1564. encoder_hidden_states = (
  1565. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  1566. )
  1567. scores = tuple(scores) if scores is not None else None
  1568. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  1569. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  1570. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  1571. return TFGreedySearchEncoderDecoderOutput(
  1572. sequences=generated,
  1573. scores=scores,
  1574. encoder_attentions=encoder_attentions,
  1575. encoder_hidden_states=encoder_hidden_states,
  1576. decoder_attentions=decoder_attentions,
  1577. cross_attentions=cross_attentions,
  1578. decoder_hidden_states=decoder_hidden_states,
  1579. )
  1580. else:
  1581. return TFGreedySearchDecoderOnlyOutput(
  1582. sequences=generated,
  1583. scores=scores,
  1584. attentions=decoder_attentions,
  1585. hidden_states=decoder_hidden_states,
  1586. )
  1587. else:
  1588. return generated
  1589. def sample(
  1590. self,
  1591. input_ids: tf.Tensor,
  1592. logits_processor: Optional[TFLogitsProcessorList] = None,
  1593. logits_warper: Optional[TFLogitsProcessorList] = None,
  1594. max_length: Optional[int] = None,
  1595. pad_token_id: Optional[int] = None,
  1596. eos_token_id: Optional[int] = None,
  1597. seed: Optional[Tuple[int, int]] = None,
  1598. output_attentions: Optional[bool] = None,
  1599. output_hidden_states: Optional[bool] = None,
  1600. output_scores: Optional[bool] = None,
  1601. return_dict_in_generate: Optional[bool] = None,
  1602. **model_kwargs,
  1603. ) -> Union[TFSampleOutput, tf.Tensor]:
  1604. r"""
  1605. Generates sequences for models with a language modeling head using multinomial sampling.
  1606. Parameters:
  1607. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1608. The sequence used as a prompt for the generation.
  1609. logits_processor (`TFLogitsProcessorList`, *optional*):
  1610. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1611. used to modify the prediction scores of the language modeling head applied at each generation step.
  1612. logits_warper (`TFLogitsProcessorList`, *optional*):
  1613. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  1614. used to warp the prediction score distribution of the language modeling head applied before multinomial
  1615. sampling at each generation step.
  1616. max_length (`int`, *optional*, defaults to 20):
  1617. The maximum length of the sequence to be generated.
  1618. pad_token_id (`int`, *optional*):
  1619. The id of the *padding* token.
  1620. eos_token_id (`Union[int, List[int]]`, *optional*):
  1621. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1622. seed (`List[int]`, *optional*):
  1623. Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
  1624. `seed` argument from stateless functions in `tf.random`.
  1625. output_attentions (`bool`, *optional*, defaults to `False`):
  1626. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1627. returned tensors for more details.
  1628. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1629. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1630. for more details.
  1631. output_scores (`bool`, *optional*, defaults to `False`):
  1632. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  1633. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1634. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1635. model_kwargs:
  1636. Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
  1637. encoder-decoder model the kwargs should include `encoder_outputs`.
  1638. Return:
  1639. [`~generation.TFSampleDecoderOnlyOutput`], [`~generation.TFSampleEncoderDecoderOutput`] or `tf.Tensor`: A
  1640. `tf.Tensor` containing the generated tokens (default behaviour) or a
  1641. [`~generation.TFSampleDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1642. `return_dict_in_generate=True` or a [`~generation.TFSampleEncoderDecoderOutput`] if
  1643. `model.config.is_encoder_decoder=True`.
  1644. Examples:
  1645. ```python
  1646. >>> import tensorflow as tf
  1647. >>> from transformers import (
  1648. ... AutoTokenizer,
  1649. ... TFAutoModelForCausalLM,
  1650. ... TFLogitsProcessorList,
  1651. ... TFMinLengthLogitsProcessor,
  1652. ... TFTopKLogitsWarper,
  1653. ... TFTemperatureLogitsWarper,
  1654. ... )
  1655. >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
  1656. >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
  1657. >>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
  1658. >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
  1659. >>> input_prompt = "Today is a beautiful day, and"
  1660. >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
  1661. >>> # instantiate logits processors
  1662. >>> logits_processor = TFLogitsProcessorList(
  1663. ... [
  1664. ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
  1665. ... ]
  1666. ... )
  1667. >>> # instantiate logits processors
  1668. >>> logits_warper = TFLogitsProcessorList(
  1669. ... [
  1670. ... TFTopKLogitsWarper(50),
  1671. ... TFTemperatureLogitsWarper(0.7),
  1672. ... ]
  1673. ... )
  1674. >>> tf.random.set_seed(0)
  1675. >>> outputs = model.sample(input_ids, logits_processor=logits_processor, logits_warper=logits_warper)
  1676. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1677. ['Today is a beautiful day, and I love my country. But when I look at Donald Trump,']
  1678. ```"""
  1679. # 1. init greedy_search values
  1680. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1681. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  1682. max_length = max_length if max_length is not None else self.generation_config.max_length
  1683. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1684. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1685. if isinstance(eos_token_id, int):
  1686. eos_token_id = [eos_token_id]
  1687. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1688. output_attentions = (
  1689. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1690. )
  1691. output_hidden_states = (
  1692. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1693. )
  1694. return_dict_in_generate = (
  1695. return_dict_in_generate
  1696. if return_dict_in_generate is not None
  1697. else self.generation_config.return_dict_in_generate
  1698. )
  1699. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  1700. use_xla = not tf.executing_eagerly()
  1701. # TODO (Joao): fix cache format or find programatic way to detect cache index
  1702. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  1703. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  1704. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  1705. # some models, like XLNet, need more than the last token in the presence of past_key_values
  1706. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  1707. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  1708. scores = [] if (return_dict_in_generate and output_scores) else None
  1709. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1710. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  1711. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  1712. # 3. init tensors to use for "xla-compileable" generate function
  1713. batch_size, cur_len = shape_list(input_ids)
  1714. # initialize `generated` (pre-populated with `pad_token_id`), `finished_sequences`
  1715. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  1716. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  1717. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  1718. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  1719. def sample_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
  1720. return ~tf.reduce_all(finished_sequences)
  1721. def sample_body_fn(generated, finished_sequences, cur_len, model_kwargs):
  1722. if model_kwargs.get("past_key_values") is None or needs_full_input:
  1723. input_ids = generated[:, :cur_len]
  1724. else:
  1725. input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
  1726. model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
  1727. # forward pass to get next token logits
  1728. model_outputs = self(
  1729. **model_inputs,
  1730. return_dict=True,
  1731. output_attentions=output_attentions,
  1732. output_hidden_states=output_hidden_states,
  1733. )
  1734. next_token_logits = model_outputs.logits[:, -1]
  1735. # pre-process distribution
  1736. next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
  1737. next_tokens_scores = logits_warper(generated, next_tokens_scores, cur_len)
  1738. # Store scores, attentions and hidden_states when required
  1739. if not use_xla and return_dict_in_generate:
  1740. if output_scores:
  1741. scores.append(next_tokens_scores)
  1742. if output_attentions and self.config.is_encoder_decoder:
  1743. decoder_attentions.append(model_outputs.decoder_attentions)
  1744. elif output_attentions and not self.config.is_encoder_decoder:
  1745. decoder_attentions.append(model_outputs.attentions)
  1746. if self.config.is_encoder_decoder:
  1747. cross_attentions.append(model_outputs.cross_attentions)
  1748. if output_hidden_states and self.config.is_encoder_decoder:
  1749. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  1750. elif output_hidden_states and self.config.is_encoder_decoder:
  1751. decoder_hidden_states.append(model_outputs.hidden_states)
  1752. # sample
  1753. if seed is not None:
  1754. sample_seed = seed
  1755. else:
  1756. sample_seed = tf.experimental.numpy.random.randint(tf.int32.min, tf.int32.max, (2,), dtype=tf.int32)
  1757. next_tokens = tf.squeeze(
  1758. tf.random.stateless_categorical(
  1759. logits=next_tokens_scores, num_samples=1, seed=sample_seed, dtype=tf.int32
  1760. ),
  1761. axis=1,
  1762. )
  1763. if eos_token_id is not None:
  1764. if pad_token_id is None:
  1765. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  1766. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  1767. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  1768. next_token_is_eos = tf.math.reduce_any(
  1769. tf.equal(
  1770. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  1771. ),
  1772. axis=0,
  1773. )
  1774. finished_sequences = finished_sequences | next_token_is_eos
  1775. # update `generated` and `cur_len`
  1776. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  1777. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  1778. cur_len += 1
  1779. # update model_kwargs
  1780. if use_xla:
  1781. model_kwargs = self._update_model_kwargs_for_xla_generation(
  1782. model_outputs=model_outputs,
  1783. model_kwargs=model_kwargs,
  1784. cur_len=cur_len,
  1785. max_length=max_length,
  1786. batch_size=batch_size,
  1787. is_encoder_decoder=self.config.is_encoder_decoder,
  1788. batch_axis=cache_batch_axis,
  1789. )
  1790. else:
  1791. model_kwargs = self._update_model_kwargs_for_generation(
  1792. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  1793. )
  1794. # if we don't cache past_key_values key values we need the whole input
  1795. if model_kwargs.get("past_key_values", None) is None:
  1796. # let's throw out `past_key_values` since we don't want `None` tensors
  1797. model_kwargs.pop("past_key_values", None)
  1798. return generated, finished_sequences, cur_len, model_kwargs
  1799. # 5. run generation
  1800. # 1st generation step has to be run before to initialize `past_key_values`
  1801. generated, finished_sequences, cur_len, model_kwargs = sample_body_fn(
  1802. generated, finished_sequences, cur_len, model_kwargs
  1803. )
  1804. # 2-to-n generation steps can then be run in autoregressive fashion
  1805. # only in case 1st generation step does NOT yield EOS token though
  1806. maximum_iterations = max_length - cur_len
  1807. generated, _, cur_len, _ = tf.while_loop(
  1808. sample_cond_fn,
  1809. sample_body_fn,
  1810. (generated, finished_sequences, cur_len, model_kwargs),
  1811. maximum_iterations=maximum_iterations,
  1812. )
  1813. # 6. prepare outputs
  1814. if not use_xla:
  1815. # cut for backward compatibility
  1816. generated = generated[:, :cur_len]
  1817. if return_dict_in_generate:
  1818. if self.config.is_encoder_decoder:
  1819. # if model is an encoder-decoder, retrieve encoder attention weights
  1820. # and hidden states
  1821. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  1822. encoder_hidden_states = (
  1823. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  1824. )
  1825. scores = tuple(scores) if scores is not None else None
  1826. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  1827. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  1828. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  1829. return TFSampleEncoderDecoderOutput(
  1830. sequences=generated,
  1831. scores=scores,
  1832. encoder_attentions=encoder_attentions,
  1833. encoder_hidden_states=encoder_hidden_states,
  1834. decoder_attentions=decoder_attentions,
  1835. cross_attentions=cross_attentions,
  1836. decoder_hidden_states=decoder_hidden_states,
  1837. )
  1838. else:
  1839. return TFSampleDecoderOnlyOutput(
  1840. sequences=generated,
  1841. scores=scores,
  1842. attentions=decoder_attentions,
  1843. hidden_states=decoder_hidden_states,
  1844. )
  1845. else:
  1846. return generated
  1847. @staticmethod
  1848. def _gather_beams(nested, beam_indices, batch_axis=0):
  1849. """Gathers the beam slices indexed by beam_indices into new beam array."""
  1850. def gather_fn(tensor):
  1851. if batch_axis > 0:
  1852. # pushes all dimentions before the batch to the end, so we get (batch, beam_id, ...)
  1853. perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
  1854. tensor = tf.transpose(tensor, perm=perm)
  1855. gathered_tensor = tf.gather(params=tensor, indices=beam_indices, axis=1, batch_dims=1)
  1856. if batch_axis > 0:
  1857. # transposes back to the original dimensions
  1858. perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
  1859. perm = tf.math.invert_permutation(perm)
  1860. gathered_tensor = tf.transpose(gathered_tensor, perm=perm)
  1861. return gathered_tensor
  1862. return tf.nest.map_structure(gather_fn, nested)
  1863. def beam_search(
  1864. self,
  1865. input_ids: tf.Tensor,
  1866. do_sample: bool = False,
  1867. max_length: Optional[int] = None,
  1868. pad_token_id: Optional[int] = None,
  1869. eos_token_id: Optional[int] = None,
  1870. length_penalty: Optional[float] = None,
  1871. early_stopping: Optional[Union[bool, str]] = None,
  1872. logits_processor: Optional[TFLogitsProcessorList] = None,
  1873. logits_warper: Optional[TFLogitsProcessorList] = None,
  1874. num_return_sequences: Optional[int] = None,
  1875. output_attentions: Optional[bool] = None,
  1876. output_hidden_states: Optional[bool] = None,
  1877. output_scores: Optional[bool] = None,
  1878. return_dict_in_generate: Optional[bool] = None,
  1879. **model_kwargs,
  1880. ) -> Union[TFBeamSearchOutput, TFBeamSampleOutput, tf.Tensor]:
  1881. r"""
  1882. Generates sequences for models with a language modeling head using beam search. If `do_sample` is `False`, uses
  1883. a greedy approach, otherwise does multinomial sampling without replacement.
  1884. Parameters:
  1885. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  1886. The sequence used as a prompt for the generation.
  1887. do_sample (`bool`, *optional*, defaults to `False`):
  1888. Whether or not to use sampling ; use greedy decoding otherwise.
  1889. max_length (`int`, *optional*, defaults to 20):
  1890. The maximum length of the sequence to be generated.
  1891. pad_token_id (`int`, *optional*):
  1892. The id of the *padding* token.
  1893. eos_token_id (`Union[int, List[int]]`, *optional*):
  1894. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  1895. length_penalty (`float`, *optional*, defaults to 1.0):
  1896. Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent
  1897. to the sequence length, which in turn is used to divide the score of the sequence. Since the score is
  1898. the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences,
  1899. while `length_penalty` < 0.0 encourages shorter sequences.
  1900. early_stopping (`bool` or `str`, *optional*, defaults to `False`):
  1901. Controls the stopping condition for beam-based methods, like beam-search. It accepts the following
  1902. values: `True`, where the generation stops as soon as there are `num_beams` complete candidates;
  1903. `False`, where an heuristic is applied and the generation stops when is it very unlikely to find better
  1904. candidates; `"never"`, where the beam search procedure only stops when there cannot be better
  1905. candidates (canonical beam search algorithm).
  1906. logits_processor (`[TFLogitsProcessorList]`, *optional*):
  1907. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  1908. used to modify the prediction scores of the language modeling head applied at each generation step.
  1909. logits_warper (`TFLogitsProcessorList`, *optional*):
  1910. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  1911. used to warp the prediction score distribution of the language modeling head applied before multinomial
  1912. sampling at each generation step.
  1913. num_return_sequences(`int`, *optional*, defaults to 1):
  1914. The number of independently computed returned sequences for each element in the batch.
  1915. output_attentions (`bool`, *optional*, defaults to `False`):
  1916. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1917. returned tensors for more details.
  1918. output_hidden_states (`bool`, *optional*, defaults to `False`):
  1919. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1920. for more details.
  1921. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  1922. Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
  1923. model_kwargs:
  1924. Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
  1925. encoder-decoder model the kwargs should include `encoder_outputs`.
  1926. Return:
  1927. [`~generation.TFBeamSearchDecoderOnlyOutput`], [`~generation.TFBeamSearchEncoderDecoderOutput`] or
  1928. `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
  1929. [`~generation.TFBeamSearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
  1930. `return_dict_in_generate=True` or a [`~generation.TFBeamSearchEncoderDecoderOutput`] if
  1931. `model.config.is_encoder_decoder=True`.
  1932. Examples:
  1933. ```python
  1934. >>> from transformers import (
  1935. ... AutoTokenizer,
  1936. ... TFAutoModelForSeq2SeqLM,
  1937. ... TFLogitsProcessorList,
  1938. ... TFMinLengthLogitsProcessor,
  1939. ... )
  1940. >>> import tensorflow as tf
  1941. >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
  1942. >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
  1943. >>> encoder_input_str = "translate English to German: How old are you?"
  1944. >>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="tf").input_ids
  1945. >>> # lets run beam search using 3 beams
  1946. >>> num_beams = 3
  1947. >>> # define decoder start token ids
  1948. >>> input_ids = tf.ones((1, num_beams, 1), dtype=tf.int32)
  1949. >>> input_ids = input_ids * model.generation_config.decoder_start_token_id
  1950. >>> # add encoder_outputs to model keyword arguments
  1951. >>> encoder_outputs = model.get_encoder()(encoder_input_ids, return_dict=True)
  1952. >>> encoder_outputs.last_hidden_state = tf.repeat(
  1953. ... tf.expand_dims(encoder_outputs.last_hidden_state, axis=0), num_beams, axis=1
  1954. ... )
  1955. >>> model_kwargs = {"encoder_outputs": encoder_outputs}
  1956. >>> # instantiate logits processors
  1957. >>> logits_processor = TFLogitsProcessorList(
  1958. ... [TFMinLengthLogitsProcessor(5, eos_token_id=model.generation_config.eos_token_id)]
  1959. ... )
  1960. >>> outputs = model.beam_search(input_ids, logits_processor=logits_processor, **model_kwargs)
  1961. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  1962. ['Wie alt bist du?']
  1963. ```"""
  1964. def flatten_beam_dim(tensor, batch_axis=0):
  1965. """Flattens the first two dimensions of a non-scalar array."""
  1966. shape = shape_list(tensor)
  1967. return tf.reshape(
  1968. tensor,
  1969. shape[:batch_axis] + [shape[batch_axis] * shape[batch_axis + 1]] + shape[batch_axis + 2 :],
  1970. )
  1971. def unflatten_beam_dim(tensor, num_beams, batch_axis=0):
  1972. """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
  1973. shape = shape_list(tensor)
  1974. return tf.reshape(tensor, shape[:batch_axis] + [-1, num_beams] + shape[batch_axis + 1 :])
  1975. # 1. init beam_search values
  1976. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  1977. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  1978. max_length = max_length if max_length is not None else self.generation_config.max_length
  1979. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  1980. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  1981. if isinstance(eos_token_id, int):
  1982. eos_token_id = [eos_token_id]
  1983. num_return_sequences = (
  1984. num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
  1985. )
  1986. output_attentions = (
  1987. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  1988. )
  1989. output_hidden_states = (
  1990. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  1991. )
  1992. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  1993. return_dict_in_generate = (
  1994. return_dict_in_generate
  1995. if return_dict_in_generate is not None
  1996. else self.generation_config.return_dict_in_generate
  1997. )
  1998. length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
  1999. early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
  2000. use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
  2001. use_xla = not tf.executing_eagerly()
  2002. # TODO (Joao): fix cache format or find programatic way to detect cache index
  2003. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  2004. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  2005. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  2006. # some models, like XLNet, need more than the last token in the presence of past_key_values
  2007. needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
  2008. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  2009. all_scores = [] if (return_dict_in_generate and output_scores) else None
  2010. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2011. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2012. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  2013. # 3. init tensors to use for "xla-compileable" generate function
  2014. batch_size, num_beams, cur_len = shape_list(input_ids)
  2015. # store the prompt length of decoder
  2016. decoder_prompt_len = cur_len
  2017. # per batch, beam-item holding current token in loop, pre-populated with `pad_token_id`
  2018. input_ids_padding = tf.ones((batch_size, num_beams, max_length - cur_len), dtype=tf.int32) * (
  2019. pad_token_id or 0
  2020. )
  2021. running_sequences = tf.concat([input_ids, input_ids_padding], axis=-1)
  2022. sequences = tf.ones((batch_size, num_beams, max_length), dtype=tf.int32) * (pad_token_id or 0)
  2023. # per batch,beam-item state bit indicating if sentence has finished.
  2024. is_sent_finished = tf.zeros((batch_size, num_beams), dtype=tf.bool)
  2025. # per batch, beam-item score, logprobs
  2026. running_scores = tf.tile(
  2027. tf.expand_dims(tf.convert_to_tensor([0.0] + [-1.0e9] * (num_beams - 1)), axis=0), [batch_size, 1]
  2028. )
  2029. scores = tf.ones((batch_size, num_beams)) * -1.0e9
  2030. # per batch beam indices
  2031. running_beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
  2032. beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
  2033. # flatten beam dim
  2034. if "encoder_outputs" in model_kwargs:
  2035. model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
  2036. model_kwargs["encoder_outputs"]["last_hidden_state"]
  2037. )
  2038. if "attention_mask" in model_kwargs:
  2039. model_kwargs["attention_mask"] = flatten_beam_dim(model_kwargs["attention_mask"])
  2040. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  2041. # define stop-condition and auto-regressive function
  2042. def beam_search_cond_fn(
  2043. cur_len,
  2044. running_sequences,
  2045. running_scores,
  2046. running_beam_indices,
  2047. sequences,
  2048. scores,
  2049. beam_indices,
  2050. is_sent_finished,
  2051. decoder_prompt_len,
  2052. model_kwargs,
  2053. ):
  2054. """
  2055. Beam Search termination condition function -- halts the generation loop if any of these conditions becomes
  2056. False
  2057. """
  2058. # 1. is less than max length?
  2059. not_max_length_yet = cur_len < max_length
  2060. # 2. can the new beams still improve?
  2061. # early_stopping == False -> apply heuristic = always get the best score from `cur_len - decoder_prompt_len`. See the discussion
  2062. # below for more details.
  2063. # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
  2064. # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
  2065. # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
  2066. if early_stopping == "never" and length_penalty > 0.0:
  2067. best_running_score = running_scores[:, :1] / ((max_length - decoder_prompt_len) ** length_penalty)
  2068. else:
  2069. best_running_score = running_scores[:, :1] / (
  2070. tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty
  2071. )
  2072. worst_finished_score = tf.where(
  2073. is_sent_finished, tf.math.reduce_min(scores, axis=1, keepdims=True), -1.0e9
  2074. )
  2075. improvement_still_possible = tf.math.reduce_any(best_running_score > worst_finished_score)
  2076. # 3. is there still a beam that has not finished?
  2077. still_open_beam = ~(tf.math.reduce_all(is_sent_finished) & (early_stopping is True))
  2078. return not_max_length_yet & still_open_beam & improvement_still_possible
  2079. def beam_search_body_fn(
  2080. cur_len,
  2081. running_sequences,
  2082. running_scores,
  2083. running_beam_indices,
  2084. sequences,
  2085. scores,
  2086. beam_indices,
  2087. is_sent_finished,
  2088. decoder_prompt_len,
  2089. model_kwargs,
  2090. ):
  2091. """
  2092. Beam Search iterative update function -- each iteration adds a new token and updates the best sequences
  2093. seen so far
  2094. """
  2095. # 1. Forward current tokens
  2096. if model_kwargs.get("past_key_values") is None or needs_full_input:
  2097. input_ids = running_sequences[:, :, :cur_len]
  2098. else:
  2099. input_ids = tf.expand_dims(running_sequences[:, :, cur_len - 1], -1)
  2100. model_inputs = self.prepare_inputs_for_generation(
  2101. flatten_beam_dim(input_ids), use_cache=use_cache, **model_kwargs
  2102. )
  2103. model_outputs = self(
  2104. **model_inputs,
  2105. return_dict=True,
  2106. output_attentions=output_attentions,
  2107. output_hidden_states=output_hidden_states,
  2108. )
  2109. logits = unflatten_beam_dim(model_outputs.logits[:, -1], num_beams)
  2110. # 2. Compute log probs
  2111. # get log probabilities from logits, process logits with processors (*e.g.* min_length, ...), and
  2112. # add new logprobs to existing running logprobs scores.
  2113. log_probs = tf.nn.log_softmax(logits)
  2114. log_probs = logits_processor(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
  2115. log_probs = unflatten_beam_dim(log_probs, num_beams)
  2116. if do_sample:
  2117. log_probs = logits_warper(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
  2118. log_probs = unflatten_beam_dim(log_probs, num_beams)
  2119. log_probs_processed = log_probs
  2120. log_probs = log_probs + tf.expand_dims(running_scores, axis=2)
  2121. vocab_size = log_probs.shape[2]
  2122. log_probs = tf.reshape(log_probs, (batch_size, num_beams * vocab_size))
  2123. # Store scores, attentions and hidden_states when required
  2124. if not use_xla and return_dict_in_generate:
  2125. if output_scores:
  2126. all_scores.append(
  2127. logits_warper(
  2128. flatten_beam_dim(running_sequences),
  2129. flatten_beam_dim(log_probs_processed),
  2130. cur_len,
  2131. )
  2132. )
  2133. if output_attentions and self.config.is_encoder_decoder:
  2134. decoder_attentions.append(model_outputs.decoder_attentions)
  2135. elif output_attentions and not self.config.is_encoder_decoder:
  2136. decoder_attentions.append(model_outputs.attentions)
  2137. if self.config.is_encoder_decoder:
  2138. cross_attentions.append(model_outputs.cross_attentions)
  2139. if output_hidden_states and self.config.is_encoder_decoder:
  2140. decoder_hidden_states.append(model_outputs.decoder_hidden_states)
  2141. elif output_hidden_states and self.config.is_encoder_decoder:
  2142. decoder_hidden_states.append(model_outputs.hidden_states)
  2143. # 3. Retrieve top-K
  2144. # Each item in batch has num_beams * vocab_size candidate sequences. For each item, get the top 2*k
  2145. # candidates with the highest log-probabilities. We gather the top 2*K beams here so that even if the
  2146. # best K sequences reach EOS simultaneously, we have another K sequences remaining to continue the live
  2147. # beam search.
  2148. # Gather the top 2*K scores from _all_ beams.
  2149. # Gather 2*k top beams.
  2150. # Recover the beam index by floor division.
  2151. # Recover token id by modulo division and expand Id array for broadcasting.
  2152. # Update sequences for the 2*K top-k new sequences.
  2153. beams_to_keep = 2 * num_beams
  2154. if do_sample:
  2155. topk_indices = sample_without_replacement(log_probs, beams_to_keep)
  2156. topk_log_probs = tf.gather(log_probs, topk_indices, axis=1, batch_dims=1)
  2157. else:
  2158. topk_log_probs, topk_indices = tf.math.top_k(log_probs, k=beams_to_keep)
  2159. topk_current_beam_indices = topk_indices // vocab_size
  2160. topk_running_beam_indices = self._gather_beams(running_beam_indices, topk_current_beam_indices)
  2161. topk_running_sequences = self._gather_beams(running_sequences, topk_current_beam_indices)
  2162. topk_ids = topk_indices % vocab_size
  2163. # writes the new token
  2164. indices_batch = tf.repeat(tf.range(batch_size), [beams_to_keep])
  2165. indices_beam = tf.tile(tf.range(beams_to_keep), [batch_size])
  2166. update_indices = tf.stack(
  2167. [indices_batch, indices_beam, tf.broadcast_to(cur_len, [batch_size * beams_to_keep])], axis=-1
  2168. )
  2169. topk_sequences = tf.tensor_scatter_nd_update(
  2170. tensor=topk_running_sequences,
  2171. indices=update_indices,
  2172. updates=tf.reshape(topk_ids, [batch_size * beams_to_keep]),
  2173. )
  2174. # we want to store the beam indices with batch information -> real beam index = beam index % num beams
  2175. batch_modified_indices = topk_current_beam_indices + tf.broadcast_to(
  2176. tf.expand_dims(tf.range(batch_size) * num_beams, axis=1), topk_current_beam_indices.shape
  2177. )
  2178. update_indices = tf.stack(
  2179. [
  2180. indices_batch,
  2181. indices_beam,
  2182. tf.broadcast_to(cur_len - decoder_prompt_len, [batch_size * beams_to_keep]),
  2183. ],
  2184. axis=-1,
  2185. )
  2186. topk_beam_indices = tf.tensor_scatter_nd_update(
  2187. tensor=topk_running_beam_indices,
  2188. indices=update_indices,
  2189. updates=tf.reshape(batch_modified_indices, [batch_size * beams_to_keep]),
  2190. )
  2191. # 4. Check which sequences have ended
  2192. # Update current sequences: Did the top `num_beams` sequences reach an end marker?
  2193. # To prevent these just finished sequences from being added to the current sequences
  2194. # set of active beam search sequences, set their log probs to a very large negative value.
  2195. if eos_token_id is None:
  2196. eos_in_next_token = tf.zeros(topk_sequences[:, :, cur_len].shape, dtype=tf.bool)
  2197. else:
  2198. eos_in_next_token = tf.math.reduce_any(
  2199. tf.equal(
  2200. tf.broadcast_to(
  2201. topk_sequences[:, :, cur_len],
  2202. [len(eos_token_id)] + topk_sequences[:, :, cur_len].shape,
  2203. ),
  2204. tf.expand_dims(tf.expand_dims(eos_token_id, -1), -1),
  2205. ),
  2206. axis=0,
  2207. )
  2208. did_topk_just_finished = eos_in_next_token & tf.broadcast_to(
  2209. tf.concat((tf.ones((num_beams), dtype=tf.bool), tf.zeros((num_beams), dtype=tf.bool)), axis=0),
  2210. shape_list(eos_in_next_token),
  2211. )
  2212. # non-top `num_beams` eos tokens can't be used to finish a beam, but the others can't be used in the next
  2213. # running sentences either
  2214. running_topk_log_probs = topk_log_probs + tf.cast(eos_in_next_token, tf.float32) * -1.0e9
  2215. # 5. Get running sequences scores for next
  2216. # Determine the top k beam indices (from top 2*k beams) from log probs and gather top k beams
  2217. # (from top 2*k beams).
  2218. next_topk_indices = tf.math.top_k(running_topk_log_probs, k=num_beams)[1]
  2219. next_running_sequences, next_running_scores, next_running_beam_indices = self._gather_beams(
  2220. [topk_sequences, running_topk_log_probs, topk_beam_indices], next_topk_indices
  2221. )
  2222. # 6. Process topk logits
  2223. # Further process log probs:
  2224. # - add length penalty
  2225. # - make sure no scores can be added anymore if beam is full
  2226. # - make sure still running sequences cannot be chosen as finalized beam
  2227. topk_log_probs = topk_log_probs / (
  2228. tf.cast(cur_len + 1 - decoder_prompt_len, dtype=tf.float32) ** length_penalty
  2229. )
  2230. beams_in_batch_are_full = tf.broadcast_to(
  2231. tf.math.reduce_all(is_sent_finished, axis=-1, keepdims=True), shape_list(did_topk_just_finished)
  2232. ) & (early_stopping is True)
  2233. add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
  2234. topk_log_probs += tf.cast(add_penalty, tf.float32) * -1.0e9
  2235. # 7. Get scores, sequences, is sentence finished for next.
  2236. # Combine sequences, scores, and flags along the beam dimension and compare new finished sequence scores
  2237. # to existing finished scores and select the best from the new set of beams
  2238. merged_sequences = tf.concat([sequences, topk_sequences], axis=1)
  2239. merged_scores = tf.concat([scores, topk_log_probs], axis=1)
  2240. merged_beams = tf.concat([beam_indices, topk_beam_indices], axis=1)
  2241. merged_is_sent_finished = tf.concat([is_sent_finished, did_topk_just_finished], axis=1)
  2242. topk_merged_indices = tf.math.top_k(merged_scores, k=num_beams)[1]
  2243. next_sequences, next_scores, next_beam_indices, next_is_sent_finished = self._gather_beams(
  2244. [merged_sequences, merged_scores, merged_beams, merged_is_sent_finished], topk_merged_indices
  2245. )
  2246. # 8. Prepare data for the next iteration
  2247. # Determine the top k beam indices from the original set of all beams. With these, gather the top k
  2248. # beam-associated caches.
  2249. cur_len = cur_len + 1
  2250. if "past_key_values" in model_outputs:
  2251. cache = tf.nest.map_structure(
  2252. lambda tensor: unflatten_beam_dim(tensor, num_beams, batch_axis=cache_batch_axis),
  2253. model_outputs.past_key_values,
  2254. )
  2255. next_running_indices = self._gather_beams(topk_current_beam_indices, next_topk_indices)
  2256. next_cache = self._gather_beams(cache, next_running_indices, batch_axis=cache_batch_axis)
  2257. model_outputs["past_key_values"] = tf.nest.map_structure(
  2258. lambda tensor: flatten_beam_dim(tensor, batch_axis=cache_batch_axis), next_cache
  2259. )
  2260. if use_xla:
  2261. next_model_kwargs = self._update_model_kwargs_for_xla_generation(
  2262. model_outputs=model_outputs,
  2263. model_kwargs=model_kwargs,
  2264. cur_len=cur_len,
  2265. max_length=max_length,
  2266. batch_size=(batch_size * num_beams),
  2267. is_encoder_decoder=self.config.is_encoder_decoder,
  2268. batch_axis=cache_batch_axis,
  2269. )
  2270. else:
  2271. next_model_kwargs = self._update_model_kwargs_for_generation(
  2272. model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2273. )
  2274. # if we don't cache past_key_values key values we need the whole input
  2275. if model_kwargs.get("past_key_values", None) is None:
  2276. # let's throw out `past_key_values` since we don't want `None` tensors
  2277. model_kwargs.pop("past_key_values", None)
  2278. return (
  2279. cur_len,
  2280. next_running_sequences,
  2281. next_running_scores,
  2282. next_running_beam_indices,
  2283. next_sequences,
  2284. next_scores,
  2285. next_beam_indices,
  2286. next_is_sent_finished,
  2287. decoder_prompt_len,
  2288. next_model_kwargs,
  2289. )
  2290. # 5. run generation
  2291. # 1st generation step has to be run before to initialize `past_key_values` (if active)
  2292. (
  2293. cur_len,
  2294. running_sequences,
  2295. running_scores,
  2296. running_beam_indices,
  2297. sequences,
  2298. scores,
  2299. beam_indices,
  2300. is_sent_finished,
  2301. decoder_prompt_len,
  2302. model_kwargs,
  2303. ) = beam_search_body_fn(
  2304. cur_len,
  2305. running_sequences,
  2306. running_scores,
  2307. running_beam_indices,
  2308. sequences,
  2309. scores,
  2310. beam_indices,
  2311. is_sent_finished,
  2312. decoder_prompt_len,
  2313. model_kwargs,
  2314. )
  2315. # 2-to-n generation steps can then be run in autoregressive fashion (only in case 1st generation step does
  2316. # NOT yield EOS token though)
  2317. maximum_iterations = max_length - cur_len
  2318. (
  2319. cur_len,
  2320. running_sequences,
  2321. running_scores,
  2322. running_beam_indices,
  2323. sequences,
  2324. scores,
  2325. beam_indices,
  2326. is_sent_finished,
  2327. decoder_prompt_len,
  2328. _,
  2329. ) = tf.while_loop(
  2330. beam_search_cond_fn,
  2331. beam_search_body_fn,
  2332. (
  2333. cur_len,
  2334. running_sequences,
  2335. running_scores,
  2336. running_beam_indices,
  2337. sequences,
  2338. scores,
  2339. beam_indices,
  2340. is_sent_finished,
  2341. decoder_prompt_len,
  2342. model_kwargs,
  2343. ),
  2344. maximum_iterations=maximum_iterations,
  2345. )
  2346. # 6. prepare outputs
  2347. # Account for the edge-case where there are no finished sequences for a particular batch item. If so, return
  2348. # running sequences for that batch item.
  2349. none_finished = tf.math.reduce_any(is_sent_finished, axis=1)
  2350. sequences = tf.where(none_finished[:, None, None], sequences, running_sequences)
  2351. beam_indices = tf.where(none_finished[:, None, None], beam_indices, running_beam_indices)
  2352. # Apply the length penalty so that running scores match the finalized scores if they are used
  2353. running_scores = running_scores / (tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty)
  2354. scores = tf.where(none_finished[:, None], scores, running_scores)
  2355. # Take best beams for each batch (the score is sorted in descending order)
  2356. sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
  2357. scores = flatten_beam_dim(scores[:, :num_return_sequences])
  2358. beam_indices = flatten_beam_dim(beam_indices[:, :num_return_sequences, :])
  2359. if not use_xla:
  2360. # Cut for backward compatibility
  2361. sequences = sequences[:, :cur_len]
  2362. beam_indices = beam_indices[:, : cur_len - decoder_prompt_len]
  2363. if return_dict_in_generate:
  2364. if self.config.is_encoder_decoder:
  2365. # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
  2366. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2367. encoder_hidden_states = (
  2368. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2369. )
  2370. output_cls = TFBeamSampleEncoderDecoderOutput if do_sample else TFBeamSearchEncoderDecoderOutput
  2371. return output_cls(
  2372. sequences=sequences,
  2373. sequences_scores=scores,
  2374. scores=all_scores,
  2375. beam_indices=beam_indices,
  2376. encoder_attentions=encoder_attentions,
  2377. encoder_hidden_states=encoder_hidden_states,
  2378. decoder_attentions=decoder_attentions,
  2379. cross_attentions=cross_attentions,
  2380. decoder_hidden_states=decoder_hidden_states,
  2381. )
  2382. else:
  2383. output_cls = TFBeamSampleDecoderOnlyOutput if do_sample else TFBeamSearchDecoderOnlyOutput
  2384. return output_cls(
  2385. sequences=sequences,
  2386. sequences_scores=scores,
  2387. scores=all_scores,
  2388. beam_indices=beam_indices,
  2389. attentions=decoder_attentions,
  2390. hidden_states=decoder_hidden_states,
  2391. )
  2392. else:
  2393. return sequences
  2394. def contrastive_search(
  2395. self,
  2396. input_ids: tf.Tensor,
  2397. top_k: Optional[int] = 1,
  2398. penalty_alpha: Optional[float] = 0,
  2399. logits_processor: Optional[TFLogitsProcessorList] = None,
  2400. logits_warper: Optional[TFLogitsProcessorList] = None,
  2401. max_length: Optional[int] = None,
  2402. pad_token_id: Optional[int] = None,
  2403. eos_token_id: Optional[int] = None,
  2404. output_attentions: Optional[bool] = None,
  2405. output_hidden_states: Optional[bool] = None,
  2406. output_scores: Optional[bool] = None,
  2407. return_dict_in_generate: Optional[bool] = None,
  2408. **model_kwargs,
  2409. ) -> Union[TFContrastiveSearchOutput, tf.Tensor]:
  2410. r"""
  2411. Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
  2412. be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
  2413. Parameters:
  2414. input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
  2415. The sequence used as a prompt for the generation.
  2416. top_k (`int`, *optional*, defaults to 1):
  2417. The size of the candidate set that is used to re-rank for contrastive search
  2418. penalty_alpha (`float`, *optional*, defaults to 0):
  2419. The degeneration penalty for contrastive search; activate when it is larger than 0
  2420. logits_processor (`TFLogitsProcessorList`, *optional*):
  2421. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
  2422. used to modify the prediction scores of the language modeling head applied at each generation step.
  2423. logits_warper (`TFLogitsProcessorList`, *optional*):
  2424. An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
  2425. used to warp the prediction score distribution of the language modeling head applied before multinomial
  2426. sampling at each generation step.
  2427. max_length (`int`, *optional*, defaults to 20):
  2428. The maximum length of the sequence to be generated.
  2429. pad_token_id (`int`, *optional*):
  2430. The id of the *padding* token.
  2431. eos_token_id (`Union[int, List[int]]`, *optional*):
  2432. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  2433. output_attentions (`bool`, *optional*, defaults to `False`):
  2434. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  2435. returned tensors for more details.
  2436. output_hidden_states (`bool`, *optional*, defaults to `False`):
  2437. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  2438. for more details.
  2439. output_scores (`bool`, *optional*, defaults to `False`):
  2440. Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
  2441. return_dict_in_generate (`bool`, *optional*, defaults to `False`):
  2442. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  2443. model_kwargs:
  2444. Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
  2445. model is an encoder-decoder model the kwargs should include `encoder_outputs`.
  2446. Return:
  2447. [`~generation.TFContrastiveSearchDecoderOnlyOutput`],
  2448. [`~generation.TFContrastiveSearchEncoderDecoderOutput`] or `tf.Tensor`: A `tf.Tensor` containing the
  2449. generated tokens (default behaviour) or a [`~generation.TFContrastiveySearchDecoderOnlyOutput`] if
  2450. `model.config.is_encoder_decoder=False` and `return_dict_in_generate=True` or a
  2451. [`~generation.TFContrastiveSearchEncoderDecoderOutput`] if `model.config.is_encoder_decoder=True`.
  2452. Examples:
  2453. ```python
  2454. >>> from transformers import AutoTokenizer, TFAutoModelForCausalLM
  2455. >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
  2456. >>> model = TFAutoModelForCausalLM.from_pretrained("facebook/opt-125m")
  2457. >>> # set pad_token_id to eos_token_id because OPT does not have a PAD token
  2458. >>> model.config.pad_token_id = model.config.eos_token_id
  2459. >>> input_prompt = "DeepMind Company is"
  2460. >>> input_ids = tokenizer(input_prompt, return_tensors="tf")
  2461. >>> outputs = model.contrastive_search(**input_ids, penalty_alpha=0.6, top_k=4, max_length=64)
  2462. >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  2463. ['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']
  2464. ```"""
  2465. def gather_best_candidate(nested, selected_idx_stacked, batch_axis=0):
  2466. """Gathers the slices indexed by selected_idx_stacked from a potentially nested structure of tensors."""
  2467. def gather_fn(tensor):
  2468. gathered_tensor = tf.gather(params=tensor, indices=selected_idx_stacked, axis=batch_axis)
  2469. return gathered_tensor
  2470. return tf.nest.map_structure(gather_fn, nested)
  2471. # 1. init greedy_search values
  2472. logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
  2473. logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
  2474. max_length = max_length if max_length is not None else self.generation_config.max_length
  2475. pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
  2476. eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
  2477. if isinstance(eos_token_id, int):
  2478. eos_token_id = [eos_token_id]
  2479. output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
  2480. output_attentions = (
  2481. output_attentions if output_attentions is not None else self.generation_config.output_attentions
  2482. )
  2483. output_hidden_states = (
  2484. output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
  2485. )
  2486. return_dict_in_generate = (
  2487. return_dict_in_generate
  2488. if return_dict_in_generate is not None
  2489. else self.generation_config.return_dict_in_generate
  2490. )
  2491. use_cache = True # In contrastive search, we always use cache
  2492. model_kwargs.pop("use_cache", None)
  2493. use_xla = not tf.executing_eagerly()
  2494. # TODO (Joao): fix cache format or find programatic way to detect cache index
  2495. # GPT2 and other models has a slightly different cache structure, with a different batch axis
  2496. model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
  2497. cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
  2498. # 2. init `attentions`, `hidden_states`, and `scores` tuples
  2499. scores = [] if (return_dict_in_generate and output_scores) else None
  2500. decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2501. cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
  2502. decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
  2503. # 3. init tensors to use for "xla-compileable" generate function
  2504. batch_size, cur_len = shape_list(input_ids)
  2505. # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
  2506. input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
  2507. generated = tf.concat([input_ids, input_ids_padding], axis=-1)
  2508. finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
  2509. # 4. define "xla-compile-able" stop-condition and auto-regressive function
  2510. # define condition fn
  2511. def contrastive_search_cond_fn(
  2512. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2513. ):
  2514. """state termination condition fn."""
  2515. return ~tf.reduce_all(finished_sequences)
  2516. # define condition fn
  2517. def contrastive_search_body_fn(
  2518. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2519. ):
  2520. """state update fn."""
  2521. # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
  2522. # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
  2523. if model_kwargs.get("past_key_values") is None:
  2524. # prepare inputs
  2525. model_inputs = self.prepare_inputs_for_generation(
  2526. generated[:, :cur_len], use_cache=use_cache, **model_kwargs
  2527. )
  2528. # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
  2529. # the `encoder_outputs`
  2530. outputs = self(
  2531. **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
  2532. )
  2533. # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
  2534. # previous tokens)
  2535. if self.config.is_encoder_decoder:
  2536. last_hidden_states = outputs.decoder_hidden_states[-1]
  2537. else:
  2538. last_hidden_states = outputs.hidden_states[-1]
  2539. # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
  2540. # iterations (with fixed shapes)
  2541. if use_xla:
  2542. last_hidden_states = tf.pad(last_hidden_states, [[0, 0], [0, max_length - cur_len], [0, 0]])
  2543. # next logit for contrastive search to select top-k candidate tokens
  2544. logit_for_next_step = outputs.logits[:, -1, :]
  2545. if use_xla:
  2546. model_kwargs = self._update_model_kwargs_for_xla_generation(
  2547. model_outputs=outputs,
  2548. model_kwargs=model_kwargs,
  2549. cur_len=cur_len,
  2550. max_length=max_length,
  2551. batch_size=batch_size,
  2552. is_encoder_decoder=self.config.is_encoder_decoder,
  2553. batch_axis=cache_batch_axis,
  2554. )
  2555. else:
  2556. model_kwargs = self._update_model_kwargs_for_generation(
  2557. outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2558. )
  2559. # Expands model inputs top_k times, for batched forward passes (akin to beam search).
  2560. _, model_kwargs = self._expand_inputs_for_generation(
  2561. expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
  2562. )
  2563. past_key_values = model_kwargs.get("past_key_values")
  2564. if past_key_values is None:
  2565. raise ValueError(
  2566. f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
  2567. "for contrastive search."
  2568. )
  2569. elif (
  2570. not isinstance(past_key_values[0], (tuple, tf.Tensor))
  2571. or past_key_values[0][0].shape[0] != batch_size
  2572. ):
  2573. raise ValueError(
  2574. f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
  2575. "used for contrastive search without further modifications."
  2576. )
  2577. else:
  2578. logit_for_next_step = next_step_cached_variables["logit_for_next_step"]
  2579. last_hidden_states = next_step_cached_variables["last_hidden_states"]
  2580. outputs = next_step_cached_variables["outputs"]
  2581. # contrastive_search main logic start:
  2582. # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
  2583. # degeneration penalty
  2584. logit_for_next_step = logits_processor(generated, logit_for_next_step, cur_len)
  2585. logit_for_next_step = logits_warper(generated, logit_for_next_step, cur_len)
  2586. next_probs = stable_softmax(logit_for_next_step, axis=-1)
  2587. top_k_probs, top_k_ids = tf.math.top_k(next_probs, k=top_k)
  2588. # Store scores, attentions and hidden_states when required
  2589. if not use_xla and return_dict_in_generate:
  2590. if output_scores:
  2591. scores.append(logit_for_next_step)
  2592. if output_attentions and self.config.is_encoder_decoder:
  2593. decoder_attentions.append(outputs.decoder_attentions)
  2594. elif output_attentions and not self.config.is_encoder_decoder:
  2595. decoder_attentions.append(outputs.attentions)
  2596. if self.config.is_encoder_decoder:
  2597. cross_attentions.append(outputs.cross_attentions)
  2598. if output_hidden_states and self.config.is_encoder_decoder:
  2599. decoder_hidden_states.append(outputs.decoder_hidden_states)
  2600. elif output_hidden_states and self.config.is_encoder_decoder:
  2601. decoder_hidden_states.append(outputs.hidden_states)
  2602. # Replicates the new past_key_values to match the `top_k` candidates
  2603. model_kwargs["past_key_values"] = tf.nest.map_structure(
  2604. lambda tensor: tf.repeat(tensor, top_k, axis=cache_batch_axis), model_kwargs["past_key_values"]
  2605. )
  2606. # compute the candidate tokens by the language model and collects their hidden_states
  2607. next_model_inputs = self.prepare_inputs_for_generation(
  2608. tf.reshape(top_k_ids, [-1, 1]), use_cache=use_cache, **model_kwargs
  2609. )
  2610. outputs = self(
  2611. **next_model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
  2612. )
  2613. next_past_key_values = self._extract_past_from_model_output(outputs)
  2614. logits = outputs.logits[:, -1, :]
  2615. # name is different for encoder-decoder and decoder-only models
  2616. if self.config.is_encoder_decoder:
  2617. next_hidden = outputs.decoder_hidden_states[-1]
  2618. full_hidden_states = outputs.decoder_hidden_states
  2619. else:
  2620. next_hidden = outputs.hidden_states[-1]
  2621. full_hidden_states = outputs.hidden_states
  2622. context_hidden = tf.repeat(last_hidden_states[:, :cur_len, :], top_k, axis=0)
  2623. # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
  2624. # model confidence
  2625. selected_idx = _ranking_fast(context_hidden, next_hidden, top_k_probs, penalty_alpha, top_k)
  2626. # converts indices to a dimension of top_k to the stacked top_k * batch_size dimension, for indexing
  2627. # without a need to reshape on tensors that have these two dimensions stacked
  2628. selected_idx_stacked = selected_idx + tf.range(selected_idx.shape[0], dtype=tf.int64) * top_k
  2629. # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
  2630. # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
  2631. # (model confidence minus degeneration penalty); (6) decoder hidden_states
  2632. next_tokens = tf.gather(top_k_ids, selected_idx, axis=1, batch_dims=1)
  2633. next_hidden = gather_best_candidate(next_hidden, selected_idx_stacked)
  2634. # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
  2635. # iterations (with fixed shapes)
  2636. if use_xla:
  2637. last_hidden_states = dynamic_update_slice(last_hidden_states, next_hidden, [0, cur_len, 0])
  2638. else:
  2639. last_hidden_states = tf.concat([last_hidden_states, next_hidden], axis=1)
  2640. next_decoder_hidden_states = gather_best_candidate(full_hidden_states, selected_idx_stacked)
  2641. next_past_key_values = gather_best_candidate(
  2642. next_past_key_values, selected_idx_stacked, batch_axis=cache_batch_axis
  2643. )
  2644. logit_for_next_step = gather_best_candidate(logits, selected_idx_stacked)
  2645. # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
  2646. if self.config.is_encoder_decoder:
  2647. next_step_cross_attentions = ()
  2648. next_step_decoder_attentions = ()
  2649. if output_attentions:
  2650. next_step_cross_attentions = gather_best_candidate(outputs.cross_attentions, selected_idx_stacked)
  2651. next_step_decoder_attentions = gather_best_candidate(
  2652. outputs.decoder_attentions, selected_idx_stacked
  2653. )
  2654. outputs = TFSeq2SeqLMOutput(
  2655. past_key_values=next_past_key_values,
  2656. decoder_hidden_states=next_decoder_hidden_states,
  2657. decoder_attentions=next_step_decoder_attentions or None,
  2658. cross_attentions=next_step_cross_attentions or None,
  2659. )
  2660. else:
  2661. next_step_attentions = ()
  2662. if output_attentions:
  2663. next_step_attentions = gather_best_candidate(outputs.attentions, selected_idx_stacked)
  2664. outputs = TFCausalLMOutputWithPast(
  2665. past_key_values=next_past_key_values,
  2666. hidden_states=next_decoder_hidden_states,
  2667. attentions=next_step_attentions or None,
  2668. )
  2669. # contrastive_search main logic end
  2670. if eos_token_id is not None:
  2671. if pad_token_id is None:
  2672. raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
  2673. unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
  2674. next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
  2675. next_token_is_eos = tf.math.reduce_any(
  2676. tf.equal(
  2677. tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
  2678. ),
  2679. axis=0,
  2680. )
  2681. finished_sequences = finished_sequences | next_token_is_eos
  2682. # update `generated` and `cur_len`
  2683. update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
  2684. generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
  2685. cur_len += 1
  2686. if use_xla:
  2687. # NOTE: 1) relative to other generation strategies, contrastive search is always running forward
  2688. # passes one step ahead -- hence the `cur_len=cur_len + 1`; 2) the attention mask here is expanded from
  2689. # [batch_size, ...] to [batch_size*top_k, ...] -- hence the `batch_size=batch_size * top_k`
  2690. model_kwargs = self._update_model_kwargs_for_xla_generation(
  2691. model_outputs=outputs,
  2692. model_kwargs=model_kwargs,
  2693. cur_len=cur_len + 1,
  2694. max_length=max_length,
  2695. batch_size=batch_size * top_k,
  2696. is_encoder_decoder=self.config.is_encoder_decoder,
  2697. batch_axis=cache_batch_axis,
  2698. )
  2699. else:
  2700. model_kwargs = self._update_model_kwargs_for_generation(
  2701. outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  2702. )
  2703. next_step_cached_variables = {
  2704. "logit_for_next_step": logit_for_next_step,
  2705. "last_hidden_states": last_hidden_states,
  2706. "outputs": outputs,
  2707. }
  2708. return generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
  2709. # 5. run generation
  2710. # 1st generation step has to be run before to initialize `past_key_values`
  2711. generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables = contrastive_search_body_fn(
  2712. generated, finished_sequences, cur_len, model_kwargs, None
  2713. )
  2714. # 2-to-n generation steps can then be run in autoregressive fashion
  2715. # only in case 1st generation step does NOT yield EOS token though
  2716. maximum_iterations = max_length - cur_len
  2717. generated, _, cur_len, _, _ = tf.while_loop(
  2718. contrastive_search_cond_fn,
  2719. contrastive_search_body_fn,
  2720. (generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables),
  2721. maximum_iterations=maximum_iterations,
  2722. )
  2723. # 6. prepare outputs
  2724. if not use_xla:
  2725. # cut for backward compatibility
  2726. generated = generated[:, :cur_len]
  2727. if return_dict_in_generate:
  2728. if self.config.is_encoder_decoder:
  2729. # if model is an encoder-decoder, retrieve encoder attention weights
  2730. # and hidden states
  2731. encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
  2732. encoder_hidden_states = (
  2733. model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
  2734. )
  2735. scores = tuple(scores) if scores is not None else None
  2736. decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
  2737. cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
  2738. decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
  2739. return TFContrastiveSearchEncoderDecoderOutput(
  2740. sequences=generated,
  2741. scores=scores,
  2742. encoder_attentions=encoder_attentions,
  2743. encoder_hidden_states=encoder_hidden_states,
  2744. decoder_attentions=decoder_attentions,
  2745. cross_attentions=cross_attentions,
  2746. decoder_hidden_states=decoder_hidden_states,
  2747. )
  2748. else:
  2749. return TFContrastiveSearchDecoderOnlyOutput(
  2750. sequences=generated,
  2751. scores=scores,
  2752. attentions=decoder_attentions,
  2753. hidden_states=decoder_hidden_states,
  2754. )
  2755. else:
  2756. return generated
  2757. def scatter_values_on_batch_indices(values, batch_indices):
  2758. shape = shape_list(batch_indices)
  2759. # broadcast batch dim to shape
  2760. broad_casted_batch_dims = tf.reshape(tf.broadcast_to(tf.expand_dims(tf.range(shape[0]), axis=-1), shape), [1, -1])
  2761. # transform batch_indices to pair_indices
  2762. pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0))
  2763. # scatter values to pair indices
  2764. return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), shape)
  2765. def sample_without_replacement(logits, num_samples):
  2766. """
  2767. categorical sampling without replacement is currently not implemented the gumbel-max trick will do for now see
  2768. https://github.com/tensorflow/tensorflow/issues/9260 for more info
  2769. """
  2770. z = -tf.math.log(-tf.math.log(tf.random.uniform(shape_list(logits), 0, 1)))
  2771. _, indices = tf.nn.top_k(logits + z, num_samples)
  2772. return indices
  2773. def _ranking_fast(
  2774. context_hidden: tf.Tensor,
  2775. next_hidden: tf.Tensor,
  2776. next_top_k_probs: tf.Tensor,
  2777. alpha: float,
  2778. beam_width: int,
  2779. ) -> tf.Tensor:
  2780. """
  2781. Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
  2782. in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
  2783. row in the batch.
  2784. """
  2785. norm_context_hidden = context_hidden / tf.norm(context_hidden, axis=2, keepdims=True)
  2786. norm_next_hidden = next_hidden / tf.norm(next_hidden, axis=2, keepdims=True)
  2787. cosine_matrix = tf.squeeze(tf.linalg.matmul(norm_context_hidden, norm_next_hidden, transpose_b=True), axis=-1)
  2788. degeneration_penalty = tf.reduce_max(cosine_matrix, axis=-1)
  2789. next_top_k_probs = tf.reshape(next_top_k_probs, shape=[-1])
  2790. contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
  2791. contrastive_score = tf.reshape(contrastive_score, shape=[-1, beam_width])
  2792. selected_idx = tf.argmax(contrastive_score, axis=1)
  2793. return selected_idx